Merge remote-tracking branch 'eugenp/master'
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
+39
@@ -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);
|
||||
}
|
||||
}
|
||||
+34
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+1
-35
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
+2
-1
@@ -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)
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+38
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+34
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -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;
|
||||
}
|
||||
}
|
||||
+16
@@ -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;
|
||||
}
|
||||
+41
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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("[email protected]"));
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+52
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user