Merge branch 'master' of github.com:eugenp/tutorials into geroza/BAEL-9523_migrate-projects-to-paren-t-pom-2

This commit is contained in:
geroza 2018-12-29 15:20:52 -02:00
commit 6de56600db
72 changed files with 305 additions and 183 deletions

View File

@ -0,0 +1,24 @@
package com.baeldung;
import java.lang.reflect.Method;
public class Outer {
public void outerPublic() {
}
private void outerPrivate() {
}
class Inner {
public void innerPublic() {
outerPrivate();
}
public void innerPublicReflection(Outer ob) throws Exception {
Method method = ob.getClass().getDeclaredMethod("outerPrivate");
method.invoke(ob);
}
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
public class OuterUnitTest {
private static final String NEST_HOST_NAME = "com.baeldung.Outer";
@Test
public void whenGetNestHostFromOuter_thenGetNestHost() {
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
}
@Test
public void whenGetNestHostFromInner_thenGetNestHost() {
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
}
@Test
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
}
@Test
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
}
@Test
public void whenGetNestMembersForNestedClasses_thenGetAllNestedClasses() {
Set<String> nestMembers = Arrays.stream(Outer.Inner.class.getNestMembers())
.map(Class::getName)
.collect(Collectors.toSet());
is(nestMembers.size()).equals(2);
assertTrue(nestMembers.contains("com.baeldung.Outer"));
assertTrue(nestMembers.contains("com.baeldung.Outer$Inner"));
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.optional;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link Optional} in Java 11.
*/
public class OptionalUnitTest {
@Test
public void givenAnEmptyOptional_isEmpty_thenBehavesAsExpected() {
Optional<String> opt = Optional.of("Baeldung");
assertFalse(opt.isEmpty());
opt = Optional.ofNullable(null);
assertTrue(opt.isEmpty());
}
}

View File

@ -0,0 +1,27 @@
=========
## Core Java Collections List Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)

View File

@ -0,0 +1,48 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-collections-list</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<lombok.version>1.16.12</lombok.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,4 +1,4 @@
package com.baeldung;
package org.baeldung;
import com.google.common.collect.Lists;
import org.junit.Test;

View File

@ -3,36 +3,21 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
@ -40,15 +25,7 @@
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [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)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)

View File

@ -4,15 +4,24 @@ import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.SubjectAlternativeNameExtension;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
import sun.security.x509.CertificateExtensions;
import sun.security.x509.GeneralNames;
import sun.security.x509.GeneralName;
import sun.security.x509.GeneralNameInterface;
import sun.security.x509.DNSName;
import sun.security.x509.IPAddressName;
import sun.security.util.DerOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
@ -189,6 +198,23 @@ public class JavaKeyStoreUnitTest {
CertificateValidity validity = new CertificateValidity(validFrom, validTo);
certInfo.set(X509CertInfo.VALIDITY, validity);
GeneralNameInterface dnsName = new DNSName("baeldung.com");
DerOutputStream dnsNameOutputStream = new DerOutputStream();
dnsName.encode(dnsNameOutputStream);
GeneralNameInterface ipAddress = new IPAddressName("127.0.0.1");
DerOutputStream ipAddressOutputStream = new DerOutputStream();
ipAddress.encode(ipAddressOutputStream);
GeneralNames generalNames = new GeneralNames();
generalNames.add(new GeneralName(dnsName));
generalNames.add(new GeneralName(ipAddress));
CertificateExtensions ext = new CertificateExtensions();
ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames));
certInfo.set(X509CertInfo.EXTENSIONS, ext);
// Create certificate and sign it
X509CertImpl cert = new X509CertImpl(certInfo);
cert.sign(keyPair.getPrivate(), SHA1WITHRSA);
@ -202,4 +228,5 @@ public class JavaKeyStoreUnitTest {
return newCert;
}
}

View File

