Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-04-25 21:21:47 +02:00
commit 238618abb5
123 changed files with 2594 additions and 1752 deletions

View File

@ -20,3 +20,4 @@
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)

View File

@ -6,6 +6,7 @@ import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
import com.baeldung.algorithms.slope_one.SlopeOne;
import com.baeldung.algorithms.pairsaddupnumber.FindPairs;
public class RunAlgorithm {
@ -17,6 +18,7 @@ public class RunAlgorithm {
System.out.println("3 - Simple Genetic Algorithm");
System.out.println("4 - Ant Colony");
System.out.println("5 - Dijkstra");
System.out.println("6 - All pairs in an array that add up to a given sum");
int decision = in.nextInt();
switch (decision) {
case 1:
@ -37,6 +39,12 @@ public class RunAlgorithm {
case 5:
System.out.println("Please run the DijkstraAlgorithmTest.");
break;
case 6:
final FindPairs findPairs = new FindPairs();
final int[] input = {1, 4, 3, 2, 1, 4, 4, 3, 3};
final int sum = 6;
findPairs.execute(input, sum);
break;
default:
System.out.println("Unknown option");
break;

View File

@ -0,0 +1,72 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
/**
* Find all different pairs of numbers in an array that add up to a given sum - Complexity O(n)
*/
public class DifferentPairs {
/**
* Show all different pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap();
for (int i : input) {
if (pairs.containsKey(i)) {
if (pairs.get(i) != null) {
// Add pair to returned list
allDifferentPairs.add(i);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - i, null);
} else if (!pairs.containsValue(i)) {
// Add pair to aux. hash map
pairs.put(sum - i, i);
}
}
return allDifferentPairs;
}
/**
* Show all different pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allDifferentPairs = new ArrayList<>();
// Aux. hash map
final Map<Integer, Integer> pairs = new HashMap();
IntStream.range(0, input.length).forEach(i -> {
if (pairs.containsKey(input[i])) {
if (pairs.get(input[i]) != null) {
// Add pair to returned list
allDifferentPairs.add(input[i]);
}
// Mark pair as added to prevent duplicates
pairs.put(sum - input[i], null);
} else if (!pairs.containsValue(input[i])) {
// Add pair to aux. hash map
pairs.put(sum - input[i], input[i]);
}
}
);
return allDifferentPairs;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
/**
* Find all existing pairs of numbers in an array that add up to a given sum - Complexity O(n^2) "Brute force"
*/
public class ExistingPairs {
/**
* Show all existing pairs using traditional "for" loop
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithForLoop(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (j != i && (input[i] + input[j]) == sum) {
allExistingPairs.add(input[i]);
}
}
}
return allExistingPairs;
}
/**
* Show all existing pairs using Java 8 stream API
*
* @param input - number's array
* @param sum - given sum
* @return - number's array with all existing pairs. This list will contain just one pair's element because
* the other one can be calculated with SUM - element_1 = element_2
*/
public static List<Integer> findPairsWithStreamApi(int[] input, int sum) {
final List<Integer> allExistingPairs = new ArrayList<>();
IntStream.range(0, input.length).forEach(i ->
IntStream.range(0, input.length)
.filter(j -> i != j && input[i] + input[j] == sum)
.forEach(j -> allExistingPairs.add(input[i]))
);
return allExistingPairs;
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.algorithms.pairsaddupnumber;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class FindPairs {
public void execute(int[] input, int sum) {
final StringBuilder inputArray = new StringBuilder();
inputArray.append("{");
IntStream.range(0, input.length).forEach(i -> inputArray.append(input[i] + ", "));
inputArray.append("}");
System.out.println(" Given number array: " + inputArray.toString());
System.out.println(" Given sum: " + sum);
/* Call services */
getDifferentPairs(input, sum);
getExistingPairs(input, sum);
}
/**
* Print all existing pairs for the given inputs: input array & sum number
*/
private static void getExistingPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All existing pairs ~");
/* Traditional FOR loop */
// Call method
pairs = ExistingPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output1 = new StringBuilder();
pairs.forEach((pair) -> output1.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output1.toString().substring(0, output1.length() - 2));
/* Java 8 stream API */
// Call the method
pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output2 = new StringBuilder();
pairs.forEach((pair) -> output2.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output2.toString().substring(0, output2.length() - 2));
}
/**
* Print all different pairs for the given inputs: input array & sum number
*/
private static void getDifferentPairs(int[] input, int sum) {
List<Integer> pairs = new ArrayList<>();
System.out.println("~ All different pairs ~");
/* Traditional FOR loop */
// Call method
pairs = DifferentPairs.findPairsWithForLoop(input, sum);
// Create a pretty printing
final StringBuilder output3 = new StringBuilder();
pairs.forEach((pair) -> output3.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Traditional \"for\" loop: " + output3.toString().substring(0, output3.length() - 2));
/* Java 8 stream API */
// Call method
pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
// Create a pretty printing
final StringBuilder output4 = new StringBuilder();
pairs.forEach((pair) -> output4.append("{" + pair + ", " + (sum - pair) + "}, "));
// Print result
System.out.println("Java 8 streams API: " + output4.toString().substring(0, output4.length() - 2));
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.algorithms.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class DifferentPairsUnitTest {
/* All different pairs */
@Test
public void whenTraditionalLoop_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllDifferentPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = DifferentPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertNotNull(pairs);
assertEquals(pairs.size(),2);
assertEquals(pairs.get(0), new Integer(4));
assertThat(pairs).hasSize(2).contains(4,3).doesNotContain(8);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.pairsaddupnumber;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ExistingPairsUnitTest {
/* All existing pairs */
@Test
public void whenTraditionalLoop_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithForLoop(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
@Test
public void whenStreamApi_thenReturnAllExistingPairs() {
/* Data */
final int[] input = {2, 4, 3, 3, 8};
final int sum = 6;
/* Call service */
final List<Integer> pairs = ExistingPairs.findPairsWithStreamApi(input, sum);
/* Check results */
assertThat(pairs).hasSize(4).contains(2,4,3,3).doesNotContain(8);
}
}

View File

@ -82,42 +82,6 @@
</resources>
</build>
<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>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<fop.version>1.1</fop.version>
<avalon-framework.version>4.3</avalon-framework.version>

View File

@ -1,4 +1,4 @@
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://github.com/eugenp/tutorials/tree/master/apache-poi)
- [Creating a MS PowerPoint Presentation in Java](http://www.baeldung.com/apache-poi-slideshow)

View File

@ -0,0 +1,146 @@
package com.baeldung.sqs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
import com.amazonaws.services.sqs.model.MessageAttributeValue;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.AmazonSQS;
public class SQSApplication {
private static final AWSCredentials credentials;
static {
// put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) {
// Set up the client
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_1)
.build();
// Create a standard queue
CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue");
String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
.getQueueUrl();
System.out.println(standardQueueUrl);
// Create a fifo queue
Map<String, String> queueAttributes = new HashMap<String, String>();
queueAttributes.put("FifoQueue", "true");
queueAttributes.put("ContentBasedDeduplication", "true");
CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes);
String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
.getQueueUrl();
System.out.println(fifoQueueUrl);
// Set up a dead letter queue
String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue")
.getQueueUrl();
GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn"));
String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes()
.get("QueueArn");
SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl)
.addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
sqs.setQueueAttributes(queueAttributesRequest);
// Send a message to a standard queue
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute")
.withDataType("String"));
SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl)
.withMessageBody("A simple message.")
.withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
.withMessageAttributes(messageAttributes);
sqs.sendMessage(sendMessageStandardQueue);
// Send a message to a fifo queue
SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl)
.withMessageBody("FIFO Queue")
.withMessageGroupId("baeldung-group-1")
.withMessageAttributes(messageAttributes);
sqs.sendMessage(sendMessageFifoQueue);
// Send multiple messages
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1")
.withMessageBody("batch-1")
.withMessageGroupId("baeldung-group-1"));
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2")
.withMessageBody("batch-2")
.withMessageGroupId("baeldung-group-1"));
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries);
sqs.sendMessageBatch(sendMessageBatchRequest);
// Read a message from a queue
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling;
.withMaxNumberOfMessages(1); // Max is 10
List<Message> sqsMessages = sqs.receiveMessage(receiveMessageRequest)
.getMessages();
sqsMessages.get(0)
.getAttributes();
sqsMessages.get(0)
.getBody();
// Delete a message from a queue
sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl)
.withReceiptHandle(sqsMessages.get(0)
.getReceiptHandle()));
// Monitoring
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All");
GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest);
System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes()
.get("ApproximateNumberOfMessages")));
System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes()
.get("ApproximateNumberOfMessagesNotVisible")));
}
}

