Merge branch 'masterupstream' into beforeAfterAnnotationsJunit

This commit is contained in:
Marcos Lopez Gonzalez 2018-04-10 22:17:26 +02:00
commit 6b0a022167
115 changed files with 2124 additions and 301 deletions

View File

@ -19,7 +19,7 @@ import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class CayenneAdvancedOperationTests {
public class CayenneAdvancedOperationIntegrationTest {
private static ObjectContext context = null;
@BeforeClass

View File

@ -16,7 +16,7 @@ import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class CayenneOperationTests {
public class CayenneOperationIntegrationTest {
private static ObjectContext context = null;
@BeforeClass

View File

@ -1,10 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.examples</groupId>
<artifactId>asm</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
@ -17,11 +19,13 @@
<version>5.2</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>

View File

@ -17,7 +17,6 @@ import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

View File

@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class MultipartUploadTest {
public class MultipartUploadLiveTest {
private static final String BUCKET_NAME = "bucket_name";
private static final String KEY_NAME = "picture.jpg";

View File

@ -1,22 +1,17 @@
<?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>
<groupId>com.example</groupId>
<artifactId>spring-boot-camel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot - Camel API</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<camel.version>2.19.1</camel.version>
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
@ -58,11 +53,6 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
@ -77,4 +67,13 @@
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<camel.version>2.19.1</camel.version>
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
</properties>
</project>

View File

@ -24,7 +24,7 @@ class JsonParserTest extends Specification {
account.value == 15.6
}
def 'Should parse to Account given Json String with date property' () {
/*def 'Should parse to Account given Json String with date property' () {
given:
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
when:
@ -36,9 +36,9 @@ class JsonParserTest extends Specification {
account.value == 15.6
println account.createdAt
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
}
}*/
def 'Should parse to Json given an Account object' () {
/*def 'Should parse to Json given an Account object' () {
given:
Account account = new Account(
id: '123',
@ -50,7 +50,7 @@ class JsonParserTest extends Specification {
then:
json
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
}
}*/
def 'Should prettify given a json string' () {
given:

View File

@ -8,7 +8,6 @@
<name>core-java-8</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>

View File

@ -0,0 +1,76 @@
package com.baeldung.time;
import static org.junit.Assert.assertEquals;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;
public class ElapsedTimeUnitTest {
@Test
public void givenRunningTask_whenMeasuringTimeWithCurrentTimeMillis_thenGetElapsedTime() throws InterruptedException {
long start = System.currentTimeMillis();
simulateRunningTask();
long finish = System.currentTimeMillis();
long timeElapsed = finish - start;
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
}
@Test
public void giveRunningTask_whenMeasuringTimeWithNanoTime_thenGetElapsedTime() throws InterruptedException {
long start = System.nanoTime();
simulateRunningTask();
long finish = System.nanoTime();
long timeElapsed = finish - start;
assertEquals(true, (2000000000L <= timeElapsed) && (timeElapsed <= 3000000000L));
}
@Test
public void givenRunningTask_whenMeasuringTimeWithStopWatch_thenGetElapsedTime() throws InterruptedException {
StopWatch watch = new StopWatch();
watch.start();
simulateRunningTask();
watch.stop();
long timeElapsed = watch.getTime();
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
}
@Test
public void givenRunningTask_whenMeasuringTimeWithInstantClass_thenGetElapsedTime() throws InterruptedException {
Instant start = Instant.now();
simulateRunningTask();
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
assertEquals(true, (2000L <= timeElapsed) && (timeElapsed <= 3000L));
}
/**
* Simulate task running for 2.5 seconds.
*
* @throws InterruptedException
*/
private static void simulateRunningTask() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(2500); // 2.5 seconds
}
}

View File

@ -142,4 +142,5 @@
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [The “final” Keyword in Java](http://www.baeldung.com/java-final)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)

View File

@ -0,0 +1,17 @@
package com.baeldung.system;
import java.awt.event.WindowEvent;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' gc() which suggests
* JVM for garbage collection. But the usage below demonstrates how the
* method can be used.
*/
public class ChatWindow {
public void windowStateChanged(WindowEvent event) {
if (event.getNewState() == WindowEvent.WINDOW_DEACTIVATED ) {
System.gc(); // if it ends up running, great!
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.system;
import java.util.Date;
public class DateTimeService {
// One hour from now
public long nowPlusOneHour() {
return System.currentTimeMillis() + 3600 * 1000L;
}
// Human-readable format
public String nowPrettyPrinted() {
return new Date(System.currentTimeMillis()).toString();
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.system;
public class EnvironmentVariables {
public String getPath() {
return System.getenv("PATH");
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.system;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard error stream
* methods to show output on screen. Also unit-tests in CI environments
* don't have console output for user to see messages. But the usage below
* demonstrates how the methods can be used.
*/
public class SystemErrDemo {
public static void main(String[] args) {
// Print without 'hitting' return
System.err.print("some inline error message");
// Print and then 'hit' return
System.err.println("an error message having new line at the end");
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.system;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' exit() which will
* exit the JVM. Also unit-tests in CI environments are not meant to
* exit unit tests like that. But the usage below demonstrates how the
* method can be used.
*/
public class SystemExitDemo {
public static void main(String[] args) {
boolean error = false;
// do something and set error value
if (error) {
System.exit(1); // error case exit
} else {
System.exit(0); // normal case exit
}
// Will not do anything after exit()
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.system;
import java.io.FileNotFoundException;
import java.io.PrintStream;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard output stream
* methods to show output on screen. Also unit-tests in CI environments
* don't have console output for user to see messages. But the usage below
* demonstrates how the methods can be used.
*/
public class SystemOutDemo {
public static void main(String[] args) throws FileNotFoundException {
// Print without 'hitting' return
System.out.print("some inline message");
// Print and then 'hit' return
System.out.println("a message having new line at the end");
// Changes output stream to send messages to file.
System.setOut(new PrintStream("file.txt"));
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.system;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Note: This class is not meant for unit-testing since it uses system
* features at low level and that it uses 'System' standard input stream
* methods to read text from user. Also unit-tests in CI environments
* don't have console input for user to type in text. But the usage below
* demonstrates how the methods can be used.
*/
public class UserCredentials {
public String readUsername(int length) throws IOException {
byte[] name = new byte[length];
System.in.read(name, 0, length); // by default, from the console
return new String(name);
}
public String readUsername() throws IOException {
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
return reader.readLine();
}
public String readUsernameWithPrompt() {
Console console = System.console();
return console == null ? null : // Console not available
console.readLine("%s", "Enter your name: ");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class DateTimeServiceTest {
@Test
public void givenClass_whenCalledMethods_thenNotNullInResult() {
DateTimeService dateTimeService = new DateTimeService();
Assert.assertNotNull(dateTimeService.nowPlusOneHour());
Assert.assertNotNull(dateTimeService.nowPrettyPrinted());
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class EnvironmentVariablesTest {
@Test
public void givenEnvVars_whenReadPath_thenGetValueinResult() {
EnvironmentVariables environmentVariables = new EnvironmentVariables();
Assert.assertNotNull(environmentVariables.getPath());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class SystemArrayCopyTest {
@Test
public void givenTwoArraysAB_whenUseArrayCopy_thenArrayCopiedFromAToBInResult() {
int[] a = {34, 22, 44, 2, 55, 3};
int[] b = new int[a.length];
// copy all elements from a to b
System.arraycopy(a, 0, b, 0, a.length);
Assert.assertArrayEquals(a, b);
}
@Test
public void givenTwoArraysAB_whenUseArrayCopyPosition_thenArrayCopiedFromAToBInResult() {
int[] a = {34, 22, 44, 2, 55, 3};
int[] b = new int[a.length];
// copy 2 elements from a, starting at a[1] to b, starting at b[3]
System.arraycopy(a, 1, b, 3, 2);
Assert.assertArrayEquals(new int[] {0, 0, 0, 22, 44, 0}, b);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
public class SystemNanoTest {
@Test
public void givenSystem_whenCalledNanoTime_thenGivesTimeinResult() {
long startTime = System.nanoTime();
// do something that takes time
long endTime = System.nanoTime();
Assert.assertTrue(endTime - startTime < 10000);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Test;
import java.util.Properties;
public class SystemPropertiesTest {
@Test
public void givenSystem_whenCalledGetProperty_thenReturnPropertyinResult() {
Assert.assertNotNull(System.getProperty("java.vm.vendor"));
}
@Test
public void givenSystem_whenCalledSetProperty_thenSetPropertyasResult() {
// set a particular property
System.setProperty("abckey", "abcvaluefoo");
Assert.assertEquals("abcvaluefoo", System.getProperty("abckey"));
}
@Test
public void givenSystem_whenCalledClearProperty_thenDeletePropertyasResult() {
// Delete a property
System.clearProperty("abckey");
Assert.assertNull(System.getProperty("abckey"));
}
@Test
public void givenSystem_whenCalledGetPropertyDefaultValue_thenReturnPropertyinResult() {
System.clearProperty("dbHost");
String myKey = System.getProperty("dbHost", "db.host.com");
Assert.assertEquals("db.host.com", myKey);
}
@Test
public void givenSystem_whenCalledGetProperties_thenReturnPropertiesinResult() {
Properties properties = System.getProperties();
Assert.assertNotNull(properties);
}
@Test
public void givenSystem_whenCalledClearProperties_thenDeleteAllPropertiesasResult() {
// Clears all system properties. Use with care!
System.getProperties().clear();
Assert.assertTrue(System.getProperties().isEmpty());
}
}

View File

@ -21,3 +21,4 @@
- [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources)
- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp)
- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection)
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)

6
javafx/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
# Created by .ignore support plugin (hsz.mobi)
.idea
classes
target
*.iml
out

3
javafx/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
-

15
javafx/pom.xml Normal file
View File

@ -0,0 +1,15 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>javafx</artifactId>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.javafx;
package com.baeldung;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;

View File

@ -1,4 +1,4 @@
package com.baeldung.javafx.model;
package com.baeldung.model;
import javafx.beans.property.*;

View File

@ -1,7 +1,7 @@
package com.baeldung.javafx.view;
package com.baeldung.view;
import com.baeldung.javafx.model.Person;
import com.baeldung.model.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
@ -11,7 +11,6 @@ import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.VBox;
import java.util.List;
import java.util.stream.Collectors;
public class SearchController {

View File

@ -7,7 +7,7 @@
<?import javafx.scene.layout.*?>
<AnchorPane xmlns:fx="http://javafx.com/fxml"
xmlns="http://javafx.com/javafx"
fx:controller="com.baeldung.javafx.view.SearchController"
fx:controller="com.baeldung.view.SearchController"
prefHeight="400.0" prefWidth="600.0">
<children>

Binary file not shown.

View File

@ -270,6 +270,12 @@
<groupId>net.openhft</groupId>
<artifactId>chronicle</artifactId>
<version>3.6.4</version>
<exclusions>
<exclusion>
<groupId>com.sun.java</groupId>
<artifactId>tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@ -675,6 +681,7 @@
<version>4.5.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
@ -772,17 +779,6 @@
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<!-- /Neuroph -->
<plugin>

View File

@ -0,0 +1,49 @@
package com.baeldung.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
public class CalculatorOperationHandler extends SimpleChannelInboundHandler<Operation> {
protected void channelRead0(ChannelHandlerContext ctx, Operation msg) throws Exception {
Long result = calculateEndpoint(msg);
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED), result.toString());
ctx.fireChannelRead(result);
}
private long calculateEndpoint(Operation operation) {
String operator = operation.getOperator().toLowerCase().trim();
switch (operator) {
case "add":
return operation.getNumber1() + operation.getNumber2();
case "multiply":
return operation.getNumber1() * operation.getNumber2();
default:
throw new IllegalArgumentException("Operation not defined");
}
}
public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpResponse res, String content) {
// Generate an error page if response getStatus code is not OK (200).
ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
res.content().writeBytes(buf);
HttpUtil.setContentLength(res, res.content().readableBytes());
ctx.channel().writeAndFlush(res);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR), "Operation not defined");
ctx.fireExceptionCaught(cause);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
public class HttpMessageHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
String uri = msg.uri();
HttpMethod httpMethod = msg.method();
HttpHeaders headers = msg.headers();
if (HttpMethod.GET == httpMethod) {
String[] uriComponents = uri.split("[?]");
String endpoint = uriComponents[0];
String[] queryParams = uriComponents[1].split("&");
if ("/calculate".equalsIgnoreCase(endpoint)) {
String[] firstQueryParam = queryParams[0].split("=");
String[] secondQueryParam = queryParams[1].split("=");
Integer a = Integer.valueOf(firstQueryParam[1]);
Integer b = Integer.valueOf(secondQueryParam[1]);
String operator = headers.get("operator");
Operation operation = new Operation(a, b, operator);
ctx.fireChannelRead(operation);
}
} else {
throw new UnsupportedOperationException("HTTP method not supported");
}
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.netty;
import java.io.Serializable;
public class Operation implements Serializable {
private Integer number1;
private Integer number2;
private String operator;
public Operation(Integer number1, Integer number2, String operator) {
this.number1 = number1;
this.number2 = number2;
this.operator = operator;
}
public Integer getNumber1() {
return number1;
}
public void setNumber1(Integer number1) {
this.number1 = number1;
}
public Integer getNumber2() {
return number2;
}
public void setNumber2(Integer number2) {
this.number2 = number2;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
@Override
public String toString() {
return "Operation{" +
"number1=" + number1 +
", number2=" + number2 +
", operator='" + operator + '\'' +
'}';
}
}

View File

@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class AsyncHttpClientTestCase {
public class AsyncHttpClientLiveTest {
private static AsyncHttpClient HTTP_CLIENT;

View File

@ -2,7 +2,6 @@ package com.baeldung.atlassian.fugue;
import io.atlassian.fugue.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;

View File

@ -16,7 +16,7 @@ import static org.awaitility.Awaitility.setDefaultTimeout;
import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo;
public class AsyncServiceLongRunningUnitTest {
public class AsyncServiceLongRunningManualTest {
private AsyncService asyncService;
@Before

View File

@ -4,7 +4,7 @@ import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Docx4jReadAndWriteTest {
public class Docx4jReadAndWriteIntegrationTest {
private static final String imagePath = "src/main/resources/image.jpg";
private static final String outputPath = "helloWorld.docx";

View File

@ -10,7 +10,7 @@ import java.util.stream.LongStream;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class HLLLongRunningUnitTest {
public class HLLLongRunningManualTest {
@Test
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {

View File

@ -14,7 +14,7 @@ import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class EventListenerTest {
public class EventListenerIntegrationTest {
private static final String CACHE_NAME = "MyCache";

View File

@ -0,0 +1,107 @@
package com.baeldung.netty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.charset.Charset;
import org.junit.Assert;
import org.junit.Test;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
public class EmbeddedChannelUnitTest {
@Test
public void givenTwoChannelHandlers_testPipeline() {
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/calculate?a=10&b=5");
httpRequest.headers().add("Operator", "Add");
EmbeddedChannel channel = new EmbeddedChannel(
new HttpMessageHandler(), new CalculatorOperationHandler());
channel.pipeline()
.addFirst(new HttpMessageHandler())
.addLast(new CalculatorOperationHandler());
// send HTTP request to server and check that the message is on the inbound pipeline
assertTrue(channel.writeInbound(httpRequest));
long inboundChannelResponse = channel.readInbound();
assertEquals(15, inboundChannelResponse);
// we should have an outbound message in the form of a HTTP response
assertEquals(1, channel.outboundMessages().size());
// Object response = channel.readOutbound();
FullHttpResponse httpResponse = channel.readOutbound();
String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
assertTrue("15".equalsIgnoreCase(httpResponseContent));
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInHttpMessageHandler() {
EmbeddedChannel channel = new EmbeddedChannel(
new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Add");
try {
// send invalid HTTP request to server and expect and error
channel.pipeline().fireChannelRead(wrongHttpRequest);
channel.checkException();
// channel.writeInbound(wrongHttpRequest);
Assert.fail();
} catch (Exception ex) {
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
assertTrue(ex instanceof UnsupportedOperationException);
assertTrue(ex.getMessage().equalsIgnoreCase("HTTP method not supported"));
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertTrue("Operation not defined".equalsIgnoreCase(errorHttpResponseContent));
assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorHttpResponse.status());
}
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
EmbeddedChannel channel = new EmbeddedChannel(
new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Invalid_operation");
try {
// send invalid HTTP request to server and expect and error
channel.writeInbound(wrongHttpRequest);
Assert.fail();
} catch (Exception ex) {
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
assertTrue(ex instanceof IllegalArgumentException);
assertTrue(ex.getMessage().equalsIgnoreCase("Operation not defined"));
// the outbound message is a HTTP response with the status code 500
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertTrue("Operation not defined".equalsIgnoreCase(errorHttpResponseContent));
assertEquals(HttpResponseStatus.INTERNAL_SERVER_ERROR, errorHttpResponse.status());
}
}
}

View File

@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class AccountTest {
public class AccountUnitTest {
@Test
public void givenAccount_whenDecrement_thenShouldReturnProperValue() {

37
patterns/facade/pom.xml Normal file
View File

@ -0,0 +1,37 @@
<?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>
<groupId>com.baeldung.pattern.facade</groupId>
<artifactId>pattern.facade</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.patterns</groupId>
<artifactId>patterns-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,32 @@
package com.baeldung.pattern.facade;
import com.baeldung.pattern.facade.carsystem.*;
public class CarEngineFacade {
private static final Integer DEFAULT_COOLING_TEMP = 90;
private static final Integer MAX_ALLOWED_TEMP = 50;
private FuelInjector fuelInjector = new FuelInjector();
private AirFlowController airFlowController = new AirFlowController();
private Starter starter = new Starter();
private CoolingController coolingController = new CoolingController();
private CatalyticConverter catalyticConverter = new CatalyticConverter();
public void startEngine(){
fuelInjector.on();
airFlowController.takeAir();
fuelInjector.on();
fuelInjector.inject();
starter.start();
coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP);
coolingController.run();
catalyticConverter.on();
}
public void stopEngine(){
fuelInjector.off();
catalyticConverter.off();
coolingController.cool(MAX_ALLOWED_TEMP);
coolingController.stop();
airFlowController.off();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowController {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowController.class);
private AirFlowMeter airFlowMeter = new AirFlowMeter();
public void takeAir() {
airFlowMeter.getMeasurements();
LOGGER.info("Air provided!");
}
public void off() {
LOGGER.info("Air controller switched off.");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowMeter {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowMeter.class);
public void getMeasurements() {
LOGGER.info("Getting air measurements...");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CatalyticConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalyticConverter.class);
public void on() {
LOGGER.info("Catalytic Converter switched on!");
}
public void off() {
LOGGER.info("Catalytic Converter switched off!");
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoolingController {
private static final Logger LOGGER = LoggerFactory.getLogger(CoolingController.class);
private static final Integer DEFAULT_RADIATOR_SPEED = 10;
private Integer temperatureUpperLimit;
private Radiator radiator = new Radiator();
private TemperatureSensor temperatureSensor = new TemperatureSensor();
public void setTemperatureUpperLimit(Integer temperatureUpperLimit) {
LOGGER.info("Setting temperature upper limit to {}", temperatureUpperLimit);
this.temperatureUpperLimit = temperatureUpperLimit;
}
public void run() {
LOGGER.info("Cooling Controller ready!");
radiator.setSpeed(DEFAULT_RADIATOR_SPEED);
}
public void cool(Integer maxAllowedTemp) {
LOGGER.info("Scheduled cooling with maximum allowed temperature {}", maxAllowedTemp);
temperatureSensor.getTemperature();
radiator.on();
}
public void stop() {
LOGGER.info("Stopping Cooling Controller...");
radiator.off();
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelInjector {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelInjector.class);
private FuelPump fuelPump = new FuelPump();
public void on(){
LOGGER.info("Fuel injector ready to inject fuel.");
}
public void inject() {
fuelPump.pump();
LOGGER.info("Fuel injected.");
}
public void off() {
LOGGER.info("Stopping Fuel injector...");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelPump {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelPump.class);
public void pump() {
LOGGER.info("Fuel Pump is pumping fuel...");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Radiator {
private static final Logger LOGGER = LoggerFactory.getLogger(Radiator.class);
public void on(){
LOGGER.info("Radiator switched on!");
}
public void off(){
LOGGER.info("Radiator switched off!");
}
public void setSpeed(Integer speed){
LOGGER.info("Setting radiator speed to {}",speed);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Starter {
private static final Logger LOGGER = LoggerFactory.getLogger(Starter.class);
public void start() {
LOGGER.info("Starting...");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.pattern.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TemperatureSensor {
private static final Logger LOGGER = LoggerFactory.getLogger(TemperatureSensor.class);
public void getTemperature(){
LOGGER.info("Getting temperature from the sensor...");
}
}

View File

@ -0,0 +1,85 @@
package com.baeldung.pattern.facade;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class CarEngineFacadeTest {
private InMemoryCustomTestAppender appender;
@Before
public void setUp() {
appender = new InMemoryCustomTestAppender();
}
@After
public void tearDown() {
appender.stop();
}
@Test
public void whenStartEngine_thenAllNecessaryActionsPerformed() {
CarEngineFacade carEngineFacade = new CarEngineFacade();
carEngineFacade.startEngine();
assertTrue(appender.logContains("Fuel injector ready to inject fuel."));
assertTrue(appender.logContains("Getting air measurements..."));
assertTrue(appender.logContains("Air provided!"));
assertTrue(appender.logContains("Fuel injector ready to inject fuel."));
assertTrue(appender.logContains("Fuel Pump is pumping fuel..."));
assertTrue(appender.logContains("Fuel injected."));
assertTrue(appender.logContains("Starting..."));
assertTrue(appender.logContains("Setting temperature upper limit to 90"));
assertTrue(appender.logContains("Cooling Controller ready!"));
assertTrue(appender.logContains("Setting radiator speed to 10"));
assertTrue(appender.logContains("Catalytic Converter switched on!"));
}
@Test
public void whenStopEngine_thenAllNecessaryActionsPerformed() {
CarEngineFacade carEngineFacade = new CarEngineFacade();
carEngineFacade.stopEngine();
assertTrue(appender.logContains("Stopping Fuel injector..."));
assertTrue(appender.logContains("Catalytic Converter switched off!"));
assertTrue(appender.logContains("Scheduled cooling with maximum allowed temperature 50"));
assertTrue(appender.logContains("Getting temperature from the sensor..."));
assertTrue(appender.logContains("Radiator switched on!"));
assertTrue(appender.logContains("Stopping Cooling Controller..."));
assertTrue(appender.logContains("Radiator switched off!"));
assertTrue(appender.logContains("Air controller switched off."));
}
private class InMemoryCustomTestAppender extends AppenderBase<ILoggingEvent> {
private List<ILoggingEvent> logs = new ArrayList<>();
public InMemoryCustomTestAppender() {
((Logger) LoggerFactory.getLogger("root")).addAppender(this);
start();
}
@Override
protected void append(ILoggingEvent eventObject) {
logs.add(eventObject);
}
public boolean logContains(String message) {
return logs.stream().anyMatch(event -> event.getFormattedMessage().equals(message));
}
}
}

16
pom.xml
View File

@ -22,8 +22,9 @@
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- plugins -->
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
</properties>
<modules>
@ -100,6 +101,7 @@
<module>javax-servlets</module>
<module>javaxval</module>
<module>jaxb</module>
<module>javafx</module>
<module>jgroups</module>
<module>jee-7</module>
<!-- <module>jhipster/jhipster-monolithic</module> -->
@ -112,7 +114,9 @@
<module>testing-modules/junit-5</module>
<module>jws</module>
<!--
<module>libraries</module>
-->
<module>libraries-data</module>
<module>linkrest</module>
<module>logging-modules/log-mdc</module>
@ -350,14 +354,16 @@
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>maven</executable>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -372,9 +378,9 @@
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@ -384,7 +390,9 @@
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>com.vackosar.gitflowincrementalbuilder</groupId>
@ -392,5 +400,7 @@
<version>3.4</version>
</extension>
</extensions>
</build>
</project>

View File

@ -32,7 +32,7 @@ public class CombiningPublishersTest {
}
@Test
/*@Test
public void givenFluxes_whenMergeWithDelayedElementsIsInvoked_thenMergeWithDelayedElements() {
Flux<Integer> fluxOfIntegers = Flux.merge(
evenNumbers.delayElements(Duration.ofMillis(2000L)),
@ -46,7 +46,7 @@ public class CombiningPublishersTest {
.expectNext(4)
.expectComplete()
.verify();
}
}*/
@Test
public void givenFluxes_whenConcatIsInvoked_thenConcat() {

View File

@ -0,0 +1,15 @@
package com.baeldung.reactive.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class UserController {
@GetMapping(path = "/users/{name}")
public Mono<String> getName(@PathVariable String name) {
return Mono.just(name);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.reactive.filter;
import org.springframework.web.reactive.function.server.HandlerFilterFunction;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import static org.springframework.http.HttpStatus.FORBIDDEN;
public class ExampleHandlerFilterFunction implements HandlerFilterFunction {
@Override
public Mono filter(ServerRequest serverRequest, HandlerFunction handlerFunction) {
if (serverRequest.pathVariable("name").equalsIgnoreCase("test")) {
return ServerResponse.status(FORBIDDEN).build();
}
return handlerFunction.handle(serverRequest);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.reactive.filter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
@Component
public class ExampleWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
serverWebExchange.getResponse().getHeaders().add("web-filter", "web-filter-test");
return webFilterChain.filter(serverWebExchange);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.reactive.handler;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
@Component
public class PlayerHandler {
public Mono<ServerResponse> getName(ServerRequest request) {
Mono<String> name = Mono.just(request.pathVariable("name"));
return ok().body(name, String.class);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.reactive.router;
import com.baeldung.reactive.filter.ExampleHandlerFilterFunction;
import com.baeldung.reactive.handler.PlayerHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
@Configuration
public class PlayerRouter {
@Bean
public RouterFunction<ServerResponse> route(PlayerHandler playerHandler) {
return RouterFunctions
.route(GET("/players/{name}"), playerHandler::getName)
.filter(new ExampleHandlerFilterFunction()::filter);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.reactive.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.EntityExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void whenUserNameIsBaeldung_thenWebFilterIsApplied() {
EntityExchangeResult<String> result = webTestClient.get().uri("/users/baeldung")
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.returnResult();
assertEquals(result.getResponseBody(), "baeldung");
assertEquals(result.getResponseHeaders().getFirst("web-filter"), "web-filter-test");
}
@Test
public void whenUserNameIsTest_thenHandlerFilterFunctionIsNotApplied() {
webTestClient.get().uri("/users/test")
.exchange()
.expectStatus().isOk();
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.reactive.handler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.EntityExchangeResult;
import org.springframework.test.web.reactive.server.WebTestClient;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PlayerHandlerTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void whenPlayerNameIsBaeldung_thenWebFilterIsApplied() {
EntityExchangeResult<String> result = webTestClient.get().uri("/players/baeldung")
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.returnResult();
assertEquals(result.getResponseBody(), "baeldung");
assertEquals(result.getResponseHeaders().getFirst("web-filter"), "web-filter-test");
}
@Test
public void whenPlayerNameIsTest_thenHandlerFilterFunctionIsApplied() {
webTestClient.get().uri("/players/test")
.exchange()
.expectStatus().isForbidden();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.sql.PreparedStatement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositoryJDBCTemplate {
@Autowired
JdbcTemplate jdbcTemplate;
final String INSERT_MESSAGE_SQL = "insert into sys_message (message) values(?) ";
public long insert(final String message) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(connection -> {
PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL);
ps.setString(1, message);
return ps;
}, keyHolder);
return (long) keyHolder.getKey();
}
final String SELECT_BY_ID = "select message from sys_message where id = ?";
public String getMessageById(long id) {
return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id });
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jdbc.autogenkey.repository;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;
@Repository
public class MessageRepositorySimpleJDBCInsert {
SimpleJdbcInsert messageInsert;
@Autowired
public MessageRepositorySimpleJDBCInsert(DataSource dataSource) {
messageInsert = new SimpleJdbcInsert(dataSource).withTableName("sys_message").usingGeneratedKeyColumns("id");
}
public long insert(String message) {
Map<String, Object> parameters = new HashMap<String, Object>(1);
parameters.put("message", message);
Number newId = messageInsert.executeAndReturnKey(parameters);
return (long) newId;
}
}

View File

@ -0,0 +1,9 @@
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.datasource.initialize=true
spring.datasource.schema=classpath:autogenkey-schema.sql

View File

@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS sys_message (
id bigint(20) NOT NULL AUTO_INCREMENT,
message varchar(100) NOT NULL,
PRIMARY KEY (id)
);

View File

@ -0,0 +1,53 @@
package com.baeldung.jdbc.autogenkey;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class)
public class GetAutoGenKeyByJDBC {
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:autogenkey-db.properties")
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey.repository" })
public static class SpringConfig {
}
@Autowired
MessageRepositorySimpleJDBCInsert messageRepositorySimpleJDBCInsert;
@Autowired
MessageRepositoryJDBCTemplate messageRepositoryJDBCTemplate;
final String MESSAGE_CONTENT = "Test";
@Test
public void insertJDBC_whenLoadMessageByKey_thenGetTheSameMessage() {
long key = messageRepositoryJDBCTemplate.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
@Test
public void insertSimpleInsert_whenLoadMessageKey_thenGetTheSameMessage() {
long key = messageRepositorySimpleJDBCInsert.insert(MESSAGE_CONTENT);
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage);
}
}

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework" level="INFO"/>
</configuration>

View File

@ -0,0 +1,44 @@
buildscript {
ext {
springBootVersion = '2.0.0.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'org.baeldung'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
springBoot {
mainClassName = 'org.baeldung.DemoApplication'
}
bootJar {
// This is overridden by the mainClassName in springBoot{} and added here for reference purposes.
mainClassName = 'org.baeldung.DemoApplication'
// This block serves the same purpose as the above thus commented out. Added here for reference purposes
// manifest {
// attributes 'Start-Class': 'org.baeldung.DemoApplication'
// }
}

Binary file not shown.

View File

@ -0,0 +1,6 @@
#Tue Feb 06 12:27:20 CET 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5.1-bin.zip

172
spring-boot-gradle/gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save ( ) {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
spring-boot-gradle/gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1 @@
rootProject.name = 'demo'

View File

@ -0,0 +1,12 @@
package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@ -0,0 +1,16 @@
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}

View File

@ -87,40 +87,4 @@
<version>${fastjson.version}</version>
</dependency>
</dependencies>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -28,7 +28,7 @@ import static org.junit.Assert.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class GeoQueriesTest {
public class GeoQueriesIntegrationTest {
private static final String WONDERS_OF_WORLD = "wonders-of-world";
private static final String WONDERS = "Wonders";

View File

@ -4,3 +4,4 @@
- [MaxUploadSizeExceededException in Spring](http://www.baeldung.com/spring-maxuploadsizeexceeded)
- [Getting Started with Forms in Spring MVC](http://www.baeldung.com/spring-mvc-form-tutorial)
- [Form Validation with AngularJS and Spring MVC](http://www.baeldung.com/validation-angularjs-spring-mvc)
- [Guide to JSTL](http://www.baeldung.com/guide-to-jstl)

View File

@ -48,6 +48,12 @@
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
@ -66,6 +72,7 @@
<version>${jackson.version}</version>
</dependency>
</dependencies>
<profiles>
<!-- Local -->
@ -97,6 +104,14 @@
</profile>
</profiles>
<repositories>
<repository>
<id>1</id>
<name>jstl</name>
<url>https://mvnrepository.com/artifact/javax.servlet/jstl</url>
</repository>
</repositories>
<properties>
<springframework.version>4.3.7.RELEASE</springframework.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
@ -104,9 +119,11 @@
<javax.servlet.jsp-api.version>2.3.1</javax.servlet.jsp-api.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<hibernate-validator.version>5.4.0.Final</hibernate-validator.version>
<deploy-path>enter-location-of-server</deploy-path>
<deploy-path>server default deploy directory</deploy-path>
<fileupload.version>1.3.2</fileupload.version>
<jackson.version>2.8.7</jackson.version>
<jackson.version>2.8.7</jackson.version><!-- persistence -->
<hibernate.version>5.2.5.Final</hibernate.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
</properties>
</project>

View File

@ -91,6 +91,7 @@ public class JSTLController {
@RequestMapping(value = "/xml_tags", method = RequestMethod.GET)
public ModelAndView xmlTags(final Model model) {
System.out.println("dddddddddddddddddffffffffffffff");
ModelAndView mv = new ModelAndView("xml_tags");
return mv;
}

View File

@ -3,16 +3,18 @@ package com.baeldung.springmvcforms.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.springmvcforms")
@ComponentScan(basePackages = {"com.baeldung.springmvcforms", "com.baeldung.jstl"})
class ApplicationConfiguration extends WebMvcConfigurerAdapter {
@Override
@ -20,15 +22,24 @@ class ApplicationConfiguration extends WebMvcConfigurerAdapter {
configurer.enable();
}
@Bean
public ResourceBundleMessageSource resourceBundleMessageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
// switch orders to server views from html over views directory
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(1);
return bean;
}
@Bean
public InternalResourceViewResolver htmlViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SessionAttrsApplicationTest {
public class SessionAttrsApplicationIntegrationTest {
@Test
public void contextLoads() {

View File

@ -25,7 +25,7 @@ import org.springframework.web.context.WebApplicationContext;
@SpringBootTest
@AutoConfigureMockMvc
@Import(TestConfig.class)
public class TodoControllerWithScopedProxyTest {
public class TodoControllerWithScopedProxyIntegrationTest {
@Autowired
private MockMvc mockMvc;

View File

@ -24,7 +24,7 @@ import org.springframework.web.servlet.FlashMap;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TodoControllerWithSessionAttributesTest {
public class TodoControllerWithSessionAttributesIntegrationTest {
@Autowired
private MockMvc mockMvc;

View File

@ -15,4 +15,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Geolocation by IP in Java](http://www.baeldung.com/geolocation-by-ip-with-maxmind)
- [Guide to JavaServer Pages (JSP)](http://www.baeldung.com/jsp)
- [Exploring SpringMVCs Form Tag Library](http://www.baeldung.com/spring-mvc-form-tags)
- [Guide to JSTL](http://www.baeldung.com/guide-to-jstl)

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