This commit is contained in:
Chirag Dewan 2019-07-24 21:30:53 +05:30
commit b32a91a8ff
405 changed files with 5177 additions and 1746 deletions

View File

@ -32,7 +32,7 @@ Running a Spring Boot module
==================== ====================
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
#Running Tests ###Running Tests
The command `mvn clean install` will run the unit tests in a module. The command `mvn clean install` will run the unit tests in a module.
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first` To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`

View File

@ -6,4 +6,4 @@
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity) - [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted) - [Checking If a List Is Sorted in Java](https://www.baeldung.com/java-check-if-list-sorted)
- [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle) - [Checking if a Java Graph has a Cycle](https://www.baeldung.com/java-graph-has-a-cycle)
- [A Guide to the Folding Technique](https://www.baeldung.com/folding-hashing-technique) - [A Guide to the Folding Technique in Java](https://www.baeldung.com/folding-hashing-technique)

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.shellsort;
public class ShellSort {
public static void sort(int arrayToSort[]) {
int n = arrayToSort.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int key = arrayToSort[i];
int j = i;
while (j >= gap && arrayToSort[j - gap] > key) {
arrayToSort[j] = arrayToSort[j - gap];
j -= gap;
}
arrayToSort[j] = key;
}
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.shellsort;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ShellSortUnitTest {
@Test
public void givenUnsortedArray_whenShellSort_thenSortedAsc() {
int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8};
ShellSort.sort(input);
int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82};
assertArrayEquals("the two arrays are not equal", expected, input);
}
}

View File

@ -18,12 +18,6 @@
<groupId>org.axonframework</groupId> <groupId>org.axonframework</groupId>
<artifactId>axon-spring-boot-starter</artifactId> <artifactId>axon-spring-boot-starter</artifactId>
<version>${axon.version}</version> <version>${axon.version}</version>
<exclusions>
<exclusion>
<groupId>org.axonframework</groupId>
<artifactId>axon-server-connector</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -58,7 +52,7 @@
</dependencies> </dependencies>
<properties> <properties>
<axon.version>4.0.3</axon.version> <axon.version>4.1.2</axon.version>
</properties> </properties>
</project> </project>

View File

@ -13,6 +13,7 @@ import com.baeldung.axon.coreapi.commands.ShipOrderCommand;
import com.baeldung.axon.coreapi.events.OrderConfirmedEvent; import com.baeldung.axon.coreapi.events.OrderConfirmedEvent;
import com.baeldung.axon.coreapi.events.OrderPlacedEvent; import com.baeldung.axon.coreapi.events.OrderPlacedEvent;
import com.baeldung.axon.coreapi.events.OrderShippedEvent; import com.baeldung.axon.coreapi.events.OrderShippedEvent;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
@Aggregate @Aggregate
public class OrderAggregate { public class OrderAggregate {
@ -34,7 +35,7 @@ public class OrderAggregate {
@CommandHandler @CommandHandler
public void handle(ShipOrderCommand command) { public void handle(ShipOrderCommand command) {
if (!orderConfirmed) { if (!orderConfirmed) {
throw new IllegalStateException("Cannot ship an order which has not been confirmed yet."); throw new UnconfirmedOrderException();
} }
apply(new OrderShippedEvent(orderId)); apply(new OrderShippedEvent(orderId));
@ -43,12 +44,12 @@ public class OrderAggregate {
@EventSourcingHandler @EventSourcingHandler
public void on(OrderPlacedEvent event) { public void on(OrderPlacedEvent event) {
this.orderId = event.getOrderId(); this.orderId = event.getOrderId();
orderConfirmed = false; this.orderConfirmed = false;
} }
@EventSourcingHandler @EventSourcingHandler
public void on(OrderConfirmedEvent event) { public void on(OrderConfirmedEvent event) {
orderConfirmed = true; this.orderConfirmed = true;
} }
protected OrderAggregate() { protected OrderAggregate() {

View File

@ -0,0 +1,8 @@
package com.baeldung.axon.coreapi.exceptions;
public class UnconfirmedOrderException extends IllegalStateException {
public UnconfirmedOrderException() {
super("Cannot ship an order which has not been confirmed yet.");
}
}

View File

@ -5,6 +5,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.axonframework.config.ProcessingGroup;
import org.axonframework.eventhandling.EventHandler; import org.axonframework.eventhandling.EventHandler;
import org.axonframework.queryhandling.QueryHandler; import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -16,6 +17,7 @@ import com.baeldung.axon.coreapi.queries.FindAllOrderedProductsQuery;
import com.baeldung.axon.coreapi.queries.OrderedProduct; import com.baeldung.axon.coreapi.queries.OrderedProduct;
@Service @Service
@ProcessingGroup("ordered-products")
public class OrderedProductsEventHandler { public class OrderedProductsEventHandler {
private final Map<String, OrderedProduct> orderedProducts = new HashMap<>(); private final Map<String, OrderedProduct> orderedProducts = new HashMap<>();

View File

@ -0,0 +1 @@
spring.application.name=Order Management Service

View File

@ -2,6 +2,7 @@ package com.baeldung.axon.commandmodel;
import java.util.UUID; import java.util.UUID;
import com.baeldung.axon.coreapi.exceptions.UnconfirmedOrderException;
import org.axonframework.test.aggregate.AggregateTestFixture; import org.axonframework.test.aggregate.AggregateTestFixture;
import org.axonframework.test.aggregate.FixtureConfiguration; import org.axonframework.test.aggregate.FixtureConfiguration;
import org.junit.*; import org.junit.*;
@ -41,12 +42,12 @@ public class OrderAggregateUnitTest {
} }
@Test @Test
public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowIllegalStateException() { public void givenOrderPlacedEvent_whenShipOrderCommand_thenShouldThrowUnconfirmedOrderException() {
String orderId = UUID.randomUUID().toString(); String orderId = UUID.randomUUID().toString();
String product = "Deluxe Chair"; String product = "Deluxe Chair";
fixture.given(new OrderPlacedEvent(orderId, product)) fixture.given(new OrderPlacedEvent(orderId, product))
.when(new ShipOrderCommand(orderId)) .when(new ShipOrderCommand(orderId))
.expectException(IllegalStateException.class); .expectException(UnconfirmedOrderException.class);
} }
@Test @Test

View File

@ -0,0 +1,45 @@
package com.baeldung.array.looping;
public class LoopDiagonally {
public String loopDiagonally(String[][] twoDArray) {
int length = twoDArray.length;
int diagonalLines = (length + length) - 1;
int itemsInDiagonal = 0;
int midPoint = (diagonalLines / 2) + 1;
StringBuilder output = new StringBuilder();
for (int i = 1; i <= diagonalLines; i++) {
StringBuilder items = new StringBuilder();
int rowIndex;
int columnIndex;
if (i <= midPoint) {
itemsInDiagonal++;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (i - j) - 1;
columnIndex = j;
items.append(twoDArray[rowIndex][columnIndex]);
}
} else {
itemsInDiagonal--;
for (int j = 0; j < itemsInDiagonal; j++) {
rowIndex = (length - 1) - j;
columnIndex = (i - length) + j;
items.append(twoDArray[rowIndex][columnIndex]);
}
}
if (i != diagonalLines) {
output.append(items).append(" ");
} else {
output.append(items);
}
}
return output.toString();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.array.looping;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class LoopDiagonallyTest {
@Test
public void twoArrayIsLoopedDiagonallyAsExpected() {
LoopDiagonally loopDiagonally = new LoopDiagonally();
String[][] twoDArray = {{"a", "b", "c"},
{"d", "e", "f"},
{"g", "h", "i"}};
String output = loopDiagonally.loopDiagonally(twoDArray);
assertEquals("a db gec hf i", output);
}
}

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [String API Updates in Java 12](https://www.baeldung.com/java12-string-api)

View File

@ -0,0 +1,34 @@
package com.baeldung.java_8_features.groupingby;
public class Tuple {
private BlogPostType type;
private String author;
public Tuple(BlogPostType type, String author) {
super();
this.type = type;
this.author = author;
}
public BlogPostType getType() {
return type;
}
public void setType(BlogPostType type) {
this.type = type;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Tuple [type=" + type + ", author=" + author + ", getType()=" + getType() + ", getAuthor()=" + getAuthor() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
}
}

View File

@ -259,4 +259,15 @@ public class OptionalUnitTest {
LOG.debug("Getting default value..."); LOG.debug("Getting default value...");
return "Default Value"; return "Default Value";
} }
// Uncomment code when code base is compatiable with Java 11
// @Test
// public void givenAnEmptyOptional_thenIsEmptyBehavesAsExpected() {
// Optional<String> opt = Optional.of("Baeldung");
// assertFalse(opt.isEmpty());
//
// opt = Optional.ofNullable(null);
// assertTrue(opt.isEmpty());
// }
} }

View File

@ -42,7 +42,7 @@ public class CoreJavaCollectionsUnitTest {
@Test(expected = UnsupportedOperationException.class) @Test(expected = UnsupportedOperationException.class)
public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() { public final void givenUsingGuavaBuilder_whenUnmodifiableListIsCreatedFromOriginal_thenNoLongerModifiable() {
final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three")); final List<String> list = new ArrayList<String>(Arrays.asList("one", "two", "three"));
final ImmutableList<Object> unmodifiableList = ImmutableList.builder().addAll(list).build(); final ImmutableList<String> unmodifiableList = ImmutableList.<String>builder().addAll(list).build();
unmodifiableList.add("four"); unmodifiableList.add("four");
} }

View File

@ -17,3 +17,4 @@
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable) - [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety) - [What is Thread-Safety and How to Achieve it?](https://www.baeldung.com/java-thread-safety)
- [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread) - [How to Start a Thread in Java](https://www.baeldung.com/java-start-thread)
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Will an Error Be Caught by Catch Block in Java?](https://www.baeldung.com/java-error-catch)

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)

View File

@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount {
this.balance = 0.0f; this.balance = 0.0f;
} }
} }
class BankAccountChainedConstructors extends BankAccount {
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountChainedConstructors(String name) {
this(name, LocalDateTime.now(), 0.0f);
}
}

View File

@ -1,15 +1,14 @@
package com.baeldung.constructors; package com.baeldung.constructors;
import com.baeldung.constructors.*; import com.google.common.collect.Comparators;
import org.junit.Test;
import java.util.logging.Logger;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.Month; import java.time.Month;
import java.util.ArrayList;
import java.util.logging.Logger;
import org.junit.Test; import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ConstructorUnitTest { public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName()); final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@ -17,26 +16,28 @@ public class ConstructorUnitTest {
@Test @Test
public void givenNoExplicitContructor_whenUsed_thenFails() { public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount(); BankAccount account = new BankAccount();
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class); assertThatThrownBy(() -> {
account.toString();
}).isInstanceOf(Exception.class);
} }
@Test @Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() { public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor(); BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> { assertThatCode(() -> {
account.toString(); account.toString();
}).doesNotThrowAnyException(); }).doesNotThrowAnyException();
} }
@Test @Test
public void givenParameterisedConstructor_whenUsed_thenSucceeds() { public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00); LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountParameterizedConstructor account = BankAccountParameterizedConstructor account =
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f); new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> { assertThatCode(() -> {
account.toString(); account.toString();
}).doesNotThrowAnyException(); }).doesNotThrowAnyException();
} }
@Test @Test
@ -47,7 +48,16 @@ public class ConstructorUnitTest {
assertThat(account.getName()).isEqualTo(newAccount.getName()); assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened()); assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
assertThat(newAccount.getBalance()).isEqualTo(0.0f); assertThat(newAccount.getBalance()).isEqualTo(0.0f);
} }
@Test
public void givenChainedConstructor_whenUsed_thenMaintainsLogic() {
BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim");
BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f);
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getBalance()).isEqualTo(newAccount.getBalance());
}
} }

View File

@ -18,7 +18,6 @@
- [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces) - [A Guide to Inner Interfaces in Java](http://www.baeldung.com/java-inner-interfaces)
- [Recursion In Java](http://www.baeldung.com/java-recursion) - [Recursion In Java](http://www.baeldung.com/java-recursion)
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize) - [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system) - [Quick Guide to java.lang.System](http://www.baeldung.com/java-lang-system)
- [Using Java Assertions](http://www.baeldung.com/java-assert) - [Using Java Assertions](http://www.baeldung.com/java-assert)

View File

@ -0,0 +1,40 @@
package com.baeldung.core.pwd;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Paths;
public final class CurrentDirectoryFetcher {
public static void main(String[] args) {
System.out.printf("Current Directory Using Java System API: %s%n", currentDirectoryUsingSystemProperties());
System.out.printf("Current Directory Using Java IO File API: %s%n", currentDirectoryUsingFile());
System.out.printf("Current Directory Using Java NIO FileSystems API: %s%n", currentDirectoryUsingFileSystems());
System.out.printf("Current Directory Using Java NIO Paths API: %s%n", currentDirectoryUsingPaths());
}
public static String currentDirectoryUsingSystemProperties() {
return System.getProperty("user.dir");
}
public static String currentDirectoryUsingPaths() {
return Paths.get("")
.toAbsolutePath()
.toString();
}
public static String currentDirectoryUsingFileSystems() {
return FileSystems.getDefault()
.getPath("")
.toAbsolutePath()
.toString();
}
public static String currentDirectoryUsingFile() {
return new File("").getAbsolutePath();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.core.pwd;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CurrentDirectoryFetcherTest {
private static final String CURRENT_DIR = "core-java-os";
@Test
public void whenUsingSystemProperties_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingSystemProperties()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingPaths()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFileSystems()
.endsWith(CURRENT_DIR));
}
@Test
public void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
assertTrue(CurrentDirectoryFetcher.currentDirectoryUsingFile()
.endsWith(CURRENT_DIR));
}
}

View File

@ -37,7 +37,6 @@
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions) - [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception) - [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
- [Java Try with Resources](https://www.baeldung.com/java-try-with-resources) - [Java Try with Resources](https://www.baeldung.com/java-try-with-resources)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class) - [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding) - [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)

Binary file not shown.

View File

@ -22,6 +22,10 @@ public class UnitTestNamingConventionRule extends AbstractJavaRule {
String className = node.getImage(); String className = node.getImage();
Objects.requireNonNull(className); Objects.requireNonNull(className);
if (className.endsWith("SpringContextTest")) {
return data;
}
if (className.endsWith("Tests") if (className.endsWith("Tests")
|| (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) { || (className.endsWith("Test") && allowedEndings.stream().noneMatch(className::endsWith))) {
addViolation(data, node); addViolation(data, node);

View File

@ -165,7 +165,7 @@ public class JacksonSerializationIgnoreUnitTest {
} }
@Test @Test
public final void givenIgnoringNullFieldsOnClass_whenWritingObjectWithNullField_thenFieldIsIgnored() throws JsonProcessingException { public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper(); final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull(); final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
@ -178,7 +178,7 @@ public class JacksonSerializationIgnoreUnitTest {
} }
@Test @Test
public final void givenIgnoringNullFieldsGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException { public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper(); final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL); mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto(); final MyDto dtoObject = new MyDto();

View File

@ -4,3 +4,4 @@
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring) - [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)
- [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords) - [Removing Stopwords from a String in Java](https://www.baeldung.com/java-string-remove-stopwords)
- [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings) - [Blank and Empty Strings in Java](https://www.baeldung.com/java-blank-empty-strings)
- [String Initialization in Java](https://www.baeldung.com/java-string-initialization)

View File

@ -1,4 +1,4 @@
package com.baeldung.string; package com.baeldung.string.multiline;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@ -1,6 +0,0 @@
## Relevant articles:
- [JHipster with a Microservice Architecture](http://www.baeldung.com/jhipster-microservices)
- [Intro to JHipster](http://www.baeldung.com/jhipster)
- [Building a Basic UAA-Secured JHipster Microservice](https://www.baeldung.com/jhipster-uaa-secured-micro-service)
- [Creating New Roles and Authorities in JHipster](https://www.baeldung.com/jhipster-new-roles)

5
libraries-io/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp)

40
libraries-io/pom.xml Normal file
View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-io</artifactId>
<name>libraries-io</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- sftp file transfer -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>${jsch.version}</version>
</dependency>
<dependency>
<groupId>com.hierynomus</groupId>
<artifactId>sshj</artifactId>
<version>${sshj.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-vfs2</artifactId>
<version>${vfs.version}</version>
</dependency>
</dependencies>
<properties>
<!-- sftp -->
<jsch.version>0.1.55</jsch.version>
<sshj.version>0.27.0</sshj.version>
<vfs.version>2.4</vfs.version>
</properties>
</project>

View File

@ -0,0 +1 @@
This is a sample text content

View File

@ -0,0 +1,106 @@
package org.baeldung.java.io.remote;
import java.io.IOException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VFS;
import org.junit.Test;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
public class SftpFileTransferLiveTest {
private String remoteHost = "HOST_NAME_HERE";
private String username = "USERNAME_HERE";
private String password = "PASSWORD_HERE";
private String localFile = "src/main/resources/input.txt";
private String remoteFile = "welcome.txt";
private String localDir = "src/main/resources/";
private String remoteDir = "remote_sftp_test/";
private String knownHostsFileLoc = "/Users/USERNAME/known_hosts_sample";
@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.put(localFile, remoteDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
ChannelSftp channelSftp = setupJsch();
channelSftp.connect();
channelSftp.get(remoteFile, localDir + "jschFile.txt");
channelSftp.exit();
}
@Test
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.put(localFile, remoteDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
SSHClient sshClient = setupSshj();
SFTPClient sftpClient = sshClient.newSFTPClient();
sftpClient.get(remoteFile, localDir + "sshjFile.txt");
sftpClient.close();
sshClient.disconnect();
}
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
remote.copyFrom(local, Selectors.SELECT_SELF);
local.close();
remote.close();
}
@Test
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
FileSystemManager manager = VFS.getManager();
FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
local.copyFrom(remote, Selectors.SELECT_SELF);
local.close();
remote.close();
}
// ====== ssh-keyscan -H -t rsa remoteHost >> known_hosts_sample
private ChannelSftp setupJsch() throws JSchException {
JSch jsch = new JSch();
jsch.setKnownHosts(knownHostsFileLoc);
Session jschSession = jsch.getSession(username, remoteHost);
jschSession.setPassword(password);
//jschSession.setConfig("StrictHostKeyChecking", "no");
jschSession.connect();
return (ChannelSftp) jschSession.openChannel("sftp");
}
private SSHClient setupSshj() throws IOException {
SSHClient client = new SSHClient();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(remoteHost);
client.authPassword(username, password);
return client;
}
}

View File

@ -42,7 +42,6 @@
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [Introduction to Smooks](http://www.baeldung.com/smooks) - [Introduction to Smooks](http://www.baeldung.com/smooks)
- [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan) - [A Guide to Infinispan in Java](http://www.baeldung.com/infinispan)
- [Introduction to OpenCSV](http://www.baeldung.com/opencsv)
- [A Guide to Unirest](http://www.baeldung.com/unirest) - [A Guide to Unirest](http://www.baeldung.com/unirest)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java) - [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy) - [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)

View File

@ -13,9 +13,9 @@ public class GetterLazy {
private static final String DELIMETER = ","; private static final String DELIMETER = ",";
@Getter(lazy = true) @Getter(lazy = true)
private final Map<String, Long> transactions = readTxnsFromFile(); private final Map<String, Long> transactions = getTransactions();
private Map<String, Long> readTxnsFromFile() { private Map<String, Long> getTransactions() {
final Map<String, Long> cache = new HashMap<>(); final Map<String, Long> cache = new HashMap<>();
List<String> txnRows = readTxnListFromFile(); List<String> txnRows = readTxnListFromFile();

View File

@ -0,0 +1,26 @@
package com.baeldung.lombok.intro;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import lombok.SneakyThrows;
import lombok.Synchronized;
public class Utility {
@SneakyThrows
public String resourceAsString() throws IOException {
try (InputStream is = this.getClass().getResourceAsStream("sure_in_my_jar.txt")) {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
return br.lines().collect(Collectors.joining("\n"));
}
}
@Synchronized
public void putValueInCache(String key, String value) {
System.out.println("Thread safe here with key : [" + key + "] and value[" + value + "]");
}
}

View File

@ -0,0 +1 @@
Hello

View File

@ -28,8 +28,31 @@
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
<properties> <properties>
<spring.version>4.3.22.RELEASE</spring.version> <spring.version>4.3.22.RELEASE</spring.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -20,3 +20,4 @@
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods) - [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
- [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern) - [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern)
- [Currying in Java](https://www.baeldung.com/java-currying) - [Currying in Java](https://www.baeldung.com/java-currying)
- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern)

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public abstract class AuthenticationProcessor { public abstract class AuthenticationProcessor {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public interface AuthenticationProvider { public interface AuthenticationProvider {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public class OAuthAuthenticationProcessor extends AuthenticationProcessor { public class OAuthAuthenticationProcessor extends AuthenticationProcessor {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public class OAuthTokenProvider implements AuthenticationProvider { public class OAuthTokenProvider implements AuthenticationProvider {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public class SamlAuthenticationProvider implements AuthenticationProvider { public class SamlAuthenticationProvider implements AuthenticationProvider {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor { public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.chainofresponsibility; package com.baeldung.chainofresponsibility;
public class UsernamePasswordProvider implements AuthenticationProvider { public class UsernamePasswordProvider implements AuthenticationProvider {

View File

@ -1,10 +1,10 @@
package com.baeldung.pattern.command.client; package com.baeldung.command.client;
import com.baeldung.pattern.command.command.OpenTextFileOperation; import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.pattern.command.command.SaveTextFileOperation; import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation; import com.baeldung.command.command.TextFileOperation;
import com.baeldung.pattern.command.invoker.TextFileOperationExecutor; import com.baeldung.command.invoker.TextFileOperationExecutor;
import com.baeldung.pattern.command.receiver.TextFile; import com.baeldung.command.receiver.TextFile;
public class TextFileApplication { public class TextFileApplication {

View File

@ -1,6 +1,6 @@
package com.baeldung.pattern.command.command; package com.baeldung.command.command;
import com.baeldung.pattern.command.receiver.TextFile; import com.baeldung.command.receiver.TextFile;
public class OpenTextFileOperation implements TextFileOperation { public class OpenTextFileOperation implements TextFileOperation {

View File

@ -1,6 +1,6 @@
package com.baeldung.pattern.command.command; package com.baeldung.command.command;
import com.baeldung.pattern.command.receiver.TextFile; import com.baeldung.command.receiver.TextFile;
public class SaveTextFileOperation implements TextFileOperation { public class SaveTextFileOperation implements TextFileOperation {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.command.command; package com.baeldung.command.command;
@FunctionalInterface @FunctionalInterface
public interface TextFileOperation { public interface TextFileOperation {

View File

@ -1,6 +1,6 @@
package com.baeldung.pattern.command.invoker; package com.baeldung.command.invoker;
import com.baeldung.pattern.command.command.TextFileOperation; import com.baeldung.command.command.TextFileOperation;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.command.receiver; package com.baeldung.command.receiver;
public class TextFile { public class TextFile {

View File

@ -1,11 +1,9 @@
package com.baeldung.pattern.templatemethod.application; package com.baeldung.templatemethod.application;
import com.baeldung.pattern.templatemethod.model.Computer; import com.baeldung.templatemethod.model.Computer;
import com.baeldung.pattern.templatemethod.model.StandardComputer; import com.baeldung.templatemethod.model.ComputerBuilder;
import com.baeldung.pattern.templatemethod.model.HighEndComputer; import com.baeldung.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.pattern.templatemethod.model.ComputerBuilder; import com.baeldung.templatemethod.model.StandardComputerBuilder;
import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder;
public class Application { public class Application {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;

View File

@ -1,6 +1,5 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
import com.baeldung.pattern.templatemethod.model.Computer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;

View File

@ -1,6 +1,5 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
import com.baeldung.pattern.templatemethod.model.Computer;
import java.util.Map; import java.util.Map;
public class HighEndComputer extends Computer { public class HighEndComputer extends Computer {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
public class HighEndComputerBuilder extends ComputerBuilder { public class HighEndComputerBuilder extends ComputerBuilder {

View File

@ -1,6 +1,5 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
import com.baeldung.pattern.templatemethod.model.Computer;
import java.util.Map; import java.util.Map;
public class StandardComputer extends Computer { public class StandardComputer extends Computer {

View File

@ -1,4 +1,4 @@
package com.baeldung.pattern.templatemethod.model; package com.baeldung.templatemethod.model;
public class StandardComputerBuilder extends ComputerBuilder { public class StandardComputerBuilder extends ComputerBuilder {

View File

@ -1,14 +1,9 @@
package com.baeldung.chainofresponsibility; package com.baeldung.chainofresponsibility;
import org.junit.Test;
import com.baeldung.pattern.chainofresponsibility.AuthenticationProcessor;
import com.baeldung.pattern.chainofresponsibility.OAuthAuthenticationProcessor;
import com.baeldung.pattern.chainofresponsibility.OAuthTokenProvider;
import com.baeldung.pattern.chainofresponsibility.UsernamePasswordProvider;
import com.baeldung.pattern.chainofresponsibility.SamlAuthenticationProvider;
import com.baeldung.pattern.chainofresponsibility.UsernamePasswordAuthenticationProcessor;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ChainOfResponsibilityIntegrationTest { public class ChainOfResponsibilityIntegrationTest {
private static AuthenticationProcessor getChainOfAuthProcessor() { private static AuthenticationProcessor getChainOfAuthProcessor() {

View File

@ -1,10 +1,12 @@
package com.baeldung.pattern.command.test; package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.pattern.command.command.OpenTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.receiver.TextFile;
public class OpenTextFileOperationUnitTest { public class OpenTextFileOperationUnitTest {

View File

@ -1,10 +1,12 @@
package com.baeldung.pattern.command.test; package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.pattern.command.command.SaveTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test; import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.receiver.TextFile;
public class SaveTextFileOperationUnitTest { public class SaveTextFileOperationUnitTest {

View File

@ -1,14 +1,17 @@
package com.baeldung.pattern.command.test; package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.pattern.command.command.OpenTextFileOperation;
import com.baeldung.pattern.command.command.SaveTextFileOperation;
import com.baeldung.pattern.command.command.TextFileOperation;
import com.baeldung.pattern.command.invoker.TextFileOperationExecutor;
import com.baeldung.pattern.command.receiver.TextFile;
import java.util.function.Function; import java.util.function.Function;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.invoker.TextFileOperationExecutor;
import com.baeldung.command.receiver.TextFile;
public class TextFileOperationExecutorUnitTest { public class TextFileOperationExecutorUnitTest {
@ -65,4 +68,11 @@ public class TextFileOperationExecutorUnitTest {
Function<SaveTextFileOperation, String> executeMethodReference = SaveTextFileOperation::execute; Function<SaveTextFileOperation, String> executeMethodReference = SaveTextFileOperation::execute;
assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt"); assertThat(executeMethodReference.apply(new SaveTextFileOperation(new TextFile("file1.txt")))).isEqualTo("Saving file file1.txt");
} }
@Test
public void givenOpenAndSaveTextFileOperationExecutorInstance_whenCalledExecuteOperationWithLambdaExpression_thenBothAssertion() {
TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor();
assertThat(textFileOperationExecutor.executeOperation(() -> "Opening file file1.txt")).isEqualTo("Opening file file1.txt");
assertThat(textFileOperationExecutor.executeOperation(() -> "Saving file file1.txt")).isEqualTo("Saving file file1.txt");
}
} }

View File

@ -1,9 +1,11 @@
package com.baeldung.pattern.command.test; package com.baeldung.command.test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.pattern.command.receiver.TextFile;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.command.receiver.TextFile;
public class TextFileUnitTest { public class TextFileUnitTest {

View File

@ -1,14 +1,16 @@
package com.baeldung.templatemethod.test; package com.baeldung.templatemethod.test;
import com.baeldung.pattern.templatemethod.model.Computer; import static org.hamcrest.CoreMatchers.instanceOf;
import com.baeldung.pattern.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.pattern.templatemethod.model.StandardComputerBuilder;
import org.junit.Assert;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat; import com.baeldung.templatemethod.model.Computer;
import com.baeldung.templatemethod.model.HighEndComputerBuilder;
import com.baeldung.templatemethod.model.StandardComputerBuilder;
public class TemplateMethodPatternIntegrationTest { public class TemplateMethodPatternIntegrationTest {

View File

@ -13,3 +13,4 @@
- [Defining JPA Entities](https://www.baeldung.com/jpa-entities) - [Defining JPA Entities](https://www.baeldung.com/jpa-entities)
- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation) - [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation)
- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values) - [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values)
- [Persisting Enums in JPA](https://www.baeldung.com/jpa-persisting-enums-in-jpa)

View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Overview of JPA/Hibernate Cascade Types](https://www.baeldung.com/jpa-cascade-types)

View File

@ -0,0 +1,5 @@
/target/
.settings/
.classpath
.project
.mvn/

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-mysql</artifactId>
<version>0.1.0</version>
<name>spring-boot-mysql</name>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-mysql-timezone</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mysql-connector-java.version>8.0.12</mysql-connector-java.version>
</properties>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
@SpringBootApplication
public class Application {
@PostConstruct
void started() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.boot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class Controller {
@Autowired
UserRepository userRepository;
@GetMapping
public User get() {
User user = new User();
userRepository.save(user);
return user;
}
@GetMapping("/find")
public List<User> find() {
List<User> users = userRepository.findAll();
return users;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.boot;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.*;
import java.util.Date;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@CreatedDate
private Date createdDate = new Date();
public Date getCreatedDate() {
return createdDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.boot;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.io.Serializable;
@Repository
public interface UserRepository extends JpaRepository<User, Serializable> {
}

View File

@ -0,0 +1,14 @@
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false
username: root
password:
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
jdbc:
time_zone: UTC

View File

@ -0,0 +1,19 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,67 @@
package org.baeldung;
import java.io.IOException;
import java.util.HashMap;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
public class SpringContextTest {
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;";
public static final String DATA_TABLE_NAME = "book";
@Autowired
private CassandraAdminOperations adminTemplate;
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
final Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY);
Thread.sleep(5000);
}
@Before
public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
}
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
@After
public void dropTable() {
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
}
@AfterClass
public static void stopCassandraEmbedded() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.eclipselink.springdata.EclipselinkSpringDataApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EclipselinkSpringDataApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.data.gemfire.function.GemfireConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -12,3 +12,4 @@
- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) - [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) - [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.spring.data.keyvalue.SpringDataKeyValueApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringDataKeyValueApplication.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,19 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class)
@ActiveProfiles(profiles = "test")
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.redis.config.RedisConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RedisConfig.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.solr.config.SolrConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SolrConfig.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.baeldung.spring.PersistenceConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -7,10 +7,10 @@
<name>spring-hibernate4</name> <name>spring-hibernate4</name>
<parent> <parent>
<artifactId>parent-spring-4</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId> <version>0.0.1-SNAPSHOT</version>
<version>1.0.0-SNAPSHOT</version> <relativePath>../../parent-spring-4</relativePath>
<relativePath>../../</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -175,7 +175,6 @@
<!-- maven plugins --> <!-- maven plugins -->
<maven-resources-plugin.version>2.7</maven-resources-plugin.version> <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<!-- <hibernate4-maven-plugin.version>1.1.0</hibernate4-maven-plugin.version> --> <!-- <hibernate4-maven-plugin.version>1.1.0</hibernate4-maven-plugin.version> -->
</properties> </properties>

View File

@ -0,0 +1,18 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung;
import org.baeldung.config.PersistenceJPAConfigL2Cache;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfigL2Cache.class }, loader = AnnotationConfigContextLoader.class)
@WebAppConfiguration
@DirtiesContext
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -39,7 +39,7 @@ public class PersistenceJPAConfig {
// beans // beans
@Bean @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() { public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource()); em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });

View File

@ -16,6 +16,7 @@ import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils; import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@ -27,6 +28,8 @@ public class EmployeeDAO {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate; private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private SimpleJdbcInsert simpleJdbcInsert; private SimpleJdbcInsert simpleJdbcInsert;
private SimpleJdbcCall simpleJdbcCall;
@Autowired @Autowired
public void setDataSource(final DataSource dataSource) { public void setDataSource(final DataSource dataSource) {
@ -36,7 +39,9 @@ public class EmployeeDAO {
namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE"); simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE");
// Commented as the database is H2, change the database and create procedure READ_EMPLOYEE before calling getEmployeeUsingSimpleJdbcCall
//simpleJdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("READ_EMPLOYEE");
} }
public int getCountOfEmployees() { public int getCountOfEmployees() {
@ -110,4 +115,15 @@ public class EmployeeDAO {
final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch);
return updateCounts; return updateCounts;
} }
public Employee getEmployeeUsingSimpleJdbcCall(int id) {
SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
Map<String, Object> out = simpleJdbcCall.execute(in);
Employee emp = new Employee();
emp.setFirstName((String) out.get("FIRST_NAME"));
emp.setLastName((String) out.get("LAST_NAME"));
return emp;
}
} }

51
pom.xml
View File

@ -312,6 +312,10 @@
<configuration> <configuration>
<forkCount>3</forkCount> <forkCount>3</forkCount>
<reuseForks>true</reuseForks> <reuseForks>true</reuseForks>
<includes>
<include>SpringContextTest</include>
<include>**/*UnitTest</include>
</includes>
<excludes> <excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude> <exclude>**/*IntTest.java</exclude>
@ -480,7 +484,6 @@
<module>jersey</module> <module>jersey</module>
<module>JGit</module> <module>JGit</module>
<module>jgroups</module> <module>jgroups</module>
<module>jhipster</module>
<module>jhipster-5</module> <module>jhipster-5</module>
<module>jib</module> <module>jib</module>
<module>jjwt</module> <module>jjwt</module>
@ -507,6 +510,7 @@
<module>libraries-security</module> <module>libraries-security</module>
<module>libraries-server</module> <module>libraries-server</module>
<module>libraries-http</module> <module>libraries-http</module>
<module>libraries-io</module>
<module>linkrest</module> <module>linkrest</module>
<module>logging-modules</module> <module>logging-modules</module>
<module>lombok</module> <module>lombok</module>
@ -545,7 +549,6 @@
<!-- <module>raml</module> --> <!-- Not a maven project --> <!-- <module>raml</module> --> <!-- Not a maven project -->
<module>ratpack</module> <module>ratpack</module>
<module>reactor-core</module> <module>reactor-core</module>
<module>rest-with-spark-java</module>
<module>resteasy</module> <module>resteasy</module>
<module>restx</module> <module>restx</module>
<!-- <module>rmi</module> --> <!-- Not a maven project --> <!-- <module>rmi</module> --> <!-- Not a maven project -->
@ -575,6 +578,10 @@
<configuration> <configuration>
<forkCount>3</forkCount> <forkCount>3</forkCount>
<reuseForks>true</reuseForks> <reuseForks>true</reuseForks>
<includes>
<include>SpringContextTest</include>
<include>**/*UnitTest</include>
</includes>
<excludes> <excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude> <exclude>**/*IntTest.java</exclude>
@ -656,22 +663,23 @@
<module>spring-boot-vue</module> <module>spring-boot-vue</module>
<module>spring-boot-libraries</module> <module>spring-boot-libraries</module>
<module>spring-cloud</module>
<module>spring-cloud-bus</module> <!-- <module>spring-cloud</module> --> <!-- BAEL-14304 -->
<!-- <module>spring-cloud-bus</module> --> <!-- BAEL-14304 -->
<!-- <module>spring-cloud-cli</module> --> <!-- Not a maven project --> <!-- <module>spring-cloud-cli</module> --> <!-- Not a maven project -->
<module>spring-cloud-data-flow</module> <!-- <module>spring-cloud-data-flow</module> --> <!-- BAEL-14304 -->
<module>spring-core</module> <module>spring-core</module>
<module>spring-core-2</module> <module>spring-core-2</module>
<module>spring-cucumber</module> <module>spring-cucumber</module>
<module>spring-data-rest</module> <module>spring-data-rest</module>
<module>spring-data-rest-querydsl</module> <!-- <module>spring-data-rest-querydsl</module> --> <!-- BAEL-14304 -->
<module>spring-dispatcher-servlet</module> <module>spring-dispatcher-servlet</module>
<module>spring-drools</module> <module>spring-drools</module>
<module>spring-ehcache</module> <module>spring-ehcache</module>
<module>spring-ejb</module> <!-- <module>spring-ejb</module> BAEL-14304 -->
<module>spring-exceptions</module> <module>spring-exceptions</module>
<module>spring-freemarker</module> <module>spring-freemarker</module>
@ -745,7 +753,7 @@
<module>spring-security-stormpath</module> <module>spring-security-stormpath</module>
<module>spring-security-thymeleaf</module> <module>spring-security-thymeleaf</module>
<module>spring-security-x509</module> <module>spring-security-x509</module>
<module>spring-session</module> <!-- <module>spring-session</module> BAEL-14304 -->
<module>spring-sleuth</module> <module>spring-sleuth</module>
<module>spring-soap</module> <module>spring-soap</module>
<module>spring-social-login</module> <module>spring-social-login</module>
@ -756,12 +764,10 @@
<module>spring-thymeleaf</module> <module>spring-thymeleaf</module>
<module>spring-userservice</module> <!-- <module>spring-vault</module> BAEL-14304 -->
<module>spring-vault</module>
<module>spring-vertx</module> <module>spring-vertx</module>
<module>spring-webflux-amqp</module> <!-- long --> <!-- <module>spring-webflux-amqp</module> BAEL-14304 --> <!-- long -->
<module>spring-zuul</module> <module>spring-zuul</module>
@ -777,7 +783,6 @@
<module>undertow</module> <module>undertow</module>
<module>vavr</module>
<module>vertx</module> <module>vertx</module>
<module>vertx-and-rxjava</module> <module>vertx-and-rxjava</module>
<module>video-tutorials</module> <module>video-tutorials</module>
@ -786,7 +791,6 @@
<module>wicket</module> <module>wicket</module>
<module>xml</module> <module>xml</module>
<module>xmlunit-2</module>
<module>xstream</module> <module>xstream</module>
<module>tensorflow-java</module> <module>tensorflow-java</module>
@ -840,7 +844,8 @@
<module>spring-boot-camel</module> <module>spring-boot-camel</module>
<module>spring-boot-client</module> <module>spring-boot-client</module>
<module>spring-boot-custom-starter</module> <module>spring-boot-custom-starter</module>
<module>greeter-spring-boot-autoconfigure</module> <module>spring-boot-di</module>
<module>greeter-spring-boot-autoconfigure</module>
<module>greeter-spring-boot-sample-app</module> <module>greeter-spring-boot-sample-app</module>
<module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module> <module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module>
<module>spring-boot-jasypt</module> <module>spring-boot-jasypt</module>
@ -927,7 +932,6 @@
<module>spring-state-machine</module> <module>spring-state-machine</module>
<module>spring-swagger-codegen/spring-swagger-codegen-app</module> <module>spring-swagger-codegen/spring-swagger-codegen-app</module>
<module>spring-thymeleaf</module> <module>spring-thymeleaf</module>
<module>spring-userservice</module>
<module>spring-vault</module> <module>spring-vault</module>
<module>spring-vertx</module> <module>spring-vertx</module>
<module>spring-zuul/spring-zuul-foos-resource</module> <module>spring-zuul/spring-zuul-foos-resource</module>
@ -955,6 +959,10 @@
<configuration> <configuration>
<forkCount>3</forkCount> <forkCount>3</forkCount>
<reuseForks>true</reuseForks> <reuseForks>true</reuseForks>
<includes>
<include>SpringContextTest</include>
<include>**/*UnitTest</include>
</includes>
<excludes> <excludes>
<exclude>**/*IntegrationTest.java</exclude> <exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude> <exclude>**/*IntTest.java</exclude>
@ -983,6 +991,7 @@
<module>core-kotlin-io</module> <module>core-kotlin-io</module>
<module>jenkins/hello-world</module> <module>jenkins/hello-world</module>
<module>jhipster</module>
<module>jws</module> <module>jws</module>
<module>libraries</module> <!-- very long running --> <module>libraries</module> <!-- very long running -->
@ -993,6 +1002,7 @@
<module>persistence-modules/jnosql</module> <module>persistence-modules/jnosql</module>
<module>vaadin</module> <module>vaadin</module>
<module>vavr</module>
</modules> </modules>
</profile> </profile>
@ -1164,7 +1174,6 @@
<module>jersey</module> <module>jersey</module>
<module>JGit</module> <module>JGit</module>
<module>jgroups</module> <module>jgroups</module>
<module>jhipster</module>
<module>jhipster-5</module> <module>jhipster-5</module>
<module>jib</module> <module>jib</module>
<module>jjwt</module> <module>jjwt</module>
@ -1226,7 +1235,6 @@
<!-- <module>raml</module> --> <!-- Not a maven project --> <!-- <module>raml</module> --> <!-- Not a maven project -->
<module>ratpack</module> <module>ratpack</module>
<module>reactor-core</module> <module>reactor-core</module>
<module>rest-with-spark-java</module>
<module>resteasy</module> <module>resteasy</module>
<module>restx</module> <module>restx</module>
<!-- <module>rmi</module> --> <!-- Not a maven project --> <!-- <module>rmi</module> --> <!-- Not a maven project -->
@ -1422,8 +1430,6 @@
<module>spring-thymeleaf</module> <module>spring-thymeleaf</module>
<module>spring-userservice</module>
<module>spring-vault</module> <module>spring-vault</module>
<module>spring-vertx</module> <module>spring-vertx</module>
@ -1443,7 +1449,6 @@
<module>undertow</module> <module>undertow</module>
<module>vavr</module>
<module>vertx</module> <module>vertx</module>
<module>vertx-and-rxjava</module> <module>vertx-and-rxjava</module>
<module>video-tutorials</module> <module>video-tutorials</module>
@ -1452,9 +1457,7 @@
<module>wicket</module> <module>wicket</module>
<module>xml</module> <module>xml</module>
<module>xmlunit-2</module>
<module>xstream</module> <module>xstream</module>
</modules> </modules>
</profile> </profile>
@ -1495,6 +1498,7 @@
<module>core-kotlin-2</module> <module>core-kotlin-2</module>
<module>jenkins/hello-world</module> <module>jenkins/hello-world</module>
<module>jhipster</module>
<module>jws</module> <module>jws</module>
<module>libraries</module> <!-- very long running --> <module>libraries</module> <!-- very long running -->
@ -1505,6 +1509,7 @@
<module>persistence-modules/jnosql</module> <module>persistence-modules/jnosql</module>
<module>vaadin</module> <module>vaadin</module>
<module>vavr</module>
</modules> </modules>
</profile> </profile>

View File

@ -1,3 +1,3 @@
## Relevant articles: ## Relevant articles:
- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io) - [Guide to QuarkusIO](https://www.baeldung.com/quarkus-io)

View File

@ -1 +0,0 @@
## Relevant articles:

View File

@ -1,39 +0,0 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>rest-with-spark-java</artifactId>
<version>1.0-SNAPSHOT</version>
<name>rest-with-spark-java</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>${spark-core.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<properties>
<spark-core.version>2.5.4</spark-core.version>
</properties>
</project>

View File

@ -1,50 +0,0 @@
package com.baeldung;
import static spark.Spark.after;
import static spark.Spark.before;
import static spark.Spark.delete;
import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.port;
import com.baeldung.domain.Book;
import com.baeldung.service.LibraryService;
public class Router {
public static void main( String[] args ){
port(8080);
before((request, response) -> {
//do some filtering stuff
});
after((request, response) -> {
response.type("application/json");
});
get("ListOfBooks", (request, response) -> {
return LibraryService.view();
});
get("SearchBook/:title", (request, response) -> {
return LibraryService.view(request.params("title"));
});
post("AddBook/:title/:author/:publisher", (request, response) -> {
Book book = new Book();
book.setTitle(request.params("title"));
book.setAuthor(request.params("author"));
book.setPublisher(request.params("publisher"));
return LibraryService.add(book);
});
delete("DeleteBook/:title", (request, response) -> {
return LibraryService.delete(request.params("title"));
});
}
}

Some files were not shown because too many files have changed in this diff Show More