@ -32,8 +32,8 @@ public class EthereumRestController {
return CompletableFuture.supplyAsync(() -> {
try {
CompletableFuture<EthBlockNumber> result = web3Service.getBlockNumber();
responseTransfer.setMessage(result.get().toString());
EthBlockNumber result = web3Service.getBlockNumber();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
@ -51,8 +51,8 @@ public class EthereumRestController {
return CompletableFuture.supplyAsync(() -> {
try {
CompletableFuture<EthAccounts> result = web3Service.getEthAccounts();
responseTransfer.setMessage(result.get().toString());
EthAccounts result = web3Service.getEthAccounts();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
@ -70,8 +70,8 @@ public class EthereumRestController {
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
CompletableFuture<EthGetTransactionCount> result = web3Service.getTransactionCount();
responseTransfer.setMessage(result.get().toString());
EthGetTransactionCount result = web3Service.getTransactionCount();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
@ -88,8 +88,8 @@ public class EthereumRestController {
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
CompletableFuture<EthGetBalance> result = web3Service.getEthBalance();
responseTransfer.setMessage(result.get().toString());
EthGetBalance result = web3Service.getEthBalance();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}

View File

@ -47,47 +47,47 @@ public class Web3Service {
return "0x" + binary;
}
public CompletableFuture<EthBlockNumber> getBlockNumber() {
public EthBlockNumber getBlockNumber() {
EthBlockNumber result = new EthBlockNumber();
try {
result = this.web3j.ethBlockNumber().sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return CompletableFuture.completedFuture(result);
return result;
}
public CompletableFuture<EthAccounts> getEthAccounts() {
public EthAccounts getEthAccounts() {
EthAccounts result = new EthAccounts();
try {
result = this.web3j.ethAccounts().sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return CompletableFuture.completedFuture(result);
return result;
}
public CompletableFuture<EthGetTransactionCount> getTransactionCount() {
public EthGetTransactionCount getTransactionCount() {
EthGetTransactionCount result = new EthGetTransactionCount();
try {
result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return CompletableFuture.completedFuture(result);
return result;
}
public CompletableFuture<EthGetBalance> getEthBalance() {
public EthGetBalance getEthBalance() {
EthGetBalance result = new EthGetBalance();
try {
result = this.web3j.ethGetBalance(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return CompletableFuture.completedFuture(result);
return result;
}
public CompletableFuture<String> fromScratchContractExample() {
public String fromScratchContractExample() {
String contractAddress = "";
@ -108,13 +108,13 @@ public class Web3Service {
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return CompletableFuture.completedFuture(contractAddress);
return contractAddress;
}
@Async
public CompletableFuture<String> sendTx() {
public String sendTx() {
String transactionHash = "";
try {
@ -135,10 +135,10 @@ public class Web3Service {
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return CompletableFuture.completedFuture(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return CompletableFuture.completedFuture(transactionHash);
return transactionHash;
}
}

View File

@ -4,8 +4,6 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
public class EthereumContractUnitTest {
private Web3Service web3Service;
@ -17,14 +15,14 @@ public class EthereumContractUnitTest {
@Test
public void testContract() {
CompletableFuture<String> result = web3Service.fromScratchContractExample();
assert (result instanceof CompletableFuture);
String result = web3Service.fromScratchContractExample();
assert (result instanceof String);
}
@Test
public void sendTx() {
CompletableFuture<String> result = web3Service.sendTx();
assert (result instanceof CompletableFuture);
String result = web3Service.sendTx();
assert (result instanceof String);
}
@After

View File

@ -10,3 +10,4 @@
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)

View File

@ -43,3 +43,5 @@
- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
- [Replace a Character at a Specific Index in a String in Java](https://www.baeldung.com/java-replace-character-at-index)
- [Convert a Comma Separated String to a List in Java](https://www.baeldung.com/java-string-with-separator-to-list)

View File

@ -21,3 +21,5 @@
- [Custom Types in Hibernate](https://www.baeldung.com/hibernate-custom-types)
- [Criteria API An Example of IN Expressions](https://www.baeldung.com/jpa-criteria-api-in-expressions)
- [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby)
- [Hibernate 5 Bootstrapping API](https://www.baeldung.com/hibernate-5-bootstrapping-api)
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)

View File

@ -72,7 +72,6 @@
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -35,7 +35,6 @@ public class HibernateUtil {
Metadata metadata = metadataSources.getMetadataBuilder()
.applyBasicType(LocalDateStringType.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build();
} catch (IOException ex) {
throw new ExceptionInInitializerError(ex);

View File

@ -1,5 +0,0 @@
package com.baeldung.dao.repositories;
public interface InsertRepository<T> {
<S extends T> void insert(S entity);
}

View File

@ -1,7 +0,0 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.Person;
public interface PersonEntityManagerInsertRepository {
void insert(Person person);
}

View File

@ -1,10 +0,0 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonEntityManagerRepository extends JpaRepository<Person, Long>, PersonEntityManagerInsertRepository {
}

View File

@ -1,7 +0,0 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.Person;
public interface PersonQueryInsertRepository {
void insert(Person person);
}

View File

@ -1,16 +0,0 @@
package com.baeldung.dao.repositories;
import com.baeldung.domain.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonQueryRepository extends JpaRepository<Person, Long>, PersonQueryInsertRepository {
@Modifying
@Query(value = "INSERT INTO person (id, first_name, last_name) VALUES (:id,:firstName,:lastName)", nativeQuery = true)
void insertWithAnnotation(@Param("id") Long id, @Param("firstName") String firstName, @Param("lastName") String lastName);
}

View File

@ -1,21 +0,0 @@
package com.baeldung.dao.repositories.impl;
import com.baeldung.dao.repositories.PersonEntityManagerInsertRepository;
import com.baeldung.domain.Person;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Transactional
public class PersonEntityManagerInsertRepositoryImpl implements PersonEntityManagerInsertRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void insert(Person person) {
this.entityManager.persist(person);
}
}

View File

@ -1,24 +1,30 @@
package com.baeldung.dao.repositories.impl;
import com.baeldung.dao.repositories.PersonQueryInsertRepository;
import com.baeldung.domain.Person;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@Transactional
public class PersonQueryInsertRepositoryImpl implements PersonQueryInsertRepository {
@Repository
public class PersonInsertRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
public void insert(Person person) {
entityManager.createNativeQuery("INSERT INTO person (id,first_name, last_name) VALUES (?,?,?)")
@Transactional
public void insertWithQuery(Person person) {
entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)")
.setParameter(1, person.getId())
.setParameter(2, person.getFirstName())
.setParameter(3, person.getLastName())
.executeUpdate();
}
@Transactional
public void insertWithEntityManager(Person person) {
this.entityManager.persist(person);
}
}

View File

@ -1,21 +1,24 @@
package com.baeldung.dao.repositories;
import com.baeldung.dao.repositories.impl.PersonInsertRepository;
import com.baeldung.domain.Person;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
@RunWith(SpringRunner.class)
@DataJpaTest
@Import(PersonInsertRepository.class)
public class PersonInsertRepositoryIntegrationTest {
private static final Long ID = 1L;
@ -24,43 +27,23 @@ public class PersonInsertRepositoryIntegrationTest {
private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME);
@Autowired
private PersonQueryRepository personQueryRepository;
private PersonInsertRepository personInsertRepository;
@Autowired
private PersonEntityManagerRepository personEntityManagerRepository;
@BeforeEach
public void clearDB() {
personQueryRepository.deleteAll();
}
private EntityManager entityManager;
@Test
public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() {
insertPerson();
insertWithQuery();
assertPersonPersisted();
}
@Test
public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenDataIntegrityViolationExceptionIsThrown() {
assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> {
insertPerson();
insertPerson();
});
}
@Test
public void givenPersonEntity_whenInsertWithQueryAnnotation_thenPersonIsPersisted() {
insertPersonWithQueryAnnotation();
assertPersonPersisted();
}
@Test
public void givenPersonEntity_whenInsertedTwiceWithQueryAnnotation_thenDataIntegrityViolationExceptionIsThrown() {
assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> {
insertPersonWithQueryAnnotation();
insertPersonWithQueryAnnotation();
public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() {
assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> {
insertWithQuery();
insertWithQuery();
});
}
@ -72,31 +55,27 @@ public class PersonInsertRepositoryIntegrationTest {
}
@Test
public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenDataIntegrityViolationExceptionIsThrown() {
assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> {
public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() {
assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> {
insertPersonWithEntityManager();
insertPersonWithEntityManager();
});
}
private void insertPerson() {
personQueryRepository.insert(PERSON);
}
private void insertPersonWithQueryAnnotation() {
personQueryRepository.insertWithAnnotation(ID, FIRST_NAME, LAST_NAME);
private void insertWithQuery() {
personInsertRepository.insertWithQuery(PERSON);
}
private void insertPersonWithEntityManager() {
personEntityManagerRepository.insert(new Person(ID, FIRST_NAME, LAST_NAME));
personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME));
}
private void assertPersonPersisted() {
Optional<Person> personOptional = personQueryRepository.findById(PERSON.getId());
Person person = entityManager.find(Person.class, ID);
assertThat(personOptional.isPresent()).isTrue();
assertThat(personOptional.get().getId()).isEqualTo(PERSON.getId());
assertThat(personOptional.get().getFirstName()).isEqualTo(PERSON.getFirstName());
assertThat(personOptional.get().getLastName()).isEqualTo(PERSON.getLastName());
assertThat(person).isNotNull();
assertThat(person.getId()).isEqualTo(PERSON.getId());
assertThat(person.getFirstName()).isEqualTo(PERSON.getFirstName());
assertThat(person.getLastName()).isEqualTo(PERSON.getLastName());
}
}

View File

@ -379,6 +379,7 @@
<!--<module>core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-arrays</module>
<module>core-java-collections</module>
<module>core-java-collections-list</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>
@ -1090,6 +1091,7 @@
<!--<module>core-java-9</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>core-java-arrays</module>
<module>core-java-collections</module>
<module>core-java-collections-list</module>
<module>core-java-concurrency-basic</module>
<module>core-java-concurrency-collections</module>
<module>core-java-io</module>

View File

@ -85,6 +85,7 @@
<lombok.version>1.16.12</lombok.version>
<commons.io.version>2.5</commons.io.version>
<spring-boot.version>1.5.2.RELEASE</spring-boot.version>
<mockito.version>1.10.19</mockito.version>
</properties>
</project>

View File

@ -98,4 +98,18 @@ public class SpringResourceIntegrationTest {
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenClassPathResourceWithAbsoultePath_thenReadSuccessful() throws IOException {
final File resource = new ClassPathResource("/data/employees.dat", this.getClass()).getFile();
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
@Test
public void whenClassPathResourceWithRelativePath_thenReadSuccessful() throws IOException {
final File resource = new ClassPathResource("../../../data/employees.dat", SpringResourceIntegrationTest.class).getFile();
final String employees = new String(Files.readAllBytes(resource.toPath()));
assertEquals(EMPLOYEES_EXPECTED, employees);
}
}

View File

@ -20,65 +20,65 @@ all: clean create-keystore add-host create-truststore add-client
create-keystore:
# Generate a certificate authority (CA)
keytool -genkey -alias ca -ext BC=ca:true \
keytool -genkey -alias ca -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \
-keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \
-validity 3650 -dname $(DNAME_CA) \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
add-host:
# Generate a host certificate
keytool -genkey -alias $(HOSTNAME) \
keytool -genkey -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \
-keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \
-validity 3650 -dname $(DNAME_HOST) \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
# Generate a host certificate signing request
keytool -certreq -alias $(HOSTNAME) -ext BC=ca:true \
keytool -certreq -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \
-keyalg RSA -keysize 4096 -sigalg SHA512withRSA \
-validity 3650 -file "$(HOSTNAME).csr" \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
# Generate signed certificate with the certificate authority
keytool -gencert -alias ca \
keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \
-validity 3650 -sigalg SHA512withRSA \
-infile "$(HOSTNAME).csr" -outfile "$(HOSTNAME).crt" -rfc \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
# Import signed certificate into the keystore
keytool -import -trustcacerts -alias $(HOSTNAME) \
keytool -import -trustcacerts -alias $(HOSTNAME) -ext san=dns:localhost,ip:127.0.0.1 \
-file "$(HOSTNAME).crt" \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
export-authority:
# Export certificate authority
keytool -export -alias ca -file ca.crt -rfc \
keytool -export -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt -rfc \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
create-truststore: export-authority
# Import certificate authority into a new truststore
keytool -import -trustcacerts -noprompt -alias ca -file ca.crt \
keytool -import -trustcacerts -noprompt -alias ca -ext san=dns:localhost,ip:127.0.0.1 -file ca.crt \
-keystore $(TRUSTSTORE) -storepass $(PASSWORD)
add-client:
# Generate client certificate
keytool -genkey -alias $(CLIENTNAME) \
keytool -genkey -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \
-keyalg RSA -keysize 4096 -sigalg SHA512withRSA -keypass $(PASSWORD) \
-validity 3650 -dname $(DNAME_CLIENT) \
-keystore $(TRUSTSTORE) -storepass $(PASSWORD)
# Generate a host certificate signing request
keytool -certreq -alias $(CLIENTNAME) -ext BC=ca:true \
keytool -certreq -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 -ext BC=ca:true \
-keyalg RSA -keysize 4096 -sigalg SHA512withRSA \
-validity 3650 -file "$(CLIENTNAME).csr" \
-keystore $(TRUSTSTORE) -storepass $(PASSWORD)
# Generate signed certificate with the certificate authority
keytool -gencert -alias ca \
keytool -gencert -alias ca -ext san=dns:localhost,ip:127.0.0.1 \
-validity 3650 -sigalg SHA512withRSA \
-infile "$(CLIENTNAME).csr" -outfile "$(CLIENTNAME).crt" -rfc \
-keystore $(KEYSTORE) -storepass $(PASSWORD)
# Import signed certificate into the truststore
keytool -import -trustcacerts -alias $(CLIENTNAME) \
keytool -import -trustcacerts -alias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \
-file "$(CLIENTNAME).crt" \
-keystore $(TRUSTSTORE) -storepass $(PASSWORD)
# Export private certificate for importing into a browser
keytool -importkeystore -srcalias $(CLIENTNAME) \
keytool -importkeystore -srcalias $(CLIENTNAME) -ext san=dns:localhost,ip:127.0.0.1 \
-srckeystore $(TRUSTSTORE) -srcstorepass $(PASSWORD) \
-destkeystore "$(CLIENTNAME).p12" -deststorepass $(PASSWORD) \
-deststoretype PKCS12