View File

@ -44,41 +44,7 @@
</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>
<properties>
<spring.version>4.3.4.RELEASE</spring.version>
<aspectjweaver.version>1.8.9</aspectjweaver.version>

View File

@ -236,41 +236,6 @@
</plugins>
</build>
<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>**/*ManualTest.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>
<properties>

View File

@ -22,3 +22,4 @@
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)

View File

@ -183,41 +183,6 @@
</plugins>
</build>
<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>**/*ManualTest.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>
<properties>

View File

@ -22,4 +22,6 @@
- [A Guide To NIO2 FileVisitor](http://www.baeldung.com/java-nio2-file-visitor)
- [A Guide To NIO2 File Attribute APIs](http://www.baeldung.com/java-nio2-file-attribute)
- [Introduction to the Java NIO2 File API](http://www.baeldung.com/java-nio-2-file-api)
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
- [Zipping and Unzipping in Java](http://www.baeldung.com/java-compress-and-uncompress)
- [Java NIO2 Path API](http://www.baeldung.com/java-nio-2-path)
- [A Guide to WatchService in Java NIO2](http://www.baeldung.com/java-nio2-watchservice)

View File

@ -151,4 +151,5 @@
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)

View File

@ -235,6 +235,11 @@
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,26 @@
package com.baeldung.assertion;
/**
* Simple demonstration of using Java assert keyword.
*/
public class Assertion {
public static void main(String[] args) {
Assertion assertion = new Assertion();
assertion.setup();
}
public void setup() {
Object conn = getConnection();
assert conn != null : "Connection is null";
// continue with other setup ...
}
// Simulate failure to get a connection; using Object
// to avoid dependencies on JDBC or some other heavy
// 3rd party library
public Object getConnection() {
return null;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.designpatterns.singleton.synchronization;
/**
* Double-checked locking design pattern applied to a singleton.
*
* @author Donato Rimenti
*
*/
public class DclSingleton {
/**
* Current instance of the singleton.
*/
private static volatile DclSingleton instance;
/**
* Private constructor to avoid instantiation.
*/
private DclSingleton() {
}
/**
* Returns the current instance of the singleton.
*
* @return the current instance of the singleton
*/
public static DclSingleton getInstance() {
if (instance == null) {
synchronized (DclSingleton.class) {
if (instance == null) {
instance = new DclSingleton();
}
}
}
return instance;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.designpatterns.singleton.synchronization;
/**
* Draconian singleton. The method to get the instance is synchronized.
*
* @author Donato Rimenti
*
*/
public class DraconianSingleton {
/**
* Current instance of the singleton.
*/
private static DraconianSingleton instance;
/**
* Private constructor to avoid instantiation.
*/
private DraconianSingleton() {
}
/**
* Returns the current instance of the singleton.
*
* @return the current instance of the singleton
*/
public static synchronized DraconianSingleton getInstance() {
if (instance == null) {
instance = new DraconianSingleton();
}
return instance;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.designpatterns.singleton.synchronization;
/**
* Singleton with early initialization. Inlines the singleton instance
* initialization.
*
* @author Donato Rimenti
*
*/
public class EarlyInitSingleton {
/**
* Current instance of the singleton.
*/
private static final EarlyInitSingleton INSTANCE = new EarlyInitSingleton();
/**
* Private constructor to avoid instantiation.
*/
private EarlyInitSingleton() {
}
/**
* Returns the current instance of the singleton.
*
* @return the current instance of the singleton
*/
public static EarlyInitSingleton getInstance() {
return INSTANCE;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.designpatterns.singleton.synchronization;
/**
* Enum singleton pattern. Uses an enum to hold a reference to the singleton
* instance.
*
* @author Donato Rimenti
*
*/
public enum EnumSingleton {
/**
* Current instance of the singleton.
*/
INSTANCE;
}

View File

@ -0,0 +1,41 @@
package com.baeldung.designpatterns.singleton.synchronization;
/**
* Initialization on demand singleton pattern. Uses a nested static class to
* hold a reference to the singleton instance.
*
* @author Donato Rimenti
*
*/
public class InitOnDemandSingleton {
/**
* Holder for a singleton instance.
*
* @author Donato Rimenti
*
*/
private static class InstanceHolder {
/**
* Current instance of the singleton.
*/
private static final InitOnDemandSingleton INSTANCE = new InitOnDemandSingleton();
}
/**
* Private constructor to avoid instantiation.
*/
private InitOnDemandSingleton() {
}
/**
* Returns the current instance of the singleton.
*
* @return the current instance of the singleton
*/
public static InitOnDemandSingleton getInstance() {
return InstanceHolder.INSTANCE;
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailService {
private String host = "";
private int port = 0;
private String username = "";
private String password = "";
public EmailService(String host, int port, String username, String password) {
this.host = host;
this.port = port;
this.username = username;
this.password = password;
sendMail();
}
private void sendMail() {
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", host);
prop.put("mail.smtp.port", port);
prop.put("mail.smtp.ssl.trust", host);
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File("pom.xml"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String ... args) {
new EmailService("smtp.mailtrap.io", 25, "87ba3d9555fae8", "91cb4379af43ed");
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.optionalparams;
public class MultiVitamin {
private String name; // required
private int vitaminA; // in mcg
private int vitaminC; // in mg
private int calcium; // in mg
private int iron; // in mg
public MultiVitamin(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getVitaminA() {
return vitaminA;
}
public void setVitaminA(int vitaminA) {
this.vitaminA = vitaminA;
}
public int getVitaminC() {
return vitaminC;
}
public void setVitaminC(int vitaminC) {
this.vitaminC = vitaminC;
}
public int getCalcium() {
return calcium;
}
public void setCalcium(int calcium) {
this.calcium = calcium;
}
public int getIron() {
return iron;
}
public void setIron(int iron) {
this.iron = iron;
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.optionalparams;
public class MultiVitaminAllowingNulls {
private String name; // required
private Integer vitaminA; // in mcg
private Integer vitaminC; // in mg
private Integer calcium; // in mg
private Integer iron; // in mg
public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) {
this.name = name;
this.vitaminA = vitaminA;
this.vitaminC = vitaminC;
this.calcium = calcium;
this.iron = iron;
}
public String getName() {
return name;
}
public Integer getVitaminA() {
return vitaminA;
}
public Integer getVitaminC() {
return vitaminC;
}
public Integer getCalcium() {
return calcium;
}
public Integer getIron() {
return iron;
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.optionalparams;
public class MultiVitaminOverloading {
static final int DEFAULT_IRON_AMOUNT = 20;
private final String name; // required
private final int vitaminA; // in mcg
private final int vitaminC; // in mg
private final int calcium; // in mg
private final int iron; // in mg
public MultiVitaminOverloading(String name) {
this(name, 0);
}
public MultiVitaminOverloading(String name, int vitaminA) {
this(name, vitaminA, 0);
}
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) {
this(name, vitaminA, vitaminC, 0);
}
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) {
this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT);
}
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) {
this.name = name;
this.vitaminA = vitaminA;
this.vitaminC = vitaminC;
this.calcium = calcium;
this.iron = iron;
}
public String getName() {
return name;
}
public int getVitaminA() {
return vitaminA;
}
public int getVitaminC() {
return vitaminC;
}
public int getCalcium() {
return calcium;
}
public int getIron() {
return iron;
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.optionalparams;
public class MultiVitaminStaticFactoryMethods {
static final int IRON_AMT_DEF = 20;
static final int IRON_AMT_MEN = 30;
static final int CALCIUM_AMT_DEF = 100;
static final int CALCIUM_AMT_WOMEN = 120;
private final String name; // required
private final int vitaminA; // in mcg
private final int vitaminC; // in mg
private final int calcium; // in mg
private final int iron; // in mg
public static MultiVitaminStaticFactoryMethods forMen(String name) {
return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN);
}
public static MultiVitaminStaticFactoryMethods forWomen(String name) {
return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF);
}
private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) {
this.name = name;
this.vitaminA = vitaminA;
this.vitaminC = vitaminC;
this.calcium = calcium;
this.iron = iron;
}
public String getName() {
return name;
}
public int getVitaminA() {
return vitaminA;
}
public int getVitaminC() {
return vitaminC;
}
public int getCalcium() {
return calcium;
}
public int getIron() {
return iron;
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.optionalparams;
public class MultiVitaminWithBuilder {
private final String name; // required
private final int vitaminA; // in mcg
private final int vitaminC; // in mg
private final int calcium; // in mg
private final int iron; // in mg
private MultiVitaminWithBuilder(MultiVitaminBuilder builder) {
this.name = builder.name;
this.vitaminA = builder.vitaminA;
this.vitaminC = builder.vitaminC;
this.calcium = builder.calcium;
this.iron = builder.iron;
}
public String getName() {
return name;
}
public int getVitaminA() {
return vitaminA;
}
public int getVitaminC() {
return vitaminC;
}
public int getCalcium() {
return calcium;
}
public int getIron() {
return iron;
}
public static class MultiVitaminBuilder {
private static final int ZERO = 0;
private final String name; // required
private int vitaminA = ZERO;
private int vitaminC = ZERO;
private int calcium = ZERO;
private int iron = ZERO;
public MultiVitaminBuilder(String name) {
this.name = name;
}
public MultiVitaminBuilder withVitaminA(int vitaminA) {
this.vitaminA = vitaminA;
return this;
}
public MultiVitaminBuilder withVitaminC(int vitaminC) {
this.vitaminC = vitaminC;
return this;
}
public MultiVitaminBuilder withCalcium(int calcium) {
this.calcium = calcium;
return this;
}
public MultiVitaminBuilder withIron(int iron) {
this.iron = iron;
return this;
}
public MultiVitaminWithBuilder build() {
return new MultiVitaminWithBuilder(this);
}
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.parameterpassing;
public class NonPrimitives {
public static void main(String[] args) {
FooClass a = new FooClass(1);
FooClass b = new FooClass(1);
System.out.printf("Before Modification: a = %d and b = %d ", a.num, b.num);
modify(a, b);
System.out.printf("\nAfter Modification: a = %d and b = %d ", a.num, b.num);
}
public static void modify(FooClass a1, FooClass b1) {
a1.num++;
b1 = new FooClass(1);
b1.num++;
}
}
class FooClass {
public int num;
public FooClass(int num) {
this.num = num;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.parameterpassing;
public class Primitives {
public static void main(String[] args) {
int x = 1;
int y = 2;
System.out.printf("Before Modification: x = %d and y = %d ", x, y);
modify(x, y);
System.out.printf("\nAfter Modification: x = %d and y = %d ", x, y);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}

View File

@ -0,0 +1,119 @@
package com.baeldung.designpatterns.singleton.synchronization;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for the singleton synchronization package with the same name.
*
* @author Donato Rimenti
*
*/
public class SingletonSynchronizationUnitTest {
/**
* Size of the thread pools used.
*/
private static final int POOL_SIZE = 1_000;
/**
* Number of tasks to submit.
*/
private static final int TASKS_TO_SUBMIT = 1_000_000;
/**
* Tests the thread-safety of {@link DraconianSingleton}.
*/
@Test
public void givenDraconianSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<DraconianSingleton> resultSet = Collections.synchronizedSet(new HashSet<DraconianSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(DraconianSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link DclSingleton}.
*/
@Test
public void givenDclSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<DclSingleton> resultSet = Collections.synchronizedSet(new HashSet<DclSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(DclSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link EarlyInitSingleton}.
*/
@Test
public void givenEarlyInitSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<EarlyInitSingleton> resultSet = Collections.synchronizedSet(new HashSet<EarlyInitSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(EarlyInitSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link InitOnDemandSingleton}.
*/
@Test
public void givenInitOnDemandSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<InitOnDemandSingleton> resultSet = Collections.synchronizedSet(new HashSet<InitOnDemandSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(InitOnDemandSingleton.getInstance()));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
/**
* Tests the thread-safety of {@link EnumSingleton}.
*/
@Test
public void givenEnumSingleton_whenMultithreadInstancesEquals_thenTrue() {
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
Set<EnumSingleton> resultSet = Collections.synchronizedSet(new HashSet<EnumSingleton>());
// Submits the instantiation tasks.
for (int i = 0; i < TASKS_TO_SUBMIT; i++) {
executor.submit(() -> resultSet.add(EnumSingleton.INSTANCE));
}
// Since the instance of the object we inserted into the set is always
// the same, the size should be one.
Assert.assertEquals(1, resultSet.size());
}
}

View File

@ -0,0 +1,159 @@
package com.baeldung.java.clock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClockUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ClockUnitTest.class);
@Test
public void givenClock_withSytemUTC_retrievesInstant() {
Clock clockUTC = Clock.systemUTC();
assertEquals(clockUTC.getZone(), ZoneOffset.UTC);
assertEquals(clockUTC.instant().equals(null), false);
LOGGER.debug("UTC instant :: " + clockUTC.instant());
}
@Test
public void givenClock_withSytem_retrievesInstant() {
Clock clockSystem = Clock.system(ZoneId.of("Asia/Calcutta"));
assertEquals(clockSystem.getZone(), ZoneId.of("Asia/Calcutta"));
assertEquals(clockSystem.instant().equals(null), false);
LOGGER.debug("System zone :: " + clockSystem.getZone());
}
@Test
public void givenClock_withSytemDefaultZone_retrievesInstant() {
Clock clockSystemDefault = Clock.systemDefaultZone();
assertEquals(clockSystemDefault.getZone().equals(null), false);
assertEquals(clockSystemDefault.instant().equals(null), false);
LOGGER.debug("System Default instant :: " + clockSystemDefault.instant());
}
@Test
public void givenClock_withSytemUTC_retrievesTimeInMillis() {
Clock clockMillis = Clock.systemDefaultZone();
assertEquals(clockMillis.instant().equals(null), false);
assertTrue(clockMillis.millis() > 0);
LOGGER.debug("System Default millis :: " + clockMillis.millis());
}
@Test
public void givenClock_usingOffset_retrievesFutureDate() {
Clock baseClock = Clock.systemDefaultZone();
// result clock will be later than baseClock
Clock futureClock = Clock.offset(baseClock, Duration.ofHours(72));
assertEquals(futureClock.instant().equals(null), false);
assertTrue(futureClock.millis() > baseClock.millis());
LOGGER.debug("Future Clock instant :: " + futureClock.instant());
}
@Test
public void givenClock_usingOffset_retrievesPastDate() {
Clock baseClock = Clock.systemDefaultZone();
// result clock will be later than baseClock
Clock pastClock = Clock.offset(baseClock, Duration.ofHours(-72));
assertEquals(pastClock.instant().equals(null), false);
assertTrue(pastClock.millis() < baseClock.millis());
LOGGER.debug("Past Clock instant :: " + pastClock.instant());
}
@Test
public void givenClock_usingTick_retrievesInstant() {
Clock clockDefaultZone = Clock.systemDefaultZone();
Clock clocktick = Clock.tick(clockDefaultZone, Duration.ofSeconds(300));
assertEquals(clockDefaultZone.instant().equals(null), false);
assertEquals(clocktick.instant().equals(null), false);
assertTrue(clockDefaultZone.millis() > clocktick.millis());
LOGGER.debug("Clock Default Zone instant : " + clockDefaultZone.instant());
LOGGER.debug("Clock tick instant: " + clocktick.instant());
}
@Test(expected=IllegalArgumentException.class)
public void givenClock_usingTickDurationNegative_throwsException() {
Clock clockDefaultZone = Clock.systemDefaultZone();
Clock.tick(clockDefaultZone, Duration.ofSeconds(-300));
}
@Test
public void givenClock_usingTickSeconds_retrievesInstant() {
ZoneId zoneId = ZoneId.of("Asia/Calcutta");
Clock tickSeconds = Clock.tickSeconds(zoneId);
assertEquals(tickSeconds.instant().equals(null), false);
LOGGER.debug("Clock tick seconds instant :: " + tickSeconds.instant());
tickSeconds = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofSeconds(100));
assertEquals(tickSeconds.instant().equals(null), false);
}
@Test
public void givenClock_usingTickMinutes_retrievesInstant() {
Clock tickMinutes = Clock.tickMinutes(ZoneId.of("Asia/Calcutta"));
assertEquals(tickMinutes.instant().equals(null), false);
LOGGER.debug("Clock tick seconds instant :: " + tickMinutes.instant());
tickMinutes = Clock.tick(Clock.system(ZoneId.of("Asia/Calcutta")), Duration.ofMinutes(5));
assertEquals(tickMinutes.instant().equals(null), false);
}
@Test
public void givenClock_usingWithZone_retrievesInstant() {
ZoneId zoneSingapore = ZoneId.of("Asia/Singapore");
Clock clockSingapore = Clock.system(zoneSingapore);
assertEquals(clockSingapore.instant().equals(null), false);
LOGGER.debug("clockSingapore instant : " + clockSingapore.instant());
ZoneId zoneCalcutta = ZoneId.of("Asia/Calcutta");
Clock clockCalcutta = clockSingapore.withZone(zoneCalcutta);
assertEquals(clockCalcutta.instant().equals(null), false);
LOGGER.debug("clockCalcutta instant : " + clockSingapore.instant());
}
@Test
public void givenClock_usingGetZone_retrievesZoneId() {
Clock clockDefaultZone = Clock.systemDefaultZone();
ZoneId zone = clockDefaultZone.getZone();
assertEquals(zone.getId().equals(null), false);
LOGGER.debug("Default zone instant : " + clockDefaultZone.instant());
}
}

View File

@ -0,0 +1,96 @@
package com.baeldung.optionalparams;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.assertj.core.util.Arrays;
import org.junit.Test;
public class OptionalParamsUnitTest {
@Test
public void whenCreateMultiVitaminWithOverloading_thenOk() {
MultiVitaminOverloading multiVitamin = new MultiVitaminOverloading("Default Multivitamin");
assertThat(multiVitamin.getName()).isEqualTo("Default Multivitamin");
assertThat(multiVitamin.getVitaminA()).isEqualTo(0);
assertThat(multiVitamin.getVitaminC()).isEqualTo(0);
assertThat(multiVitamin.getCalcium()).isEqualTo(0);
assertThat(multiVitamin.getIron()).isEqualTo(MultiVitaminOverloading.DEFAULT_IRON_AMOUNT);
}
@Test
public void whenCreateMultiVitaminWithStaticFactoryMethods_thenOk() {
MultiVitaminStaticFactoryMethods mensMultiVitamin = MultiVitaminStaticFactoryMethods.forMen("Complete for Men");
assertThat(mensMultiVitamin.getName()).isEqualTo("Complete for Men");
assertThat(mensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_DEF);
assertThat(mensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_MEN);
MultiVitaminStaticFactoryMethods womensMultiVitamin = MultiVitaminStaticFactoryMethods.forWomen("Complete for Women");
assertThat(womensMultiVitamin.getName()).isEqualTo("Complete for Women");
assertThat(womensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_WOMEN);
assertThat(womensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_DEF);
}
@Test
public void whenCreateMultiVitaminWithBuilder_thenOk() {
MultiVitaminWithBuilder vitamin = new MultiVitaminWithBuilder.MultiVitaminBuilder("Maximum Strength")
.withCalcium(100)
.withIron(200)
.withVitaminA(50)
.withVitaminC(1000)
.build();
assertThat(vitamin.getName()).isEqualTo("Maximum Strength");
assertThat(vitamin.getCalcium()).isEqualTo(100);
assertThat(vitamin.getIron()).isEqualTo(200);
assertThat(vitamin.getVitaminA()).isEqualTo(50);
assertThat(vitamin.getVitaminC()).isEqualTo(1000);
}
@Test
public void whenCreateMutliVitaminWithAccessors_thenOk() {
MultiVitamin vitamin = new MultiVitamin("Generic");
vitamin.setVitaminA(50);
vitamin.setVitaminC(1000);
vitamin.setCalcium(100);
vitamin.setIron(200);
assertThat(vitamin.getName()).isEqualTo("Generic");
assertThat(vitamin.getCalcium()).isEqualTo(100);
assertThat(vitamin.getIron()).isEqualTo(200);
assertThat(vitamin.getVitaminA()).isEqualTo(50);
assertThat(vitamin.getVitaminC()).isEqualTo(1000);
}
@Test
public void whenCreateMultiVitaminWithNulls_thenOk() {
MultiVitamin vitamin = new MultiVitamin(null);
assertThat(vitamin.getName()).isNull();
}
public void varArgsDemo() {
Object[] args = Arrays.array(Long.valueOf(1), Integer.valueOf(2), BigDecimal.valueOf(3));
processVarArgsWithCastingAntiPattern(args);
}
private void processVarArgsWithCastingAntiPattern(Object... args) {
String message = "processing %s as %s";
// never do this sort of thing
for (Object arg : args) {
if (arg instanceof Long) {
System.out.println(String.format(message, arg, "Long"));
} else if (arg instanceof Integer) {
System.out.println(String.format(message, arg, "Integer"));
} else if (arg instanceof BigDecimal) {
System.out.println(String.format(message, arg, "BigDecimal"));
}
}
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class NonPrimitivesUnitTest {
@Test
public void whenModifyingObjects_thenOriginalObjectChanged() {
Foo a = new Foo(1);
Foo b = new Foo(1);
// Before Modification
Assert.assertEquals(a.num, 1);
Assert.assertEquals(b.num, 1);
modify(a, b);
// After Modification
Assert.assertEquals(a.num, 2);
Assert.assertEquals(b.num, 1);
}
public static void modify(Foo a1, Foo b1) {
a1.num++;
b1 = new Foo(1);
b1.num++;
}
}
class Foo {
public int num;
public Foo(int num) {
this.num = num;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class PrimitivesUnitTest {
@Test
public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
int x = 1;
int y = 2;
// Before Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
modify(x, y);
// After Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}

View File

@ -24,3 +24,4 @@
- [Regular Expressions in Kotlin](http://www.baeldung.com/kotlin-regular-expressions)
- [Objects in Kotlin](http://www.baeldung.com/kotlin-objects)
- [Reading from a File in Kotlin](http://www.baeldung.com/kotlin-read-file)
- [Guide to Kotlin @JvmField](http://www.baeldung.com/kotlin-jvm-field-annotation)

View File

@ -5,6 +5,7 @@
- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring)
- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase)
- [Querying Couchbase with MapReduce Views](http://www.baeldung.com/couchbase-query-mapreduce-view)
- [Querying Couchbase with N1QL](http://www.baeldung.com/n1ql-couchbase)
### Overview
This Maven project contains the Java code for the Couchbase entities and Spring services

View File

@ -139,33 +139,6 @@
</build>
<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>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>

View File

@ -77,36 +77,6 @@
<finalName>ethereumj</finalName>
</build>
<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>none</exclude>
</excludes>
<includes>
<include>*/EthControllerTestOne.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>

View File

@ -32,3 +32,4 @@
- [Bloom Filter in Java using Guava](http://www.baeldung.com/guava-bloom-filter)
- [Using Guava CountingOutputStream](http://www.baeldung.com/guava-counting-outputstream)
- [Hamcrest Text Matchers](http://www.baeldung.com/hamcrest-text-matchers)
- [Quick Guide to the Guava RateLimiter](http://www.baeldung.com/guava-rate-limiter)

View File

@ -78,40 +78,4 @@
<scope>test</scope>
</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

@ -994,32 +994,5 @@
</dependency>
</dependencies>
</profile>
<profile>
<id>integration</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<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>
<includes>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -45,39 +45,4 @@
</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

@ -72,7 +72,7 @@
</dependency>
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring</artifactId>
<artifactId>ignite-spring-data</artifactId>
<version>${ignite.version}</version>
</dependency>
<dependency>
@ -192,7 +192,7 @@
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<ormlite.version>5.0</ormlite.version>
<kafka.version>1.0.0</kafka.version>
<ignite.version>2.3.0</ignite.version>
<ignite.version>2.4.0</ignite.version>
<gson.version>2.8.2</gson.version>
</properties>
</project>

View File

@ -0,0 +1,53 @@
package com.baeldung.ignite.spring;
import com.baeldung.ignite.spring.config.SpringDataConfig;
import com.baeldung.ignite.spring.dto.EmployeeDTO;
import com.baeldung.ignite.spring.repository.EmployeeRepository;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.QueryCursor;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;
/**
* Created by Gebruiker on 4/12/2018.
*/
public class IgniteApp {
public static void main (String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(SpringDataConfig.class);
context.refresh();
EmployeeRepository repository = context.getBean(EmployeeRepository.class);
EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setId(1);
employeeDTO.setName("John");
employeeDTO.setEmployed(true);
repository.save(employeeDTO.getId(), employeeDTO);
EmployeeDTO employee = repository.getEmployeeDTOById(employeeDTO.getId());
System.out.println(employee);
}
private void getUsingTheCache(Integer employeeId) {
Ignite ignite = Ignition.ignite();
IgniteCache<Integer, EmployeeDTO> cache = ignite.cache("baeldungCache");
EmployeeDTO employeeDTO = cache.get(employeeId);
System.out.println(employeeDTO);
SqlFieldsQuery sql = new SqlFieldsQuery(
"select * from EmployeeDTO where isEmployed = 'true'");
QueryCursor<List<?>> cursor = cache.query(sql);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.ignite.spring.config;
import com.baeldung.ignite.spring.dto.EmployeeDTO;
import com.baeldung.ignite.spring.repository.EmployeeRepository;
import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.springdata.repository.config.EnableIgniteRepositories;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableIgniteRepositories(basePackageClasses = EmployeeRepository.class)
@ComponentScan(basePackages = "com.baeldung.ignite.spring.repository")
public class SpringDataConfig {
@Bean
public Ignite igniteInstance() {
IgniteConfiguration config = new IgniteConfiguration();
CacheConfiguration cache = new CacheConfiguration("baeldungCache");
cache.setIndexedTypes(Integer.class, EmployeeDTO.class);
config.setCacheConfiguration(cache);
return Ignition.start(config);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.ignite.spring.dto;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import java.io.Serializable;
public class EmployeeDTO implements Serializable {
@QuerySqlField(index = true)
private Integer id;
@QuerySqlField(index = true)
private String name;
@QuerySqlField(index = true)
private boolean isEmployed;
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;
}
public boolean isEmployed() {
return isEmployed;
}
public void setEmployed(boolean employed) {
isEmployed = employed;
}
@Override
public String toString() {
return "EmployeeDTO{" +
"id=" + id +
", name='" + name + '\'' +
", isEmployed=" + isEmployed +
'}';
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.ignite.spring.repository;
import com.baeldung.ignite.spring.dto.EmployeeDTO;
import org.apache.ignite.springdata.repository.IgniteRepository;
import org.apache.ignite.springdata.repository.config.RepositoryConfig;
import org.springframework.stereotype.Repository;
@Repository
@RepositoryConfig(cacheName = "baeldungCache")
public interface EmployeeRepository extends IgniteRepository<EmployeeDTO, Integer> {
EmployeeDTO getEmployeeDTOById(Integer id);
}

View File

@ -59,12 +59,12 @@
- [Intro to JDO Queries 2/2](http://www.baeldung.com/jdo-queries)
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
- [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup)
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
- [Introduction To OpenCSV](http://www.baeldung.com/opencsv)
- [Introduction to Akka Actors in Java] (http://www.baeldung.com/akka-actors-java)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [Asynchronous HTTP with async-http-client in Java](https://github.com/eugenp/tutorials/tree/master/libraries)
- [Introduction to Smooks](http://www.baeldung.com/smooks)
- [WebSockets with AsyncHttpClient](http://www.baeldung.com/async-http-client-websockets)
@ -72,6 +72,8 @@
- [Introduction to OpenCSV](http://www.baeldung.com/opencsv)
- [A Guide to Unirest](http://www.baeldung.com/unirest)
- [Introduction to Akka Actors in Java](http://www.baeldung.com/akka-actors-java)
- [A Guide to Apache Commons Collections CollectionUtils](http://www.baeldung.com/apache-commons-collection-utils)
- [A Guide to Byte Buddy](http://www.baeldung.com/byte-buddy)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -686,6 +686,12 @@
<artifactId>fugue</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.jctools</groupId>
<artifactId>jctools-core</artifactId>
<version>${jctools.version}</version>
</dependency>
</dependencies>
<repositories>
@ -785,6 +791,52 @@
</archive>
</configuration>
</plugin>
<!-- /Neuroph -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Borrowed from the 'jmh-java-benchmark-archetype' pom.xml -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>benchmarks</finalName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<!--
Shading signed JARs will fail without this.
http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar
-->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -856,6 +908,7 @@
<infinispan.version>9.1.5.Final</infinispan.version>
<opencsv.version>4.1</opencsv.version>
<unirest.version>1.4.9</unirest.version>
<jctools.version>2.1.2</jctools.version>
<commons-codec-version>1.10.L001</commons-codec-version>
<jets3t-version>0.9.4.0006L</jets3t-version>
</properties>

View File

@ -0,0 +1,73 @@
package com.baeldung.jctools;
import org.jctools.queues.MpmcArrayQueue;
import org.jctools.queues.atomic.MpmcAtomicArrayQueue;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Control;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Fork(1)
@Warmup(iterations = 1)
@Measurement(iterations = 3)
@State(Scope.Group)
public class MpmcBenchmark {
public static final String PARAM_UNSAFE = "MpmcArrayQueue";
public static final String PARAM_AFU = "MpmcAtomicArrayQueue";
public static final String PARAM_JDK = "ArrayBlockingQueue";
public static final int PRODUCER_THREADS_NUMBER = 32;
public static final int CONSUMER_THREADS_NUMBER = 32;
public static final String GROUP_NAME = "MyGroup";
public static final int CAPACITY = 128;
@Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK})
public volatile String implementation;
public volatile Queue<Long> queue;
@Setup(Level.Trial)
public void setUp() {
switch (implementation) {
case PARAM_UNSAFE:
queue = new MpmcArrayQueue<>(CAPACITY);
break;
case PARAM_AFU:
queue = new MpmcAtomicArrayQueue<>(CAPACITY);
break;
case PARAM_JDK:
queue = new ArrayBlockingQueue<>(CAPACITY);
break;
default:
throw new UnsupportedOperationException("Unsupported implementation " + implementation);
}
}
@Benchmark
@Group(GROUP_NAME)
@GroupThreads(PRODUCER_THREADS_NUMBER)
public void write(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && !queue.offer(1L)) {
// Is intentionally left blank
}
}
@Benchmark
@Group(GROUP_NAME)
@GroupThreads(CONSUMER_THREADS_NUMBER)
public void read(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && queue.poll() == null) {
// Is intentionally left blank
}
}
}

View File

@ -0,0 +1,7 @@
## How to build and run the JMH benchmark
Execute the following from the project's root:
```bash
mvn clean install
java -jar ./target/benchmarks.jar MpmcBenchmark -si true
```

View File

@ -0,0 +1,86 @@
package com.baeldung.jctools;
import org.jctools.queues.SpscArrayQueue;
import org.jctools.queues.SpscChunkedArrayQueue;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
public class JCToolsUnitTest {
@Test
public void givenMultipleProducers_whenSpscQueueUsed_thenNoWarningOccurs() throws InterruptedException {
SpscArrayQueue<Integer> queue = new SpscArrayQueue<Integer>(2);
Thread producer1 = new Thread(() -> {
queue.offer(1);
});
producer1.start();
producer1.join();
Thread producer2 = new Thread(() -> {
queue.offer(2);
});
producer2.start();
producer2.join();
Set<Integer> fromQueue = new HashSet<>();
Thread consumer = new Thread(() -> queue.drain(fromQueue::add));
consumer.start();
consumer.join();
assertThat(fromQueue).containsOnly(1, 2);
}
@Test
public void whenQueueIsFull_thenNoMoreElementsCanBeAdded() throws InterruptedException {
SpscChunkedArrayQueue<Integer> queue = new SpscChunkedArrayQueue<>(8, 16);
assertThat(queue.capacity()).isEqualTo(16);
CountDownLatch startConsuming = new CountDownLatch(1);
CountDownLatch awakeProducer = new CountDownLatch(1);
AtomicReference<Throwable> error = new AtomicReference<>();
Thread producer = new Thread(() -> {
IntStream.range(0, queue.capacity()).forEach(i -> {
assertThat(queue.offer(i)).isTrue();
});
assertThat(queue.offer(queue.capacity())).isFalse();
startConsuming.countDown();
try {
awakeProducer.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
assertThat(queue.offer(queue.capacity())).isTrue();
});
producer.setUncaughtExceptionHandler((t, e) -> {
error.set(e);
startConsuming.countDown();
});
producer.start();
startConsuming.await();
if (error.get() != null) {
fail("Producer's assertion failed", error.get());
}
Set<Integer> fromQueue = new HashSet<>();
queue.drain(fromQueue::add);
awakeProducer.countDown();
producer.join();
queue.drain(fromQueue::add);
assertThat(fromQueue).containsAll(IntStream.range(0, 17).boxed().collect(Collectors.toSet()));
}
}

View File

@ -52,16 +52,12 @@ public class EmbeddedChannelUnitTest {
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Add");
Throwable thrownException = catchThrowable(() -> {
// send invalid HTTP request to server and expect and error
channel.pipeline().fireChannelRead(wrongHttpRequest);
channel.checkException();
Assertions.failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);
});
assertThat(thrownException)
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("HTTP method not supported");
assertThatThrownBy(() -> {
// send invalid HTTP request to server and expect and error
channel.pipeline().fireChannelRead(wrongHttpRequest);
channel.checkException();
}).isInstanceOf(UnsupportedOperationException.class)
.hasMessage("HTTP method not supported");
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
@ -77,15 +73,11 @@ public class EmbeddedChannelUnitTest {
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Invalid_operation");
Throwable thrownException = catchThrowable(() -> {
// send invalid HTTP request to server and expect and error
channel.writeInbound(wrongHttpRequest);
Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
});
// the HttpMessageHandler does not handle the exception and throws it down the
// pipeline
assertThat(thrownException).isInstanceOf(IllegalArgumentException.class).hasMessage("Operation not defined");
// the HttpMessageHandler does not handle the exception and throws it down the pipeline
assertThatThrownBy(() -> {
channel.writeInbound(wrongHttpRequest);
}).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Operation not defined");
// the outbound message is a HTTP response with the status code 500
FullHttpResponse errorHttpResponse = channel.readOutbound();

View File

@ -58,39 +58,4 @@
</plugins>
</build>
<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>

9
maven/README.md Normal file
View File

@ -0,0 +1,9 @@
### Relevant Articles
- [Guide to the Core Maven Plugins](http://www.baeldung.com/core-maven-plugins)
- [Maven Resources Plugin](http://www.baeldung.com/maven-resources-plugin)
- [Maven Compiler Plugin](http://www.baeldung.com/maven-compiler-plugin)
- [Quick Guide to the Maven Surefire Plugin](http://www.baeldung.com/maven-surefire-plugin)
- [The Maven Failsafe Plugin](http://www.baeldung.com/maven-failsafe-plugin)
- [The Maven Verifier Plugin](http://www.baeldung.com/maven-verifier-plugin)
- [The Maven Clean Plugin](http://www.baeldung.com/maven-clean-plugin)

View File

@ -75,5 +75,45 @@
</plugin>
</plugins>
</build>
<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>**/*ManualTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/AutoconfigurationTest.java</exclude>
<exclude>**/*UnitTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>*/EthControllerTestOne.java</include>
<include>**/*IntTest.java</include>
<include>**/*EntryPointsTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -43,41 +43,6 @@
<finalName>java-cassandra</finalName>
</build>
<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>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -28,41 +28,6 @@
</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>**/*ManualTest.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>
<repositories>
<repository>
<id>Central</id>

View File

@ -32,41 +32,6 @@
</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>**/*ManualTest.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>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

View File

@ -163,40 +163,4 @@
</plugin>
</plugins>
</build>
<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

@ -87,39 +87,4 @@
<optional>true</optional>
</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

@ -117,41 +117,6 @@
</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>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>

View File

@ -98,41 +98,6 @@
</build>
<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>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>

36
pom.xml
View File

@ -482,4 +482,40 @@
</extensions>
</build>
<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>**/*ManualTest.java</exclude>
<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

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

View File

@ -1,4 +1,4 @@
package com.baeldung.reactive.filter;
package com.baeldung.reactive.filters;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

View File

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

View File

@ -1,7 +1,5 @@
package com.baeldung.reactive.router;
package com.baeldung.reactive.filters;
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;
@ -17,6 +15,6 @@ public class PlayerRouter {
public RouterFunction<ServerResponse> route(PlayerHandler playerHandler) {
return RouterFunctions
.route(GET("/players/{name}"), playerHandler::getName)
.filter(new ExampleHandlerFilterFunction()::filter);
.filter(new ExampleHandlerFilterFunction());
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.reactive.controller;
package com.baeldung.reactive.filters;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

View File

@ -1,4 +1,4 @@
package com.baeldung.reactive.handler;
package com.baeldung.reactive.filters;
import org.junit.Test;
import org.junit.runner.RunWith;

View File

@ -1,4 +1,4 @@
package com.baeldung.reactive.controller;
package com.baeldung.reactive.filters;
import org.junit.Test;
import org.junit.runner.RunWith;

View File

@ -12,7 +12,7 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring 5 Functional Bean Registration](http://www.baeldung.com/spring-5-functional-beans)
- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5](http://www.baeldung.com/spring-5-junit-config)
- [Spring Security 5 for Reactive Applications](http://www.baeldung.com/spring-security-5-reactive)
- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/sring-5-enabledif)
- [Spring 5 Testing with @EnabledIf Annotation](http://www.baeldung.com/spring-5-enabledIf)
- [Introduction to Spring REST Docs](http://www.baeldung.com/spring-rest-docs)
- [Spring Security 5 OAuth2 Login](http://www.baeldung.com/spring-security-5-oauth2-login)
- [Spring ResponseStatusException](http://www.baeldung.com/spring-response-status-exception)

View File

@ -51,41 +51,6 @@
</dependencyManagement>
<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>
<properties>
<spring.version>4.3.4.RELEASE</spring.version>
<akka.version>2.4.14</akka.version>

View File

@ -227,41 +227,6 @@
</build>
<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>
<properties>
<start-class>org.baeldung.sample.App</start-class>
<!-- Spring -->

View File

@ -1,3 +1,3 @@
### Relevant Articles:
- [Spring with Maven BOM]
- [Spring with Maven BOM](http://www.baeldung.com/spring-maven-bom)

View File

@ -87,39 +87,6 @@
</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>
<exclude>**/AutoconfigurationTest.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>
<profile>
<id>autoconfiguration</id>
<build>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class)

View File

@ -1,4 +1,4 @@
###The Course
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
@ -33,4 +33,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [A Quick Guide to Maven Wrapper](http://www.baeldung.com/maven-wrapper)
- [An Introduction to Kong](http://www.baeldung.com/kong)
- [Spring Boot Customize Whitelabel Error Page](http://www.baeldung.com/spring-boot-custom-error-page)
- [Spring Boot: Configuring a Main Class](http://www.baeldung.com/spring-boot-main-class)

View File

@ -200,39 +200,6 @@
</build>
<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>
<exclude>**/AutoconfigurationTest.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>
<profile>
<id>autoconfiguration</id>
<build>

View File

@ -15,6 +15,14 @@ public class User {
private String name;
private Integer status;
public User() {
}
public User(String name, Integer status) {
this.name = name;
this.status = status;
}
public Integer getId() {
return id;
}

View File

@ -1,10 +1,20 @@
package org.baeldung.repository;
import org.baeldung.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
@ -21,4 +31,54 @@ public interface UserRepository extends JpaRepository<User, Integer> {
@Async
CompletableFuture<User> findOneByStatus(Integer status);
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
User findUserByStatusAndName(Integer status, String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
@Query("SELECT u FROM User u WHERE u.name like ?1%")
User findUserByNameLike(String name);
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM Users ORDER BY id \n-- #pageable\n", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@Query("update User u set u.status = :status where u.name = :name")
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
}

View File

@ -1,58 +1,65 @@
package org.baeldung.repository;
import org.baeldung.boot.Application;
import org.baeldung.boot.config.H2JpaConfig;
import org.baeldung.model.User;
import org.junit.After;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.JpaSort;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created by adam.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@SpringBootTest(classes = H2JpaConfig.class)
public class UserRepositoryIntegrationTest {
private final String USER_NAME_ADAM = "Adam";
private final String USER_NAME_PETER = "Peter";
private final Integer INACTIVE_STATUS = 0;
private final Integer ACTIVE_STATUS = 1;
@Autowired
private UserRepository userRepository;
@Autowired private UserRepository userRepository;
@Test
public void shouldReturnEmptyOptionalWhenSearchByNameInEmptyDB() {
public void givenEmptyDBWhenFindOneByNameThenReturnEmptyOptional() {
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(false));
assertThat(foundUser.isPresent()).isEqualTo(false);
}
@Test
public void shouldReturnOptionalWithPresentUserWhenExistsWithGivenName() {
public void givenUserInDBWhenFindOneByNameThenReturnOptionalWithUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
userRepository.save(user);
Optional<User> foundUser = userRepository.findOneByName(USER_NAME_ADAM);
assertThat(foundUser.isPresent(), equalTo(true));
assertThat(foundUser.get().getName(), equalTo(USER_NAME_ADAM));
assertThat(foundUser.isPresent()).isEqualTo(true);
assertThat(foundUser.get().getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
@Transactional
public void shouldReturnStreamOfUsersWithNameWhenExistWithSameGivenName() {
public void givenUsersWithSameNameInDBWhenFindAllByNameThenReturnStreamOfUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
userRepository.save(user1);
@ -70,12 +77,12 @@ public class UserRepositoryIntegrationTest {
userRepository.save(user4);
try (Stream<User> foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) {
assertThat(foundUsersStream.count(), equalTo(3l));
assertThat(foundUsersStream.count()).isEqualTo(3l);
}
}
@Test
public void shouldReturnUserWithGivenStatusAsync() throws ExecutionException, InterruptedException {
public void givenUserInDBWhenFindOneByStatusAsyncThenReturnCompletableFutureUser() throws ExecutionException, InterruptedException {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
@ -83,8 +90,271 @@ public class UserRepositoryIntegrationTest {
CompletableFuture<User> userByStatus = userRepository.findOneByStatus(ACTIVE_STATUS);
assertThat(userByStatus.get().getName(), equalTo(USER_NAME_ADAM));
assertThat(userByStatus.get().getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsers();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUsersInDBWhenFindAllWithQueryAnnotationNativeThenReturnCollectionWithActiveUsers() {
User user1 = new User();
user1.setName(USER_NAME_ADAM);
user1.setStatus(ACTIVE_STATUS);
userRepository.save(user1);
User user2 = new User();
user2.setName(USER_NAME_ADAM);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User user3 = new User();
user3.setName(USER_NAME_ADAM);
user3.setStatus(INACTIVE_STATUS);
userRepository.save(user3);
Collection<User> allActiveUsers = userRepository.findAllActiveUsersNative();
assertThat(allActiveUsers.size()).isEqualTo(2);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUserInDBWhenFindUserByStatusWithQueryAnnotationNativeThenReturnActiveUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationIndexedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParamsThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNamesThenReturnOneUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User user2 = new User();
user2.setName(USER_NAME_PETER);
user2.setStatus(ACTIVE_STATUS);
userRepository.save(user2);
User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM);
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationIndexedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLike("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNamedParamsThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindUserByNameLikeWithQueryAnnotationNativeThenReturnUser() {
User user = new User();
user.setName(USER_NAME_ADAM);
user.setStatus(ACTIVE_STATUS);
userRepository.save(user);
User userByStatus = userRepository.findUserByNameLikeNative("Ad");
assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithSortByNameThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
List<User> usersSortByName = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
assertThat(usersSortByName.get(0).getName()).isEqualTo(USER_NAME_ADAM);
}
@Test(expected = PropertyReferenceException.class)
public void givenUsersInDBWhenFindAllSortWithFunctionThenThrowException() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllSortWithFunctionQueryAnnotationJPQLThenReturnUsersSorted() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.findAllUsers(new Sort("name"));
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
assertThat(usersSortByNameLength.get(0).getName()).isEqualTo(USER_NAME_ADAM);
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationJPQLThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
assertThat(usersPage.getContent().get(0).getName()).isEqualTo("SAMPLE1");
}
@Test
public void givenUsersInDBWhenFindAllWithPageRequestQueryAnnotationNativeThenReturnPageOfUsers() {
userRepository.save(new User(USER_NAME_ADAM, ACTIVE_STATUS));
userRepository.save(new User(USER_NAME_PETER, ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE2", INACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", INACTIVE_STATUS));
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
assertThat(usersSortByNameLength.getContent().get(0).getName()).isEqualTo("SAMPLE1");
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationJPQLThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@Test
@Transactional
public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() {
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE1", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE", ACTIVE_STATUS));
userRepository.save(new User("SAMPLE3", ACTIVE_STATUS));
userRepository.flush();
int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE");
assertThat(updatedUsersSize).isEqualTo(2);
}
@After

View File

@ -40,42 +40,5 @@
</dependency>
</dependencies>
</dependencyManagement>
<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

@ -40,40 +40,5 @@
</dependency>
</dependencies>
</dependencyManagement>
<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

@ -41,39 +41,4 @@
</dependencies>
</dependencyManagement>
<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

@ -60,42 +60,5 @@
</snapshots>
</repository>
</repositories>
<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

@ -10,5 +10,6 @@
- [Using Spring @Value with Defaults](http://www.baeldung.com/spring-value-defaults)
- [Groovy Bean Definitions](http://www.baeldung.com/spring-groovy-beans)
- [XML-Based Injection in Spring](http://www.baeldung.com/spring-xml-injection)
- [A Quick Guide to the Spring @Lazy Annotation] (http://www.baeldung.com/spring-lazy-annotation)
- [A Quick Guide to the Spring @Lazy Annotation](http://www.baeldung.com/spring-lazy-annotation)
- [Injecting Prototype Beans into a Singleton Instance in Spring](http://www.baeldung.com/spring-inject-prototype-bean-into-singleton)
- [How to Inject a Property Value Into a Class Not Managed by Spring?](http://www.baeldung.com/inject-properties-value-non-spring-class)

View File

@ -90,42 +90,7 @@
</plugins>
</build>
<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>
<properties>
<mockito.version>1.10.19</mockito.version>
<mockito.spring.boot.version>1.4.4.RELEASE</mockito.spring.boot.version>

View File

@ -66,39 +66,4 @@
</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

@ -138,43 +138,7 @@
</plugins>
</build>
<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>
<properties>
<!-- The main class to start by executing java -jar -->
<start-class>org.baeldung.boot.DemoApplication</start-class>

View File

@ -75,41 +75,6 @@
</plugins>
</build>
<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>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -8,8 +8,6 @@ import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
@ -18,7 +16,7 @@ import javax.ejb.Startup;
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class CountryStateBeanManagedBean implements CountryState {
private volatile Map<String, List<String>> countryStatesMap = new HashMap<String, List<String>>();
private final Map<String, List<String>> countryStatesMap = new HashMap<String, List<String>>();
@PostConstruct
public synchronized void initialize() {

View File

@ -131,39 +131,4 @@
</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

@ -55,26 +55,6 @@
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/*UnitTest.java</exclude>
</excludes>
<!-- Run only tests whose name end with "IntegrationTest" -->
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>unit</id>
<build>

View File

@ -185,41 +185,6 @@
</pluginManagement>
</build>
<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>
<properties>
<org.jooq.version>3.8.6</org.jooq.version>
<com.h2database.version>1.4.193</com.h2database.version>

View File

@ -30,41 +30,6 @@
</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>
<properties>
<mockito.version>1.10.19</mockito.version>
</properties>

View File

@ -199,38 +199,6 @@
</build>
<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>
<profile>
<id>live</id>

View File

@ -0,0 +1,17 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
@Configuration
public class CustomWebMvcConfigurationSupport extends WebMvcConfigurationSupport {
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
handlerMapping.setUseSuffixPatternMatch(false);
return handlerMapping;
}
}

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