Merge branch 'master' into BAEL-1711-move-code-snippets
This commit is contained in:
commit
7267803efc
|
@ -34,3 +34,9 @@ CI - Jenkins
|
|||
================================
|
||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
||||
|
||||
### Relevant Articles:
|
||||
================================
|
||||
|
||||
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
|
||||
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
|
||||
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
|
||||
|
|
|
@ -20,4 +20,5 @@
|
|||
- [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)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
|
||||
- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
|
||||
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
|
||||
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)
|
||||
|
|
|
@ -18,10 +18,29 @@
|
|||
<artifactId>auto-value</artifactId>
|
||||
<version>${auto-value.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.auto.factory</groupId>
|
||||
<artifactId>auto-factory</artifactId>
|
||||
<version>${auto-factory.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
<version>${guice.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<auto-value.version>1.3</auto-value.version>
|
||||
<auto-factory.version>1.0-beta5</auto-factory.version>
|
||||
<guice.version>4.2.0</guice.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.autofactory;
|
||||
|
||||
import com.baeldung.autofactory.model.Camera;
|
||||
import com.baeldung.autofactory.model.Phone;
|
||||
import com.baeldung.autofactory.model.PhoneFactory;
|
||||
import com.baeldung.autofactory.modules.SonyCameraModule;
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
|
||||
public class App {
|
||||
|
||||
public static void main(String[] args) {
|
||||
PhoneFactory phoneFactory = new PhoneFactory(() -> new Camera("Unknown", "XXX"));
|
||||
Phone simplePhone = phoneFactory.create("other parts");
|
||||
|
||||
Injector injector = Guice.createInjector(new SonyCameraModule());
|
||||
PhoneFactory injectedFactory = injector.getInstance(PhoneFactory.class);
|
||||
Phone xperia = injectedFactory.create("Xperia");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung.autofactory;
|
||||
|
||||
import com.baeldung.autofactory.custom.SmartPhone;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public interface CustomStorage {
|
||||
|
||||
SmartPhone customROMInGB(int romSize);
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.autofactory.custom;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public abstract class AbstractFactory {
|
||||
|
||||
abstract CustomPhone newInstance(String brand);
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.autofactory.custom;
|
||||
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
@AutoFactory(extending = AbstractFactory.class)
|
||||
public class CustomPhone {
|
||||
|
||||
private final String brand;
|
||||
|
||||
public CustomPhone(String brand) {
|
||||
this.brand = brand;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.autofactory.custom;
|
||||
|
||||
import com.baeldung.autofactory.CustomStorage;
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
@AutoFactory(className = "SamsungFactory", allowSubclasses = true, implementing = CustomStorage.class)
|
||||
public class SmartPhone {
|
||||
|
||||
private int romSize;
|
||||
|
||||
public SmartPhone(int romSize) {
|
||||
this.romSize = romSize;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.autofactory.model;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class Camera {
|
||||
|
||||
private final String manufacturer;
|
||||
private final String serial;
|
||||
|
||||
public Camera(String manufacturer, String serial) {
|
||||
this.manufacturer = manufacturer;
|
||||
this.serial = serial;
|
||||
}
|
||||
|
||||
public String getManufacturer() {
|
||||
return manufacturer;
|
||||
}
|
||||
|
||||
public String getSerial() {
|
||||
return serial;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.autofactory.model;
|
||||
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
import com.google.auto.factory.Provided;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class ClassicPhone {
|
||||
|
||||
private final String dialpad;
|
||||
private final String ringer;
|
||||
private String otherParts;
|
||||
|
||||
@AutoFactory
|
||||
public ClassicPhone(@Provided String dialpad, @Provided String ringer) {
|
||||
this.dialpad = dialpad;
|
||||
this.ringer = ringer;
|
||||
}
|
||||
|
||||
@AutoFactory
|
||||
public ClassicPhone(String otherParts) {
|
||||
this("defaultDialPad", "defaultRinger");
|
||||
this.otherParts = otherParts;
|
||||
}
|
||||
|
||||
public String getDialpad() {
|
||||
return dialpad;
|
||||
}
|
||||
|
||||
public String getRinger() {
|
||||
return ringer;
|
||||
}
|
||||
|
||||
public String getOtherParts() {
|
||||
return otherParts;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.autofactory.model;
|
||||
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
import com.google.auto.factory.Provided;
|
||||
|
||||
import javax.inject.Named;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
@AutoFactory
|
||||
public class Phone {
|
||||
|
||||
private Camera camera;
|
||||
private String otherParts;
|
||||
|
||||
public Phone(@Provided @Named("Sony") Camera camera, String otherParts) {
|
||||
this.camera = camera;
|
||||
this.otherParts = otherParts;
|
||||
}
|
||||
|
||||
/* required when used as a base class for AutoFactory */
|
||||
public Phone() {
|
||||
}
|
||||
|
||||
public Camera getCamera() {
|
||||
return camera;
|
||||
}
|
||||
|
||||
public String getOtherParts() {
|
||||
return otherParts;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.autofactory.modules;
|
||||
|
||||
import com.baeldung.autofactory.model.Camera;
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.Provides;
|
||||
|
||||
import javax.inject.Named;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class SonyCameraModule extends AbstractModule {
|
||||
|
||||
private static int SONY_CAMERA_SERIAL = 1;
|
||||
|
||||
@Named("Sony")
|
||||
@Provides
|
||||
Camera cameraProvider() {
|
||||
return new Camera("Sony", String.format("%03d", SONY_CAMERA_SERIAL++));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.autofactory.provided;
|
||||
|
||||
import com.google.auto.factory.AutoFactory;
|
||||
import com.google.auto.factory.Provided;
|
||||
import javafx.scene.Camera;
|
||||
|
||||
import javax.inject.Provider;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
@AutoFactory
|
||||
public class IntermediateAssembler {
|
||||
|
||||
private final Provider<Camera> camera;
|
||||
private final String otherParts;
|
||||
|
||||
public IntermediateAssembler(@Provided Provider<Camera> camera, String otherParts) {
|
||||
this.camera = camera;
|
||||
this.otherParts = otherParts;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.autofactory.provider;
|
||||
|
||||
import com.baeldung.autofactory.model.Camera;
|
||||
import com.google.inject.Provider;
|
||||
|
||||
/**
|
||||
* @author aiet
|
||||
*/
|
||||
public class SonyCameraProvider implements Provider<Camera> {
|
||||
|
||||
private static int sonyCameraSerial = 1;
|
||||
|
||||
@Override
|
||||
public Camera get() {
|
||||
return new Camera("Sony", String.format("%03d", sonyCameraSerial++));
|
||||
}
|
||||
|
||||
}
|
|
@ -5,4 +5,8 @@
|
|||
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
|
||||
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
|
||||
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
|
||||
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
|
||||
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
|
||||
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
|
||||
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
|
||||
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
## Relevant articles:
|
||||
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)
|
||||
- [Code Analysis with SonarQube](http://www.baeldung.com/sonar-qube)
|
||||
|
|
10
cdi/pom.xml
10
cdi/pom.xml
|
@ -8,16 +8,12 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-spring</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
|
|
@ -28,12 +28,6 @@
|
|||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
|
|
|
@ -0,0 +1,61 @@
|
|||
package com.baeldung.java10;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Java10FeaturesUnitTest {
|
||||
|
||||
private List<Integer> someIntList;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
someIntList = new ArrayList<>();
|
||||
|
||||
someIntList.add(1);
|
||||
someIntList.add(2);
|
||||
someIntList.add(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVarInitWithString_thenGetStringTypeVar() {
|
||||
var message = "Hello, Java 10";
|
||||
assertTrue(message instanceof String);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenVarInitWithAnonymous_thenGetAnonymousType() {
|
||||
var obj = new Object() {};
|
||||
assertFalse(obj.getClass().equals(Object.class));
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenModifyCopyOfList_thenThrowsException() {
|
||||
List<Integer> copyList = List.copyOf(someIntList);
|
||||
copyList.add(4);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenModifyToUnmodifiableList_thenThrowsException() {
|
||||
List<Integer> evenList = someIntList.stream()
|
||||
.filter(i -> i % 2 == 0)
|
||||
.collect(Collectors.toUnmodifiableList());
|
||||
evenList.add(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListContainsInteger_OrElseThrowReturnsInteger() {
|
||||
Integer firstEven = someIntList.stream()
|
||||
.filter(i -> i % 2 == 0)
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
is(firstEven).equals(Integer.valueOf(2));
|
||||
}
|
||||
}
|
|
@ -44,3 +44,10 @@
|
|||
- [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)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||
|
||||
|
|
|
@ -9,17 +9,12 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.hashtable;
|
||||
|
||||
public class Word {
|
||||
private String name;
|
||||
|
||||
public Word(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof Word))
|
||||
return false;
|
||||
|
||||
Word word = (Word) o;
|
||||
return word.getName().equals(this.name) ? true : false;
|
||||
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,274 @@
|
|||
package com.baeldung.hashtable;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HashtableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPutAndGet_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
|
||||
String definition = table.get(word);
|
||||
|
||||
assertEquals("an animal", definition);
|
||||
|
||||
definition = table.remove(word);
|
||||
|
||||
assertEquals("an animal", definition);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThesameInstanceOfKey_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
String extracted = table.get(word);
|
||||
assertEquals("an animal", extracted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEqualsOverridden_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
String extracted = table.get(new Word("cat"));
|
||||
assertEquals("an animal", extracted);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenNullKey_thenException() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(null, "an animal");
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenIterate_thenFailFast() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "an animal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
Word key = it.next();
|
||||
System.out.println(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEnumerate_thenNotFailFast() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("1"), "one");
|
||||
table.put(new Word("2"), "two");
|
||||
table.put(new Word("3"), "three");
|
||||
table.put(new Word("4"), "four");
|
||||
table.put(new Word("5"), "five");
|
||||
table.put(new Word("6"), "six");
|
||||
table.put(new Word("7"), "seven");
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
Word key = enumKey.nextElement();
|
||||
System.out.println(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddElements_thenIterationOrderUnpredicable() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("1"), "one");
|
||||
table.put(new Word("2"), "two");
|
||||
table.put(new Word("3"), "three");
|
||||
table.put(new Word("4"), "four");
|
||||
table.put(new Word("5"), "five");
|
||||
table.put(new Word("6"), "six");
|
||||
table.put(new Word("7"), "seven");
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Word, String> entry = it.next();
|
||||
System.out.println(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetOrDefault_thenDefaultGot() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
Word key = new Word("dog");
|
||||
String definition;
|
||||
|
||||
// old way
|
||||
/* if (table.containsKey(key)) {
|
||||
definition = table.get(key);
|
||||
} else {
|
||||
definition = "not found";
|
||||
}*/
|
||||
|
||||
// new way
|
||||
definition = table.getOrDefault(key, "not found");
|
||||
|
||||
assertThat(definition, is("not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutifAbsent_thenNotRewritten() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
String definition = "an animal";
|
||||
// old way
|
||||
/* if (!table.containsKey(new Word("cat"))) {
|
||||
table.put(new Word("cat"), definition);
|
||||
}*/
|
||||
// new way
|
||||
table.putIfAbsent(new Word("cat"), definition);
|
||||
|
||||
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovePair_thenCheckKeyAndValue() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
// old way
|
||||
/* if (table.get(new Word("cat")).equals("an animal")) {
|
||||
table.remove(new Word("cat"));
|
||||
}*/
|
||||
|
||||
// new way
|
||||
boolean result = table.remove(new Word("cat"), "an animal");
|
||||
|
||||
assertThat(result, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplacePair_thenValueChecked() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
String definition = "an animal";
|
||||
|
||||
// old way
|
||||
/* if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) {
|
||||
table.put(new Word("cat"), definition);
|
||||
}*/
|
||||
// new way
|
||||
table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);
|
||||
|
||||
assertThat(table.get(new Word("cat")), is("an animal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyIsAbsent_thenNotRewritten() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
// old way
|
||||
/* if (!table.containsKey(cat)) {
|
||||
String definition = "an animal";// calculate
|
||||
table.put(new Word("cat"), definition);
|
||||
}
|
||||
*/
|
||||
// new way
|
||||
|
||||
table.computeIfAbsent(new Word("cat"), key -> "an animal");
|
||||
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyIsPresent_thenComputeIfPresent() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
Word cat = new Word("cat");
|
||||
// old way
|
||||
/* if (table.containsKey(cat)) {
|
||||
String concatination = cat.getName() + " - " + table.get(cat);
|
||||
table.put(cat, concatination);
|
||||
}*/
|
||||
|
||||
// new way
|
||||
table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);
|
||||
|
||||
assertThat(table.get(cat), is("cat - a small domesticated carnivorous mammal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompute_thenForAllKeys() {
|
||||
|
||||
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
|
||||
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
|
||||
for (String animal : animals) {
|
||||
table.compute(animal, (key, value) -> (value == null ? Integer.valueOf(1) : Integer.valueOf(value) + 1));
|
||||
}
|
||||
assertThat(table.values(), hasItems(2, 2, 2, 1));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsteadOfCompute_thenMerge() {
|
||||
|
||||
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
|
||||
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
|
||||
for (String animal : animals) {
|
||||
table.merge(animal, 1, (oldValue, value) -> (oldValue + value));
|
||||
}
|
||||
assertThat(table.values(), hasItems(2, 2, 2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenForeach_thenIterate() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceall_thenNoIterationNeeded() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
table.replaceAll((k, v) -> k.getName() + " - " + v);
|
||||
|
||||
assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal"));
|
||||
}
|
||||
}
|
|
@ -23,3 +23,4 @@
|
|||
- [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)
|
||||
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
|
||||
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
|
||||
|
|
|
@ -8,10 +8,11 @@
|
|||
<name>core-java-collections</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -25,11 +26,6 @@
|
|||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
@ -55,7 +51,6 @@
|
|||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<guava.version>22.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<collections-generic.version>4.01</collections-generic.version>
|
||||
|
|
|
@ -9,17 +9,12 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
|
|
@ -25,3 +25,5 @@
|
|||
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
|
||||
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
|
||||
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)
|
||||
- [Guide to Java NIO2 Asynchronous Channel APIs](http://www.baeldung.com/java-nio-2-async-channels)
|
||||
- [A Guide to NIO2 Asynchronous Socket Channel](http://www.baeldung.com/java-nio2-async-socket-channel)
|
||||
|
|
|
@ -9,8 +9,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -20,11 +21,6 @@
|
|||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
|
|
@ -8,8 +8,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -19,11 +20,6 @@
|
|||
<artifactId>collections-generic</artifactId>
|
||||
<version>${collections-generic.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
|
|
@ -74,17 +74,14 @@
|
|||
- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
|
||||
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
|
||||
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
|
||||
- [Singletons in Java](http://www.baeldung.com/java-singleton)
|
||||
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
|
||||
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
|
||||
- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
|
||||
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
|
||||
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
|
||||
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
|
||||
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
|
||||
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
|
||||
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
||||
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||
|
@ -116,8 +113,6 @@
|
|||
- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
|
||||
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
|
||||
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
|
||||
- [The Observer Pattern in Java](https://github.com/eugenp/tutorials/tree/master/core-java)
|
||||
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
|
||||
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
|
||||
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
|
||||
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
|
||||
|
@ -127,4 +122,22 @@
|
|||
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
|
||||
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
|
||||
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
|
||||
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
|
||||
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
|
||||
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
|
||||
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
|
||||
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
|
||||
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
|
||||
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
|
||||
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
|
||||
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
|
||||
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
|
||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
|
||||
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
|
||||
- [Sending Emails with Java](http://www.baeldung.com/java-email)
|
||||
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
|
||||
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
|
||||
- [Using Java Assertions](http://www.baeldung.com/java-assert)
|
||||
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
|
||||
|
|
|
@ -9,17 +9,12 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
|
@ -438,7 +433,6 @@
|
|||
<log4j.version>1.2.17</log4j.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>22.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<bouncycastle.version>1.55</bouncycastle.version>
|
||||
<commons-codec.version>1.10</commons-codec.version>
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
package com.baeldung.designpatterns.creational.abstractfactory;
|
||||
|
||||
public interface Color {
|
||||
String getColor();
|
||||
}
|
|
@ -1,5 +0,0 @@
|
|||
package com.baeldung.designpatterns.creational.factory;
|
||||
|
||||
public interface Polygon {
|
||||
String getType();
|
||||
}
|
|
@ -1,10 +1,12 @@
|
|||
package com.baeldung.numberofdigits;
|
||||
|
||||
import static com.baeldung.designpatterns.util.LogerUtil.LOG;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class NumberOfDigitsDriver {
|
||||
private static NumberOfDigits numberOfDigits;
|
||||
|
||||
private static Logger LOG = Logger.getLogger(NumberOfDigitsDriver.class);
|
||||
|
||||
static {
|
||||
numberOfDigits = new NumberOfDigits();
|
||||
}
|
||||
|
|
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.RunnerException;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
|
||||
public class Benchmarking {
|
||||
public static void main(String[] args) throws RunnerException {
|
||||
Options opt = new OptionsBuilder()
|
||||
.include(Benchmarking.class.getSimpleName())
|
||||
.forks(1)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
}
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class ExecutionPlan {
|
||||
public String number = Integer.toString(Integer.MAX_VALUE);
|
||||
public boolean isNumber = false;
|
||||
public IsNumeric isNumeric= new IsNumeric();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingCoreJava(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingCoreJava(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingRegularExpressions(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingRegularExpressions(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isCreatable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isCreatable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingNumberUtils_isParsable(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingNumberUtils_isParsable(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumeric(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumeric(plan.number);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
public void usingStringUtils_isNumericSpace(ExecutionPlan plan) {
|
||||
plan.isNumber = plan.isNumeric.usingStringUtils_isNumericSpace(plan.number);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
|
||||
public class IsNumeric {
|
||||
public boolean usingCoreJava(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean usingRegularExpressions(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isCreatable(String strNum) {
|
||||
return NumberUtils.isCreatable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingNumberUtils_isParsable(String strNum) {
|
||||
return NumberUtils.isParsable(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumeric(String strNum) {
|
||||
return StringUtils.isNumeric(strNum);
|
||||
}
|
||||
|
||||
public boolean usingStringUtils_isNumericSpace(String strNum) {
|
||||
return StringUtils.isNumericSpace(strNum);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
public class IsNumericDriver {
|
||||
private static IsNumeric isNumeric;
|
||||
private static Logger LOG = Logger.getLogger(IsNumericDriver.class);
|
||||
static {
|
||||
isNumeric =new IsNumeric();
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
LOG.info("Testing all methods...");
|
||||
|
||||
boolean res = isNumeric.usingCoreJava("1001");
|
||||
LOG.info("Using Core Java : " + res);
|
||||
|
||||
res = isNumeric.usingRegularExpressions("1001");
|
||||
LOG.info("Using Regular Expressions : " + res);
|
||||
|
||||
res =isNumeric.usingNumberUtils_isCreatable("1001");
|
||||
LOG.info("Using NumberUtils.isCreatable : " + res);
|
||||
|
||||
res =isNumeric.usingNumberUtils_isParsable("1001");
|
||||
LOG.info("Using NumberUtils.isParsable : " + res);
|
||||
|
||||
res =isNumeric.usingStringUtils_isNumeric("1001");
|
||||
LOG.info("Using StringUtils.isNumeric : " + res);
|
||||
|
||||
res =isNumeric.usingStringUtils_isNumericSpace("1001");
|
||||
LOG.info("Using StringUtils.isNumericSpace : " + res);
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CoreJavaIsNumericUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
try {
|
||||
double d = Double.parseDouble(strNum);
|
||||
} catch (NumberFormatException | NullPointerException nfe) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCoreJava_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
assertThat(isNumeric("10.0d")).isTrue();
|
||||
assertThat(isNumeric(" 22 ")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric(null)).isFalse();
|
||||
assertThat(isNumeric("")).isFalse();
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsCreatableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isCreatable("22")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("5.05")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("-200")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("10.0d")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("1000L")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("0xFF")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("07")).isTrue();
|
||||
assertThat(NumberUtils.isCreatable("2.99e+8")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isCreatable(null)).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("abc")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable(" 22 ")).isFalse();
|
||||
assertThat(NumberUtils.isCreatable("09")).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.commons.lang3.math.NumberUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class NumberUtilsIsParsableUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsParsable_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(NumberUtils.isParsable("22")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("-23")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("2.2")).isTrue();
|
||||
assertThat(NumberUtils.isParsable("09")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(NumberUtils.isParsable(null)).isFalse();
|
||||
assertThat(NumberUtils.isParsable("")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("6.2f")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("9.8d")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("22L")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("0xFF")).isFalse();
|
||||
assertThat(NumberUtils.isParsable("2.99e+8")).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class RegularExpressionsUnitTest {
|
||||
public static boolean isNumeric(String strNum) {
|
||||
return strNum.matches("-?\\d+(\\.\\d+)?");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingRegularExpressions_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(isNumeric("22")).isTrue();
|
||||
assertThat(isNumeric("5.05")).isTrue();
|
||||
assertThat(isNumeric("-200")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(isNumeric("abc")).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringUtilsIsNumericSpaceUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumericSpace_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumericSpace("123")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace(" ")).isTrue();
|
||||
assertThat(StringUtils.isNumericSpace("12 3")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumericSpace(null)).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumericSpace("-123")).isFalse();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.stringisnumeric;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class StringUtilsIsNumericUnitTest {
|
||||
@Test
|
||||
public void givenApacheCommons_whenUsingIsNumeric_thenTrue() {
|
||||
// Valid Numbers
|
||||
assertThat(StringUtils.isNumeric("123")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("١٢٣")).isTrue();
|
||||
assertThat(StringUtils.isNumeric("१२३")).isTrue();
|
||||
|
||||
// Invalid Numbers
|
||||
assertThat(StringUtils.isNumeric(null)).isFalse();
|
||||
assertThat(StringUtils.isNumeric("")).isFalse();
|
||||
assertThat(StringUtils.isNumeric(" ")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12 3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("ab2c")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("12.3")).isFalse();
|
||||
assertThat(StringUtils.isNumeric("-123")).isFalse();
|
||||
}
|
||||
}
|
|
@ -25,3 +25,4 @@
|
|||
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)
|
||||
- [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file)
|
||||
- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation)
|
||||
- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
|
||||
|
|
|
@ -25,12 +25,6 @@
|
|||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
|
@ -69,6 +63,24 @@
|
|||
<artifactId>kotlinx-coroutines-core</artifactId>
|
||||
<version>${kotlinx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-api</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-subject-extension</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.spek</groupId>
|
||||
<artifactId>spek-junit-platform-engine</artifactId>
|
||||
<version>1.1.5</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nhaarman</groupId>
|
||||
<artifactId>mockito-kotlin</artifactId>
|
||||
|
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.filesystem
|
||||
|
||||
import java.io.File
|
||||
|
||||
class FileWriter {
|
||||
|
||||
fun writeFileUsingPrintWriter(fileName: String, fileContent: String) =
|
||||
File(fileName).printWriter().use { out -> out.print(fileContent) }
|
||||
|
||||
fun writeFileUsingBufferedWriter(fileName: String, fileContent: String) =
|
||||
File(fileName).bufferedWriter().use { out -> out.write(fileContent) }
|
||||
|
||||
fun writeFileDirectly(fileName: String, fileContent: String) =
|
||||
File(fileName).writeText(fileContent)
|
||||
|
||||
fun writeFileDirectlyAsBytes(fileName: String, fileContent: String) =
|
||||
File(fileName).writeBytes(fileContent.toByteArray())
|
||||
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package com.baeldung.lambda
|
||||
|
||||
fun inferredType(input: Int): Int {
|
||||
val square = { number: Int -> number * number }
|
||||
|
||||
return square(input)
|
||||
}
|
||||
|
||||
fun intToBiggerString(argument: Int): String {
|
||||
|
||||
val magnitude100String = { input: Int ->
|
||||
val magnitude = input * 100
|
||||
magnitude.toString()
|
||||
}
|
||||
|
||||
return magnitude100String(argument)
|
||||
}
|
||||
|
||||
fun manyLambda(nums: Array<Int>): List<String> {
|
||||
val newList = nums.map { intToBiggerString(it) }
|
||||
|
||||
return newList
|
||||
}
|
||||
|
||||
fun empty() {
|
||||
val noReturn: (Int) -> Unit = { num -> println(num) }
|
||||
|
||||
noReturn(5)
|
||||
}
|
||||
|
||||
fun invokeLambda(lambda: (Double) -> Boolean): Boolean {
|
||||
return lambda(4.329)
|
||||
}
|
||||
|
||||
fun extendString(arg: String, num: Int): String {
|
||||
val another: String.(Int) -> String = { this + it }
|
||||
|
||||
return arg.another(num)
|
||||
}
|
||||
|
||||
fun getCalculationLambda(): (Int) -> Any {
|
||||
val calculateGrade = { grade: Int ->
|
||||
when (grade) {
|
||||
in 0..40 -> "Fail"
|
||||
in 41..70 -> "Pass"
|
||||
in 71..100 -> "Distinction"
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
return calculateGrade
|
||||
}
|
||||
|
||||
fun getCalculationLambdaWithReturn(): (Int) -> String {
|
||||
val calculateGrade: Int.() -> String = lambda@{
|
||||
if (this < 0 || this > 100) {
|
||||
return@lambda "Error"
|
||||
} else if (this < 40) {
|
||||
return@lambda "Fail"
|
||||
} else if (this < 70) {
|
||||
return@lambda "Pass"
|
||||
}
|
||||
|
||||
"Distinction"
|
||||
}
|
||||
|
||||
return calculateGrade
|
||||
}
|
||||
|
||||
fun getCalculationAnonymousFunction(): (Int) -> String {
|
||||
val calculateGrade = fun(grade: Int): String {
|
||||
if (grade < 0 || grade > 100) {
|
||||
return "Error"
|
||||
} else if (grade < 40) {
|
||||
return "Fail"
|
||||
} else if (grade < 70) {
|
||||
return "Pass"
|
||||
}
|
||||
|
||||
return "Distinction"
|
||||
}
|
||||
|
||||
return calculateGrade
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.lambda;
|
||||
|
||||
import kotlin.jvm.functions.Function1;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Created by Paul Jervis on 24/04/2018.
|
||||
*/
|
||||
class LambdaKotlinTest {
|
||||
|
||||
@Test
|
||||
void givenJava6_whenUsingAnonnymousClass_thenReturnLambdaResult() {
|
||||
assertTrue(LambdaKt.invokeLambda(new Function1<Double, Boolean>() {
|
||||
@Override
|
||||
public Boolean invoke(Double c) {
|
||||
return c >= 0;
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJava8_whenUsingLambda_thenReturnLambdaResult() {
|
||||
assertTrue(LambdaKt.invokeLambda(c -> c >= 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJava8_whenCallingMethodWithStringExtension_thenImplementExtension() {
|
||||
String actual = LambdaKt.extendString("Word", 90);
|
||||
String expected = "Word90";
|
||||
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.filesystem
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.File
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
internal class FileWriterTest {
|
||||
|
||||
private val fileName = "src/test/resources/Kotlin.out"
|
||||
|
||||
private val fileContent = "Kotlin\nConcise, Safe, Interoperable, Tool-friendly"
|
||||
|
||||
private val fileWriter = FileWriter()
|
||||
|
||||
@Test
|
||||
fun whenWrittenWithPrintWriter_thenCorrect() {
|
||||
fileWriter.writeFileUsingPrintWriter(fileName, fileContent)
|
||||
|
||||
assertEquals(fileContent, File(fileName).readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWrittenWithBufferedWriter_thenCorrect() {
|
||||
fileWriter.writeFileUsingBufferedWriter(fileName, fileContent)
|
||||
|
||||
assertEquals(fileContent, File(fileName).readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWrittenDirectly_thenCorrect() {
|
||||
fileWriter.writeFileDirectly(fileName, fileContent)
|
||||
|
||||
assertEquals(fileContent, File(fileName).readText())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenWrittenDirectlyAsBytes_thenCorrect() {
|
||||
fileWriter.writeFileDirectlyAsBytes(fileName, fileContent)
|
||||
|
||||
assertEquals(fileContent, File(fileName).readText())
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.kotlin.spek
|
||||
|
||||
import com.baeldung.kotlin.junit5.Calculator
|
||||
import org.jetbrains.spek.api.dsl.describe
|
||||
import org.jetbrains.spek.api.dsl.it
|
||||
import org.jetbrains.spek.subject.SubjectSpek
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
|
||||
class CalculatorSubjectTest5 : SubjectSpek<Calculator>({
|
||||
subject { Calculator() }
|
||||
describe("A calculator") {
|
||||
describe("Addition") {
|
||||
val result = subject.add(3, 5)
|
||||
it("Produces the correct answer") {
|
||||
assertEquals(8, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.kotlin.spek
|
||||
|
||||
import com.baeldung.kotlin.junit5.Calculator
|
||||
import org.jetbrains.spek.api.Spek
|
||||
import org.jetbrains.spek.api.dsl.describe
|
||||
import org.jetbrains.spek.api.dsl.given
|
||||
import org.jetbrains.spek.api.dsl.it
|
||||
import org.jetbrains.spek.api.dsl.on
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
|
||||
class CalculatorTest5 : Spek({
|
||||
given("A calculator") {
|
||||
val calculator = Calculator()
|
||||
on("Adding 3 and 5") {
|
||||
val result = calculator.add(3, 5)
|
||||
it("Produces 8") {
|
||||
assertEquals(8, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("A calculator") {
|
||||
val calculator = Calculator()
|
||||
describe("Addition") {
|
||||
val result = calculator.add(3, 5)
|
||||
it("Produces the correct answer") {
|
||||
assertEquals(8, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
})
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.kotlin.spek
|
||||
|
||||
import org.jetbrains.spek.api.Spek
|
||||
import org.jetbrains.spek.api.dsl.describe
|
||||
import org.jetbrains.spek.api.dsl.it
|
||||
import org.junit.jupiter.api.Assertions
|
||||
|
||||
class DataDrivenTest5 : Spek({
|
||||
describe("A data driven test") {
|
||||
mapOf(
|
||||
"hello" to "HELLO",
|
||||
"world" to "WORLD"
|
||||
).forEach { input, expected ->
|
||||
describe("Capitalising $input") {
|
||||
it("Correctly returns $expected") {
|
||||
Assertions.assertEquals(expected, input.toUpperCase())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.kotlin.spek
|
||||
|
||||
import org.jetbrains.spek.api.Spek
|
||||
import org.jetbrains.spek.api.dsl.describe
|
||||
import org.jetbrains.spek.api.dsl.it
|
||||
|
||||
class GroupTest5 : Spek({
|
||||
describe("Outer group") {
|
||||
beforeEachTest {
|
||||
System.out.println("BeforeEachTest 0")
|
||||
}
|
||||
beforeGroup {
|
||||
System.out.println("BeforeGroup 0")
|
||||
}
|
||||
afterEachTest {
|
||||
System.out.println("AfterEachTest 0")
|
||||
}
|
||||
afterGroup {
|
||||
System.out.println("AfterGroup 0")
|
||||
}
|
||||
describe("Inner group 1") {
|
||||
beforeEachTest {
|
||||
System.out.println("BeforeEachTest 1")
|
||||
}
|
||||
beforeGroup {
|
||||
System.out.println("BeforeGroup 1")
|
||||
}
|
||||
afterEachTest {
|
||||
System.out.println("AfterEachTest 1")
|
||||
}
|
||||
afterGroup {
|
||||
System.out.println("AfterGroup 1")
|
||||
}
|
||||
it("Test 1") {
|
||||
System.out.println("Test 1")
|
||||
}
|
||||
it("Test 2") {
|
||||
System.out.println("Test 2")
|
||||
}
|
||||
}
|
||||
describe("Inner group 2") {
|
||||
beforeEachTest {
|
||||
System.out.println("BeforeEachTest 2")
|
||||
}
|
||||
beforeGroup {
|
||||
System.out.println("BeforeGroup 2")
|
||||
}
|
||||
afterEachTest {
|
||||
System.out.println("AfterEachTest 2")
|
||||
}
|
||||
afterGroup {
|
||||
System.out.println("AfterGroup 2")
|
||||
}
|
||||
it("Test 3") {
|
||||
System.out.println("Test 3")
|
||||
}
|
||||
it("Test 4") {
|
||||
System.out.println("Test 4")
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
|
@ -0,0 +1,95 @@
|
|||
package com.baeldung.lambda
|
||||
|
||||
import org.junit.jupiter.api.Assertions.assertFalse
|
||||
import org.junit.jupiter.api.Assertions.assertTrue
|
||||
import org.junit.jupiter.api.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class LambdaTest {
|
||||
@Test
|
||||
fun whenCallingALambda_thenPerformTheAction() {
|
||||
assertEquals(9, inferredType(3))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenCallingAMoreComplicatedLambda_thenPerformTheAction() {
|
||||
assertEquals("500", intToBiggerString(5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenPassingALambdaObject_thenCallTriggerLambda() {
|
||||
val lambda = { arg: Double ->
|
||||
arg == 4.329
|
||||
}
|
||||
|
||||
val result = invokeLambda(lambda)
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenPassingALambdaLiteral_thenCallTriggerLambda() {
|
||||
val result = invokeLambda({
|
||||
true
|
||||
})
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenPassingALambdaLiteralOutsideBrackets_thenCallTriggerLambda() {
|
||||
val result = invokeLambda { arg -> arg.isNaN() }
|
||||
|
||||
assertFalse(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenPassingAnAnonymousFunction_thenCallTriggerLambda() {
|
||||
val result = invokeLambda(fun(arg: Double): Boolean {
|
||||
return arg >= 0
|
||||
})
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUsingLambda_thenCalculateGrade() {
|
||||
val gradeCalculation = getCalculationLambda()
|
||||
|
||||
assertEquals(false, gradeCalculation(-40))
|
||||
assertEquals("Pass", gradeCalculation(50))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUsingReturnStatementLambda_thenCalculateGrade() {
|
||||
val gradeCalculation: Int.() -> String = getCalculationLambdaWithReturn()
|
||||
|
||||
assertEquals("Distinction", 80.gradeCalculation())
|
||||
assertEquals("Error", 244_234_324.gradeCalculation())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUsingAnonymousFunction_thenCalculateGrade() {
|
||||
val gradeCalculation = getCalculationAnonymousFunction()
|
||||
|
||||
assertEquals("Error", gradeCalculation(244_234_324))
|
||||
assertEquals("Pass", gradeCalculation(50))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenPassingAFunctionReference_thenCallTriggerLambda() {
|
||||
val reference = Double::isFinite
|
||||
val result = invokeLambda(reference)
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenArray_whenMappingArray_thenPerformCalculationOnAllElements() {
|
||||
val expected = listOf("100", "200", "300", "400", "500")
|
||||
val actual = manyLambda(arrayOf(1, 2, 3, 4, 5))
|
||||
|
||||
assertEquals(expected, actual)
|
||||
}
|
||||
|
||||
}
|
|
@ -5,10 +5,11 @@
|
|||
<artifactId>drools</artifactId>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-spring</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
@ -47,18 +48,13 @@
|
|||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>${apache-poi-version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-core.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<http-component-version>4.4.6</http-component-version>
|
||||
<drools-version>7.4.1.Final</drools-version>
|
||||
<apache-poi-version>3.13</apache-poi-version>
|
||||
<spring-core.version>4.3.6.RELEASE</spring-core.version>
|
||||
<spring.version>4.3.6.RELEASE</spring.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
|
||||
- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity)
|
||||
|
|
10
gson/pom.xml
10
gson/pom.xml
|
@ -8,8 +8,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -19,11 +20,6 @@
|
|||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
|
|
|
@ -8,19 +8,11 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<guava.version>18.0</guava.version>
|
||||
</properties>
|
||||
|
|
|
@ -8,19 +8,11 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<guava.version>19.0</guava.version>
|
||||
</properties>
|
||||
|
|
|
@ -7,18 +7,12 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.jooq</groupId>
|
||||
<artifactId>jool</artifactId>
|
||||
|
|
|
@ -8,17 +8,13 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
|
@ -36,6 +32,14 @@
|
|||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${java-hamcrest.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -56,6 +60,7 @@
|
|||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,259 @@
|
|||
package org.baeldung.hamcrest;
|
||||
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.core.StringEndsWith.endsWith;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
|
||||
public class HamcrestCoreMatchersTest {
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingIsForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, is("hamcrest core"));
|
||||
assertThat(testString, is(equalTo("hamcrest core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
Object original = 100;
|
||||
|
||||
// ASSERT
|
||||
assertThat(original, equalToObject(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() {
|
||||
|
||||
assertThat("hamcrest", is(instanceOf(String.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingIsA_ThenAssertType() {
|
||||
|
||||
assertThat("hamcrest core", isA(String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEqualToMatcherForEquality() {
|
||||
|
||||
// GIVEN
|
||||
String actualString = "Hamcrest Core";
|
||||
List<String> actualList = Lists.newArrayList("hamcrest", "core");
|
||||
|
||||
// ASSERT
|
||||
assertThat(actualString, is(equalTo("Hamcrest Core")));
|
||||
assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNotForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, not("hamcrest core"));
|
||||
assertThat(testString, is(not(equalTo("hamcrest core"))));
|
||||
assertThat(testString, is(not(instanceOf(Integer.class))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNullValueForNullCheck() {
|
||||
|
||||
// GIVEN
|
||||
Integer nullObject = null;
|
||||
|
||||
// ASSERT
|
||||
assertThat(nullObject, is(nullValue()));
|
||||
assertThat(nullObject, is(nullValue(Integer.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() {
|
||||
|
||||
// GIVEN
|
||||
Integer testNumber = 123;
|
||||
|
||||
// ASSERT
|
||||
assertThat(testNumber, is(notNullValue()));
|
||||
assertThat(testNumber, is(notNullValue(Integer.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenStartsWith_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, startsWith("hamcrest"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, startsWithIgnoringCase("HAMCREST"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenEndsWith_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, endsWith("core"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, endsWithIgnoringCase("CORE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenContainsString_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, containsString("co"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() {
|
||||
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, containsStringIgnoringCase("CO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingHasItemInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
|
||||
|
||||
// ASSERT
|
||||
assertThat(list, hasItem("java"));
|
||||
assertThat(list, hasItem(isA(String.class)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingHasItemsInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
|
||||
|
||||
// ASSERT
|
||||
assertThat(list, hasItems("java", "baeldung"));
|
||||
assertThat(list, hasItems(isA(String.class), endsWith("ing")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAnyForClassType() {
|
||||
|
||||
assertThat("hamcrest", is(any(String.class)));
|
||||
assertThat("hamcrest", is(any(Object.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAllOfForAllMatchers() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAnyOfForAnyMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingBothForMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core Matchers";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, both(startsWith("Ham")).and(containsString("Core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEitherForMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core Matchers";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, either(startsWith("Bael")).or(containsString("Core")));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEveryItemForMatchInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> testItems = Lists.newArrayList("Common", "Core", "Combinable");
|
||||
|
||||
// ASSERT
|
||||
assertThat(testItems, everyItem(startsWith("Co")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String string1 = "hamcrest";
|
||||
String string2 = string1;
|
||||
|
||||
// ASSERT
|
||||
assertThat(string1, is(sameInstance(string2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() {
|
||||
// GIVEN
|
||||
String string1 = "hamcrest";
|
||||
String string2 = string1;
|
||||
|
||||
// ASSERT
|
||||
assertThat(string1, is(theInstance(string2)));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import static org.hamcrest.Matchers.hasItems;
|
|||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.emptyIterable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
@ -57,6 +58,12 @@ public class HamcrestExamplesUnitTest {
|
|||
final List<String> collection = Lists.newArrayList();
|
||||
assertThat(collection, empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenIterableIsEmpty_whenChecking_thenEmpty() {
|
||||
final Iterable<String> collection = Lists.newArrayList();
|
||||
assertThat(collection, emptyIterable());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenCollectionIsNotEmpty_whenChecking_thenNotEmpty() {
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Testing with Hamcrest](http://www.baeldung.com/java-junit-hamcrest-guide)
|
||||
- [Hamcrest File Matchers](http://www.baeldung.com/hamcrest-file-matchers)
|
||||
|
|
|
@ -11,11 +11,6 @@
|
|||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>5.0.0-M4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
|
@ -62,4 +57,8 @@
|
|||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
|
||||
</properties>
|
||||
</project>
|
|
@ -10,8 +10,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-spring</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-spring</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
|
|
@ -9,3 +9,4 @@
|
|||
- [Hibernate Interceptors](http://www.baeldung.com/hibernate-interceptor)
|
||||
- [JPA Attribute Converters](http://www.baeldung.com/jpa-attribute-converters)
|
||||
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
|
||||
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
|
||||
|
|
|
@ -1,30 +1,12 @@
|
|||
package com.baeldung.hibernate;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
import com.baeldung.hibernate.pojo.OrderEntry;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
|
||||
import com.baeldung.hibernate.pojo.OrderEntryPK;
|
||||
import com.baeldung.hibernate.pojo.PointEntity;
|
||||
import com.baeldung.hibernate.pojo.PolygonEntity;
|
||||
import com.baeldung.hibernate.pojo.Product;
|
||||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
import com.baeldung.hibernate.pojo.Course;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
import com.baeldung.hibernate.pojo.User;
|
||||
import com.baeldung.hibernate.pojo.UserProfile;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Animal;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Bag;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Book;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Car;
|
||||
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
|
||||
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pen;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Person;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Pet;
|
||||
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
|
||||
|
||||
import com.baeldung.hibernate.pessimisticlocking.Individual;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pojo.*;
|
||||
import com.baeldung.hibernate.pojo.Person;
|
||||
import com.baeldung.hibernate.pojo.inheritance.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
|
@ -82,6 +64,12 @@ public class HibernateUtil {
|
|||
metadataSources.addAnnotatedClass(PointEntity.class);
|
||||
metadataSources.addAnnotatedClass(PolygonEntity.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pojo.Person.class);
|
||||
metadataSources.addAnnotatedClass(Individual.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingEmployee.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
|
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class Address {
|
||||
|
||||
private String country;
|
||||
private String city;
|
||||
|
||||
public Address(String country, String city) {
|
||||
this.country = country;
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,58 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
private Long customerId;
|
||||
private String name;
|
||||
private String lastName;
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "customer_address")
|
||||
private List<Address> addressList;
|
||||
|
||||
public Customer() {
|
||||
}
|
||||
|
||||
public Customer(Long customerId, String name, String lastName, List<Address> addressList) {
|
||||
this.customerId = customerId;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
this.addressList = addressList;
|
||||
}
|
||||
|
||||
public Long getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(Long customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public List<Address> getAddressList() {
|
||||
return addressList;
|
||||
}
|
||||
|
||||
public void setAddressList(List<Address> addressList) {
|
||||
this.addressList = addressList;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Inheritance;
|
||||
import javax.persistence.InheritanceType;
|
||||
|
||||
@Entity
|
||||
@Inheritance(strategy = InheritanceType.JOINED)
|
||||
public class Individual {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
private String lastName;
|
||||
|
||||
public Individual(Long id, String name, String lastName) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public Individual() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingCourse {
|
||||
|
||||
@Id
|
||||
private Long courseId;
|
||||
private String name;
|
||||
@ManyToOne
|
||||
@JoinTable(name = "student_course")
|
||||
private PessimisticLockingStudent student;
|
||||
|
||||
public PessimisticLockingCourse(Long courseId, String name, PessimisticLockingStudent student) {
|
||||
this.courseId = courseId;
|
||||
this.name = name;
|
||||
this.student = student;
|
||||
}
|
||||
|
||||
public PessimisticLockingCourse() {
|
||||
}
|
||||
|
||||
public Long getCourseId() {
|
||||
return courseId;
|
||||
}
|
||||
|
||||
public void setCourseId(Long courseId) {
|
||||
this.courseId = courseId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PessimisticLockingStudent getStudent() {
|
||||
return student;
|
||||
}
|
||||
|
||||
public void setStudent(PessimisticLockingStudent students) {
|
||||
this.student = students;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingEmployee extends Individual {
|
||||
|
||||
private BigDecimal salary;
|
||||
|
||||
public PessimisticLockingEmployee(Long id, String name, String lastName, BigDecimal salary) {
|
||||
super(id, name, lastName);
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public PessimisticLockingEmployee() {
|
||||
super();
|
||||
}
|
||||
|
||||
public BigDecimal getSalary() {
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void setSalary(BigDecimal average) {
|
||||
this.salary = average;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
public class PessimisticLockingStudent {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "student")
|
||||
private List<PessimisticLockingCourse> courses;
|
||||
|
||||
public PessimisticLockingStudent(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public PessimisticLockingStudent() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<PessimisticLockingCourse> getCourses() {
|
||||
return courses;
|
||||
}
|
||||
|
||||
public void setCourses(List<PessimisticLockingCourse> courses) {
|
||||
this.courses = courses;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,151 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.vividsolutions.jts.util.Assert;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class BasicPessimisticLockingIntegrationTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOHN");
|
||||
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "MATH", student);
|
||||
student.setCourses(Arrays.asList(course));
|
||||
entityManager.persist(course);
|
||||
entityManager.persist(student);
|
||||
entityManager.getTransaction()
|
||||
.commit();
|
||||
entityManager.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFoundRecordWithPessimisticRead_whenFindingNewOne_PessimisticLockExceptionThrown() {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
entityManager.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_READ);
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
Query query = entityManager.createQuery("from Student where studentId = :studentId");
|
||||
query.setParameter("studentId", 1L);
|
||||
query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
|
||||
query.getResultList();
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
Query query2 = entityManager2.createQuery("from Student where studentId = :studentId");
|
||||
query2.setParameter("studentId", 1L);
|
||||
query2.setLockMode(LockModeType.PESSIMISTIC_READ);
|
||||
query2.getResultList();
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordWithPessimisticReadLock_whenFindingNewOne_PessimisticLockExceptionThrown() {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
|
||||
entityManager.lock(resultStudent, LockModeType.PESSIMISTIC_READ);
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordAndRefreshWithPessimisticRead_whenFindingWithPessimisticWrite_PessimisticLockExceptionThrown() {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
|
||||
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
entityManager2.find(PessimisticLockingStudent.class, 1L, LockModeType.PESSIMISTIC_WRITE);
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordWithPessimisticRead_whenUpdatingRecord_PessimisticLockExceptionThrown() {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
|
||||
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_READ);
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
|
||||
resultStudent2.setName("Change");
|
||||
entityManager2.persist(resultStudent2);
|
||||
entityManager2.getTransaction()
|
||||
.commit();
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRecordWithPessimisticWrite_whenUpdatingRecord_PessimisticLockExceptionThrown() {
|
||||
try {
|
||||
EntityManager entityManager = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent = entityManager.find(PessimisticLockingStudent.class, 1L);
|
||||
entityManager.refresh(resultStudent, LockModeType.PESSIMISTIC_WRITE);
|
||||
|
||||
EntityManager entityManager2 = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent resultStudent2 = entityManager2.find(PessimisticLockingStudent.class, 1L);
|
||||
resultStudent2.setName("Change");
|
||||
entityManager2.persist(resultStudent2);
|
||||
entityManager2.getTransaction()
|
||||
.commit();
|
||||
|
||||
entityManager.close();
|
||||
entityManager2.close();
|
||||
} catch (Exception e) {
|
||||
Assert.isTrue(e instanceof PessimisticLockException);
|
||||
}
|
||||
}
|
||||
|
||||
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
|
||||
String propertyFileName = "hibernate-pessimistic-locking.properties";
|
||||
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
|
||||
.openSession();
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
|
||||
return entityManager;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.LockModeType;
|
||||
import javax.persistence.PessimisticLockScope;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class PessimisticLockScopesIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
|
||||
EntityManager em = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingEmployee employee = new PessimisticLockingEmployee(1L, "JOHN", "SMITH", new BigDecimal(4.5));
|
||||
em.persist(employee);
|
||||
em.getTransaction()
|
||||
.commit();
|
||||
em.close();
|
||||
|
||||
// NORMAL SCOPE
|
||||
EntityManager em2 = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingEmployee foundEmployee = em2.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE);
|
||||
em2.getTransaction()
|
||||
.rollback();
|
||||
|
||||
// EXTENDED SCOPE
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
|
||||
|
||||
EntityManager em3 = getEntityManagerWithOpenTransaction();
|
||||
foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
|
||||
em3.getTransaction()
|
||||
.rollback();
|
||||
|
||||
em2.close();
|
||||
em3.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntityWithElementCollection_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
|
||||
EntityManager em = getEntityManagerWithOpenTransaction();
|
||||
Address address = new Address("Poland", "Warsaw");
|
||||
Customer customer = new Customer(1L, "JOE", "DOE", Arrays.asList(address));
|
||||
em.persist(customer);
|
||||
em.getTransaction()
|
||||
.commit();
|
||||
em.close();
|
||||
|
||||
// NORMAL SCOPE
|
||||
EntityManager em2 = getEntityManagerWithOpenTransaction();
|
||||
Customer foundCustomer = em2.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE);
|
||||
em2.getTransaction()
|
||||
.rollback();
|
||||
|
||||
// EXTENDED SCOPE
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
|
||||
|
||||
EntityManager em3 = getEntityManagerWithOpenTransaction();
|
||||
foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
|
||||
em2.getTransaction()
|
||||
.rollback();
|
||||
|
||||
em2.close();
|
||||
em3.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEntityWithOneToMany_whenLock_thenHibernateExtendedScopeLockOnlyOwningEntity() throws IOException {
|
||||
EntityManager em = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingStudent student = new PessimisticLockingStudent(1L, "JOE");
|
||||
PessimisticLockingCourse course = new PessimisticLockingCourse(1L, "COURSE", student);
|
||||
student.setCourses(Arrays.asList(course));
|
||||
em.persist(course);
|
||||
em.persist(student);
|
||||
em.getTransaction()
|
||||
.commit();
|
||||
em.close();
|
||||
|
||||
// NORMAL SCOPE
|
||||
EntityManager em2 = getEntityManagerWithOpenTransaction();
|
||||
PessimisticLockingCourse foundCourse = em2.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE);
|
||||
em2.getTransaction()
|
||||
.rollback();
|
||||
|
||||
// EXTENDED SCOPE
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
|
||||
|
||||
EntityManager em3 = getEntityManagerWithOpenTransaction();
|
||||
foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
|
||||
em3.getTransaction()
|
||||
.rollback();
|
||||
|
||||
em2.close();
|
||||
em3.close();
|
||||
}
|
||||
|
||||
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
|
||||
String propertyFileName = "hibernate-pessimistic-locking.properties";
|
||||
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
|
||||
.openSession();
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
|
||||
return entityManager;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
|
@ -8,17 +8,13 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
|
|
|
@ -24,6 +24,7 @@ import org.junit.Test;
|
|||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
@ -89,7 +90,7 @@ public class HttpClientAuthLiveTest {
|
|||
public final void givenAuthorizationHeaderIsSetManually_whenExecutingGetRequest_thenSuccess2() throws IOException {
|
||||
final HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
|
||||
final String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
|
||||
final String authHeader = "Basic " + new String(encodedAuth);
|
||||
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
|
||||
|
||||
|
@ -129,7 +130,7 @@ public class HttpClientAuthLiveTest {
|
|||
|
||||
private String authorizationHeader(final String username, final String password) {
|
||||
final String auth = username + ":" + password;
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
|
||||
final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
|
||||
|
||||
return "Basic " + new String(encodedAuth);
|
||||
}
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
## Influx SDK Tutorial Project
|
||||
|
||||
### Relevant Article:
|
||||
- [Introduction to using InfluxDB with Java](http://www.baeldung.com/using-influxdb-with-java/)
|
||||
- [Using InfluxDB with Java](http://www.baeldung.com/java-influxdb)
|
||||
|
||||
|
||||
### Overview
|
||||
This Maven project contains the Java code for the article linked above.
|
||||
|
|
|
@ -8,18 +8,13 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Java Servlets](http://www.baeldung.com/intro-to-servlets)
|
||||
- [An MVC Example with Servlets and JSP](http://www.baeldung.com/mvc-servlet-jsp)
|
||||
- [Handling Cookies and a Session in a Java Servlet](http://www.baeldung.com/java-servlet-cookies-session)
|
||||
|
|
16
jmh/pom.xml
16
jmh/pom.xml
|
@ -10,8 +10,9 @@
|
|||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
@ -25,17 +26,6 @@
|
|||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${openjdk.jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -2,3 +2,4 @@
|
|||
- [Introduction to JSF Expression Language 3.0](http://www.baeldung.com/jsf-expression-language-el-3)
|
||||
- [Introduction to JSF EL 2](http://www.baeldung.com/intro-to-jsf-expression-language)
|
||||
- [JavaServer Faces (JSF) with Spring](http://www.baeldung.com/spring-jsf)
|
||||
- [Introduction to Primefaces](http://www.baeldung.com/jsf-primefaces)
|
||||
|
|
|
@ -73,6 +73,13 @@
|
|||
<scope>provided</scope>
|
||||
<version>${javax.servlet.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Primefaces -->
|
||||
<dependency>
|
||||
<groupId>org.primefaces</groupId>
|
||||
<artifactId>primefaces</artifactId>
|
||||
<version>6.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
@ -103,6 +110,6 @@
|
|||
|
||||
<!-- maven plugins -->
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
</properties>
|
||||
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,120 @@
|
|||
package com.baeldung.springintegration.controllers;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.el.ELContextEvent;
|
||||
import javax.el.ELContextListener;
|
||||
import javax.faces.bean.ManagedBean;
|
||||
import javax.faces.bean.ViewScoped;
|
||||
|
||||
@ManagedBean(name = "helloPFBean")
|
||||
@ViewScoped
|
||||
public class HelloPFBean {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
private String componentSuite;
|
||||
|
||||
private List<Technology> technologies;
|
||||
|
||||
private String inputText;
|
||||
private String outputText;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
firstName = "Hello";
|
||||
lastName = "Primefaces";
|
||||
|
||||
technologies = new ArrayList<Technology>();
|
||||
|
||||
Technology technology1 = new Technology();
|
||||
technology1.setCurrentVersion("10");
|
||||
technology1.setName("Java");
|
||||
|
||||
technologies.add(technology1);
|
||||
|
||||
Technology technology2 = new Technology();
|
||||
technology2.setCurrentVersion("5.0");
|
||||
technology2.setName("Spring");
|
||||
|
||||
technologies.add(technology2);
|
||||
}
|
||||
|
||||
public void onBlurEvent() {
|
||||
outputText = inputText.toUpperCase();
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getComponentSuite() {
|
||||
return componentSuite;
|
||||
}
|
||||
|
||||
public void setComponentSuite(String componentSuite) {
|
||||
this.componentSuite = componentSuite;
|
||||
}
|
||||
|
||||
public List<Technology> getTechnologies() {
|
||||
return technologies;
|
||||
}
|
||||
|
||||
public void setTechnologies(List<Technology> technologies) {
|
||||
this.technologies = technologies;
|
||||
}
|
||||
|
||||
public String getInputText() {
|
||||
return inputText;
|
||||
}
|
||||
|
||||
public void setInputText(String inputText) {
|
||||
this.inputText = inputText;
|
||||
}
|
||||
|
||||
public String getOutputText() {
|
||||
return outputText;
|
||||
}
|
||||
|
||||
public void setOutputText(String outputText) {
|
||||
this.outputText = outputText;
|
||||
}
|
||||
|
||||
public class Technology {
|
||||
private String name;
|
||||
private String currentVersion;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCurrentVersion() {
|
||||
return currentVersion;
|
||||
}
|
||||
|
||||
public void setCurrentVersion(String currentVersion) {
|
||||
this.currentVersion = currentVersion;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.springintegration.controllers;
|
||||
|
||||
import javax.faces.bean.ManagedBean;
|
||||
import javax.faces.bean.SessionScoped;
|
||||
|
||||
@ManagedBean(name = "helloPFMBean")
|
||||
@SessionScoped
|
||||
public class HelloPFMBean {
|
||||
|
||||
private String magicWord;
|
||||
|
||||
public String getMagicWord() {
|
||||
return magicWord;
|
||||
}
|
||||
|
||||
public void setMagicWord(String magicWord) {
|
||||
this.magicWord = magicWord;
|
||||
}
|
||||
|
||||
public String go() {
|
||||
if (this.magicWord != null && this.magicWord.toUpperCase()
|
||||
.equals("BAELDUNG")) {
|
||||
return "pm:success";
|
||||
}
|
||||
return "pm:failure";
|
||||
}
|
||||
|
||||
}
|
|
@ -25,6 +25,12 @@
|
|||
</var>
|
||||
</resource-bundle>
|
||||
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
|
||||
|
||||
<navigation-handler>
|
||||
org.primefaces.mobile.application.MobileNavigationHandler
|
||||
</navigation-handler>
|
||||
|
||||
<!-- <default-render-kit-id>PRIMEFACES_MOBILE</default-render-kit-id> -->
|
||||
</application>
|
||||
|
||||
<navigation-rule>
|
||||
|
|
|
@ -0,0 +1,59 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:h="http://java.sun.com/jsf/html"
|
||||
xmlns:f="http://java.sun.com/jsf/core"
|
||||
xmlns:ui="http://java.sun.com/jsf/facelets"
|
||||
xmlns:p="http://primefaces.org/ui">
|
||||
|
||||
<h:head>
|
||||
<title>Hello Primefaces</title>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<h:form id="primeForm">
|
||||
|
||||
<p:panelGrid columns="2">
|
||||
<h:outputText value="#{helloPFBean.firstName}" />
|
||||
<h:outputText value="#{helloPFBean.lastName}" />
|
||||
</p:panelGrid>
|
||||
|
||||
<h:panelGrid columns="2">
|
||||
<p:outputLabel for="jsfCompSuite" value="Component Suite" />
|
||||
<p:selectOneRadio id="jsfCompSuite"
|
||||
value="#{helloPFBean.componentSuite}">
|
||||
<f:selectItem itemLabel="ICEfaces" itemValue="ICEfaces" />
|
||||
<f:selectItem itemLabel="RichFaces" itemValue="RichFaces" />
|
||||
</p:selectOneRadio>
|
||||
</h:panelGrid>
|
||||
|
||||
<p:dataTable var="technology" value="#{helloPFBean.technologies}">
|
||||
<p:column headerText="Name">
|
||||
<h:outputText value="#{technology.name}" />
|
||||
</p:column>
|
||||
|
||||
<p:column headerText="Version">
|
||||
<h:outputText value="#{technology.currentVersion}" />
|
||||
</p:column>
|
||||
</p:dataTable>
|
||||
|
||||
<h:panelGrid columns="3">
|
||||
<h:outputText value="Blur event " />
|
||||
<p:inputText id="inputTextId" value="#{helloPFBean.inputText}">
|
||||
<p:ajax event="blur" update="outputTextId"
|
||||
listener="#{helloPFBean.onBlurEvent}" />
|
||||
</p:inputText>
|
||||
<h:outputText id="outputTextId" value="#{helloPFBean.outputText}" />
|
||||
<p:commandButton value="Open Dialog" icon="ui-icon-note"
|
||||
onclick="PF('exDialog').show();">
|
||||
</p:commandButton>
|
||||
</h:panelGrid>
|
||||
|
||||
<p:dialog header="Example dialog" widgetVar="exDialog" minHeight="40">
|
||||
<h:outputText value="Hello Baeldung!" />
|
||||
</p:dialog>
|
||||
|
||||
</h:form>
|
||||
|
||||
</h:body>
|
||||
</html>
|
|
@ -0,0 +1,38 @@
|
|||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:ui="http://java.sun.com/jsf/facelets"
|
||||
xmlns:h="http://java.sun.com/jsf/html"
|
||||
xmlns:f="http://java.sun.com/jsf/core"
|
||||
xmlns:p="http://primefaces.org/ui"
|
||||
xmlns:pm="http://primefaces.org/mobile">
|
||||
<f:view renderKitId="PRIMEFACES_MOBILE" />
|
||||
<h:head>
|
||||
</h:head>
|
||||
<h:body>
|
||||
<pm:page id="enter">
|
||||
<pm:header>
|
||||
<p:outputLabel value="Introduction to PFM"></p:outputLabel>
|
||||
</pm:header>
|
||||
<pm:content>
|
||||
<h:form id="enterForm">
|
||||
<pm:field>
|
||||
<p:outputLabel value="Enter Magic Word"></p:outputLabel>
|
||||
<p:inputText id="magicWord" value="#{helloPFMBean.magicWord}"></p:inputText>
|
||||
</pm:field>
|
||||
<p:commandButton value="Go!" action="#{helloPFMBean.go}"></p:commandButton>
|
||||
</h:form>
|
||||
</pm:content>
|
||||
</pm:page>
|
||||
<pm:page id="success">
|
||||
<pm:content>
|
||||
<p:outputLabel value="Correct!"></p:outputLabel>
|
||||
<p:button value="Back" outcome="pm:enter?transition=flow"></p:button>
|
||||
</pm:content>
|
||||
</pm:page>
|
||||
<pm:page id="failure">
|
||||
<pm:content>
|
||||
<p:outputLabel value="That is not the magic word"></p:outputLabel>
|
||||
<p:button value="Back" outcome="pm:enter?transition=flow"></p:button>
|
||||
</pm:content>
|
||||
</pm:page>
|
||||
</h:body>
|
||||
</html>
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Introduction to JSON Schema in Java](http://www.baeldung.com/introduction-to-json-schema-in-java)
|
||||
- [A Guide to FastJson](http://www.baeldung.com/????????)
|
||||
- [A Guide to FastJson](http://www.baeldung.com/fastjson)
|
||||
- [Introduction to JSONForms](http://www.baeldung.com/introduction-to-jsonforms)
|
||||
- [Introduction to JsonPath](http://www.baeldung.com/guide-to-jayway-jsonpath)
|
||||
- [Introduction to JSON-Java (org.json)](http://www.baeldung.com/java-org-json)
|
||||
|
|
|
@ -34,12 +34,6 @@
|
|||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
|
|
|
@ -7,4 +7,5 @@
|
|||
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
|
||||
- [Introduction to HikariCP](http://www.baeldung.com/hikaricp)
|
||||
- [Introduction to JCache](http://www.baeldung.com/jcache)
|
||||
- [A Guide to Apache Ignite](http://www.baeldung.com/apache-ignite)
|
||||
- [Apache Ignite with Spring Data](http://www.baeldung.com/apache-ignite-spring-data)
|
|
@ -61,7 +61,7 @@
|
|||
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
|
||||
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
|
||||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries)
|
||||
- [Asynchronous HTTP with async-http-client in Java](http://www.baeldung.com/async-http-client)
|
||||
- [Introduction to Smooks](http://www.baeldung.com/smooks)
|
||||
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
|
||||
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
|
||||
|
@ -70,7 +70,16 @@
|
|||
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
|
||||
- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils)
|
||||
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
|
||||
- [Introduction to jOOL](http://www.baeldung.com/jool)
|
||||
- [Consumer Driven Contracts with Pact](http://www.baeldung.com/pact-junit-consumer-driven-contracts)
|
||||
- [Apache Commons BeanUtils](http://www.baeldung.com/apache-commons-beanutils)
|
||||
- [Apache Commons Collections BidiMap](http://www.baeldung.com/commons-collections-bidi-map)
|
||||
- [Introduction to Atlassian Fugue](http://www.baeldung.com/java-fugue)
|
||||
- [Publish and Receive Messages with Nats Java Client](http://www.baeldung.com/nats-java-client)
|
||||
- [Java Concurrency Utility with JCTools](http://www.baeldung.com/java-concurrency-jc-tools)
|
||||
- [Apache Commons Collections MapUtils](http://www.baeldung.com/apache-commons-map-utils)
|
||||
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
|
||||
|
||||
|
||||
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.
|
||||
|
||||
|
|
|
@ -680,6 +680,12 @@
|
|||
<version>${unirest.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- javalin -->
|
||||
<dependency>
|
||||
<groupId>io.javalin</groupId>
|
||||
<artifactId>javalin</artifactId>
|
||||
<version>1.6.0</version>
|
||||
</dependency>
|
||||
<!-- Atlassian Fugue -->
|
||||
<dependency>
|
||||
<groupId>io.atlassian.fugue</groupId>
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.javalin;
|
||||
|
||||
import com.baeldung.javalin.User.UserController;
|
||||
import io.javalin.Javalin;
|
||||
|
||||
public class JavalinApp {
|
||||
public static void main(String[] args) {
|
||||
Javalin app = Javalin.create()
|
||||
.port(7000)
|
||||
.start();
|
||||
|
||||
app.get("/hello", ctx -> ctx.html("Hello, Javalin!"));
|
||||
app.get("/users", UserController.fetchAllUsernames);
|
||||
app.get("/users/:id", UserController.fetchById);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.javalin.User;
|
||||
|
||||
public class User {
|
||||
public final int id;
|
||||
public final String name;
|
||||
|
||||
public User(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package com.baeldung.javalin.User;
|
||||
|
||||
import io.javalin.Handler;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class UserController {
|
||||
public static Handler fetchAllUsernames = ctx -> {
|
||||
UserDao dao = UserDao.instance();
|
||||
Iterable<String> allUsers = dao.getAllUsernames();
|
||||
ctx.json(allUsers);
|
||||
};
|
||||
|
||||
public static Handler fetchById = ctx -> {
|
||||
int id = Integer.parseInt(Objects.requireNonNull(ctx.param("id")));
|
||||
UserDao dao = UserDao.instance();
|
||||
User user = dao.getUserById(id);
|
||||
if (user == null) {
|
||||
ctx.html("Not Found");
|
||||
} else {
|
||||
ctx.json(user);
|
||||
}
|
||||
};
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue