Merge pull request #2 from eugenp/master

Pull from origin
This commit is contained in:
Mikhail Chugunov 2019-01-02 17:18:15 +03:00 committed by GitHub
commit 8d4badcea7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1707 changed files with 22651 additions and 6641 deletions

View File

@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip install: skip
script: travis_wait 60 mvn -q install -Pdefault-first,default-second script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
sudo: required sudo: required

View File

@ -28,14 +28,14 @@ public class Log {
System.out.println("Had " + count + " commits overall on current branch"); System.out.println("Had " + count + " commits overall on current branch");
logs = git.log() logs = git.log()
.add(repository.resolve("remotes/origin/testbranch")) .add(repository.resolve(git.getRepository().getFullBranch()))
.call(); .call();
count = 0; count = 0;
for (RevCommit rev : logs) { for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */); System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++; count++;
} }
System.out.println("Had " + count + " commits overall on test-branch"); System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log() logs = git.log()
.all() .all()

View File

@ -1,3 +1,5 @@
package com.baeldung.jgit;
import com.baeldung.jgit.helper.Helper; import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader; import org.eclipse.jgit.lib.ObjectReader;

48
akka-http/pom.xml Normal file
View File

@ -0,0 +1,48 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-http</artifactId>
<name>akka-http</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.12</artifactId>
<version>2.5.11</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-jackson_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-testkit_2.12</artifactId>
<version>${akka.http.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.akkahttp;
public class User {
private final Long id;
private final String name;
public User() {
this.name = "";
this.id = null;
}
public User(Long id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.akkahttp;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.japi.pf.FI;
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
class UserActor extends AbstractActor {
private UserService userService = new UserService();
static Props props() {
return Props.create(UserActor.class);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(CreateUserMessage.class, handleCreateUser())
.match(GetUserMessage.class, handleGetUser())
.build();
}
private FI.UnitApply<CreateUserMessage> handleCreateUser() {
return createUserMessageMessage -> {
userService.createUser(createUserMessageMessage.getUser());
sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser()
.getName())), getSelf());
};
}
private FI.UnitApply<GetUserMessage> handleGetUser() {
return getUserMessageMessage -> {
sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf());
};
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.akkahttp;
import java.io.Serializable;
public interface UserMessages {
class ActionPerformed implements Serializable {
private static final long serialVersionUID = 1L;
private final String description;
public ActionPerformed(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
class CreateUserMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final User user;
public CreateUserMessage(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
class GetUserMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final Long userId;
public GetUserMessage(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.akkahttp;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.http.javadsl.marshallers.jackson.Jackson;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.HttpApp;
import akka.http.javadsl.server.Route;
import akka.pattern.PatternsCS;
import akka.util.Timeout;
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
import scala.concurrent.duration.Duration;
import static akka.http.javadsl.server.PathMatchers.*;
class UserServer extends HttpApp {
private final ActorRef userActor;
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
UserServer(ActorRef userActor) {
this.userActor = userActor;
}
@Override
public Route routes() {
return path("users", this::postUser)
.orElse(path(segment("users").slash(longSegment()), id ->
route(getUser(id))));
}
private Route getUser(Long id) {
return get(() -> {
CompletionStage<Optional<User>> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout)
.thenApply(obj -> (Optional<User>) obj);
return onSuccess(() -> user, performed -> {
if (performed.isPresent())
return complete(StatusCodes.OK, performed.get(), Jackson.marshaller());
else
return complete(StatusCodes.NOT_FOUND);
});
});
}
private Route postUser() {
return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> {
CompletionStage<ActionPerformed> userCreated = PatternsCS.ask(userActor, new CreateUserMessage(user), timeout)
.thenApply(obj -> (ActionPerformed) obj);
return onSuccess(() -> userCreated, performed -> {
return complete(StatusCodes.CREATED, performed, Jackson.marshaller());
});
})));
}
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create("userServer");
ActorRef userActor = system.actorOf(UserActor.props(), "userActor");
UserServer server = new UserServer(userActor);
server.startServer("localhost", 8080, system);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.akkahttp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class UserService {
private final static List<User> users = new ArrayList<>();
static {
users.add(new User(1l, "Alice"));
users.add(new User(2l, "Bob"));
users.add(new User(3l, "Chris"));
users.add(new User(4l, "Dick"));
users.add(new User(5l, "Eve"));
users.add(new User(6l, "Finn"));
}
public Optional<User> getUser(Long id) {
return users.stream()
.filter(user -> user.getId()
.equals(id))
.findFirst();
}
public void createUser(User user) {
users.add(user);
}
public List<User> getUsers(){
return users;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.akkahttp;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.http.javadsl.model.ContentTypes;
import akka.http.javadsl.model.HttpEntities;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRoute;
import org.junit.Test;
public class UserServerUnitTest extends JUnitRouteTest {
ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor");
TestRoute appRoute = testRoute(new UserServer(userActorRef).routes());
@Test
public void whenRequest_thenActorResponds() {
appRoute.run(HttpRequest.GET("/users/1"))
.assertEntity(alice())
.assertStatusCode(200);
appRoute.run(HttpRequest.GET("/users/42"))
.assertStatusCode(404);
appRoute.run(HttpRequest.DELETE("/users/1"))
.assertStatusCode(200);
appRoute.run(HttpRequest.DELETE("/users/42"))
.assertStatusCode(200);
appRoute.run(HttpRequest.POST("/users")
.withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod())))
.assertStatusCode(201);
}
private String alice() {
return "{\"id\":1,\"name\":\"Alice\"}";
}
private String zaphod() {
return "{\"id\":42,\"name\":\"Zaphod\"}";
}
}

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-genetic</artifactId> <artifactId>algorithms-genetic</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>algorithms-genetic</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -61,4 +61,5 @@
<commons-codec.version>1.11</commons-codec.version> <commons-codec.version>1.11</commons-codec.version>
</properties> </properties>
</project> </project>

View File

@ -11,3 +11,5 @@
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms) - [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters) - [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element) - [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-miscellaneous-1</artifactId> <artifactId>algorithms-miscellaneous-1</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-1</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -17,6 +17,11 @@
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
<version>${commons-math3.version}</version> <version>${commons-math3.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
@ -73,6 +78,7 @@
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version> <org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version> <commons-codec.version>1.11</commons-codec.version>
<guava.version>25.1-jre</guava.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,63 @@
package com.baeldung.algorithms.factorial;
import java.math.BigInteger;
import java.util.stream.LongStream;
import org.apache.commons.math3.util.CombinatoricsUtils;
import com.google.common.math.BigIntegerMath;
public class Factorial {
public long factorialUsingForLoop(int n) {
long fact = 1;
for (int i = 2; i <= n; i++) {
fact = fact * i;
}
return fact;
}
public long factorialUsingStreams(int n) {
return LongStream.rangeClosed(1, n)
.reduce(1, (long x, long y) -> x * y);
}
public long factorialUsingRecursion(int n) {
if (n <= 2) {
return n;
}
return n * factorialUsingRecursion(n - 1);
}
private Long[] factorials = new Long[20];
public long factorialUsingMemoize(int n) {
if (factorials[n] != null) {
return factorials[n];
}
if (n <= 2) {
return n;
}
long nthValue = n * factorialUsingMemoize(n - 1);
factorials[n] = nthValue;
return nthValue;
}
public BigInteger factorialHavingLargeResult(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++)
result = result.multiply(BigInteger.valueOf(i));
return result;
}
public long factorialUsingApacheCommons(int n) {
return CombinatoricsUtils.factorial(n);
}
public BigInteger factorialUsingGuava(int n) {
return BigIntegerMath.factorial(n);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.string;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LongestSubstringNonRepeatingCharacters {
public static String getUniqueCharacterSubstringBruteForce(String input) {
String output = "";
for (int start = 0; start < input.length(); start++) {
Set<Character> visited = new HashSet<>();
int end = start;
for (; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.contains(currChar)) {
break;
} else {
visited.add(currChar);
}
}
if (output.length() < end - start + 1) {
output = input.substring(start, end);
}
}
return output;
}
public static String getUniqueCharacterSubstring(String input) {
Map<Character, Integer> visited = new HashMap<>();
String output = "";
for (int start = 0, end = 0; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.containsKey(currChar)) {
start = Math.max(visited.get(currChar) + 1, start);
}
if (output.length() < end - start + 1) {
output = input.substring(start, end + 1);
}
visited.put(currChar, end);
}
return output;
}
public static void main(String[] args) {
if(args.length > 0) {
System.out.println(getUniqueCharacterSubstring(args[0]));
} else {
System.err.println("This program expects command-line input. Please try again!");
}
}
}

View File

@ -0,0 +1,90 @@
package com.baeldung.algorithms.string;
import java.util.HashSet;
import java.util.Set;
public class SubstringPalindrome {
public Set<String> findAllPalindromesUsingCenter(String input) {
final Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
palindromes.addAll(findPalindromes(input, i, i + 1));
palindromes.addAll(findPalindromes(input, i, i));
}
return palindromes;
}
private Set<String> findPalindromes(String input, int low, int high) {
Set<String> result = new HashSet<>();
while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
result.add(input.substring(low, high + 1));
low--;
high++;
}
return result;
}
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
Set<String> palindromes = new HashSet<>();
if (input == null || input.isEmpty()) {
return palindromes;
}
if (input.length() == 1) {
palindromes.add(input);
return palindromes;
}
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++)
if (isPalindrome(input.substring(i, j))) {
palindromes.add(input.substring(i, j));
}
}
return palindromes;
}
private boolean isPalindrome(String input) {
StringBuilder plain = new StringBuilder(input);
StringBuilder reverse = plain.reverse();
return (reverse.toString()).equals(input);
}
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
Set<String> palindromes = new HashSet<>();
String formattedInput = "@" + input + "#";
char inputCharArr[] = formattedInput.toCharArray();
int max;
int radius[][] = new int[2][input.length() + 1];
for (int j = 0; j <= 1; j++) {
radius[j][0] = max = 0;
int i = 1;
while (i <= input.length()) {
palindromes.add(Character.toString(inputCharArr[i]));
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
max++;
radius[j][i] = max;
int k = 1;
while ((radius[j][i - k] != max - k) && (k < max)) {
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
k++;
}
max = Math.max(max - k, 0);
i += k;
}
}
for (int i = 1; i <= input.length(); i++) {
for (int j = 0; j <= 1; j++) {
for (max = radius[j][i]; max > 0; max--) {
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
}
}
}
return palindromes;
}
}

View File

@ -0,0 +1,72 @@
package com.baeldung.algorithms.factorial;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigInteger;
import org.junit.Before;
import org.junit.Test;
public class FactorialUnitTest {
Factorial factorial;
@Before
public void setup() {
factorial = new Factorial();
}
@Test
public void whenCalculatingFactorialUsingForLoop_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingStreams_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingRecursion_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingMemoize_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120);
n = 6;
assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720);
}
@Test
public void whenCalculatingFactorialHavingLargeResult_thenCorrect() {
int n = 22;
assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000"));
}
@Test
public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() {
int n = 5;
assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120);
}
@Test
public void whenCalculatingFactorialUsingGuava_thenCorrect() {
int n = 22;
assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000"));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
public class LongestSubstringNonRepeatingCharactersUnitTest {
@Test
void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstringBruteForce(""));
assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
}
@Test
void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
assertEquals("", getUniqueCharacterSubstring(""));
assertEquals("A", getUniqueCharacterSubstring("A"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.algorithms.string;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
public class SubstringPalindromeUnitTest {
private static final String INPUT_BUBBLE = "bubble";
private static final String INPUT_CIVIC = "civic";
private static final String INPUT_INDEED = "indeed";
private static final String INPUT_ABABAC = "ababac";
Set<String> EXPECTED_PALINDROME_BUBBLE = new HashSet<String>() {
{
add("b");
add("u");
add("l");
add("e");
add("bb");
add("bub");
}
};
Set<String> EXPECTED_PALINDROME_CIVIC = new HashSet<String>() {
{
add("civic");
add("ivi");
add("i");
add("c");
add("v");
}
};
Set<String> EXPECTED_PALINDROME_INDEED = new HashSet<String>() {
{
add("i");
add("n");
add("d");
add("e");
add("ee");
add("deed");
}
};
Set<String> EXPECTED_PALINDROME_ABABAC = new HashSet<String>() {
{
add("a");
add("b");
add("c");
add("aba");
add("bab");
add("ababa");
}
};
private SubstringPalindrome palindrome = new SubstringPalindrome();
@Test
public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
}
@Test
public void whenUsingCenterApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
}
@Test
public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
}
}

View File

@ -17,3 +17,4 @@
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred) - [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage) - [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings) - [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-miscellaneous-2</artifactId> <artifactId>algorithms-miscellaneous-2</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>algorithms-miscellaneous-2</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -33,6 +33,11 @@
<artifactId>jgrapht-core</artifactId> <artifactId>jgrapht-core</artifactId>
<version>${org.jgrapht.core.version}</version> <version>${org.jgrapht.core.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.jgrapht</groupId>
<artifactId>jgrapht-ext</artifactId>
<version>${org.jgrapht.ext.version}</version>
</dependency>
<dependency> <dependency>
<groupId>pl.allegro.finance</groupId> <groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId> <artifactId>tradukisto</artifactId>
@ -83,6 +88,7 @@
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version> <tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version> <org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version> <org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version> <commons-codec.version>1.11</commons-codec.version>
</properties> </properties>

View File

@ -0,0 +1,47 @@
package com.baeldung.jgrapht;
import static org.junit.Assert.assertTrue;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.jgrapht.ext.JGraphXAdapter;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.junit.Before;
import org.junit.Test;
import com.mxgraph.layout.mxCircleLayout;
import com.mxgraph.layout.mxIGraphLayout;
import com.mxgraph.util.mxCellRenderer;
public class GraphImageGenerationUnitTest {
static DefaultDirectedGraph<String, DefaultEdge> g;
@Before
public void createGraph() throws IOException {
File imgFile = new File("src/test/resources/graph.png");
imgFile.createNewFile();
g = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String x1 = "x1";
String x2 = "x2";
String x3 = "x3";
g.addVertex(x1);
g.addVertex(x2);
g.addVertex(x3);
g.addEdge(x1, x2);
g.addEdge(x2, x3);
g.addEdge(x3, x1);
}
@Test
public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
JGraphXAdapter<String, DefaultEdge> graphAdapter = new JGraphXAdapter<String, DefaultEdge>(g);
mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
layout.execute(graphAdapter.getDefaultParent());
File imgFile = new File("src/test/resources/graph.png");
BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
ImageIO.write(image, "PNG", imgFile);
assertTrue(imgFile.exists());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>algorithms-sorting</artifactId> <artifactId>algorithms-sorting</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>algorithms-sorting</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -34,7 +34,7 @@ public class MergeSort {
while (i < left && j < right) { while (i < left && j < right) {
if (l[i] < r[j]) if (l[i] <= r[j])
a[k++] = l[i++]; a[k++] = l[i++];
else else
a[k++] = r[j++]; a[k++] = r[j++];

View File

@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>annotation-processing</artifactId> <artifactId>annotation-processing</artifactId>
<name>annotation-processing</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>annotation-user</artifactId> <artifactId>annotation-user</artifactId>
<name>annotation-user</name>
<parent> <parent>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>

View File

@ -4,6 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>annotations</name>
<parent> <parent>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>

View File

@ -3,10 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-avro</artifactId> <artifactId>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>Apache Avro</name> <name>apache-avro</name>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -4,6 +4,7 @@
<groupId>apache-bval</groupId> <groupId>apache-bval</groupId>
<artifactId>apache-bval</artifactId> <artifactId>apache-bval</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-bval</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -4,6 +4,7 @@
<artifactId>apache-curator</artifactId> <artifactId>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>apache-curator</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -58,7 +59,7 @@
<properties> <properties>
<curator.version>4.0.1</curator.version> <curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version> <zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.4</jackson-databind.version> <jackson-databind.version>2.9.7</jackson-databind.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>

View File

@ -2,6 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cxf-aegis</artifactId> <artifactId>cxf-aegis</artifactId>
<name>cxf-aegis</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -4,6 +4,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cxf-introduction</artifactId> <artifactId>cxf-introduction</artifactId>
<name>cxf-introduction</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -4,6 +4,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cxf-jaxrs-implementation</artifactId> <artifactId>cxf-jaxrs-implementation</artifactId>
<name>cxf-jaxrs-implementation</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -3,6 +3,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cxf-spring</artifactId> <artifactId>cxf-spring</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>cxf-spring</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId> <artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-cxf</name>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>

View File

@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>sse-jaxrs</artifactId> <artifactId>sse-jaxrs</artifactId>
<name>sse-jaxrs</name>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>

View File

@ -3,6 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>sse-jaxrs-client</artifactId>
<name>sse-jaxrs-client</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -10,8 +12,6 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>sse-jaxrs-client</artifactId>
<properties> <properties>
<cxf-version>3.2.0</cxf-version> <cxf-version>3.2.0</cxf-version>
</properties> </properties>
@ -21,7 +21,6 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions> <executions>
<execution> <execution>
<id>singleEvent</id> <id>singleEvent</id>

View File

@ -3,6 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>sse-jaxrs-server</artifactId>
<name>sse-jaxrs-server</name>
<packaging>war</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -10,9 +13,6 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<artifactId>sse-jaxrs-server</artifactId>
<packaging>war</packaging>
<properties> <properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version> <liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml> <failOnMissingWebXml>false</failOnMissingWebXml>

View File

@ -3,10 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-geode</artifactId> <artifactId>apache-geode</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>apache-geode</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -4,6 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apache-opennlp</artifactId> <artifactId>apache-opennlp</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>apache-opennlp</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-poi</artifactId> <artifactId>apache-poi</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-poi</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -3,8 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.pulsar</groupId> <groupId>com.baeldung.pulsar</groupId>
<artifactId>pulsar-java</artifactId> <artifactId>apache-pulsar</artifactId>
<version>0.0.1</version> <version>0.0.1</version>
<name>apache-pulsar</name>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -5,6 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apache-shiro</artifactId> <artifactId>apache-shiro</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>apache-shiro</name>
<parent> <parent>
<artifactId>parent-boot-1</artifactId> <artifactId>parent-boot-1</artifactId>

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-thrift</artifactId> <artifactId>apache-thrift</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-thrift</name>
<packaging>pom</packaging> <packaging>pom</packaging>
<parent> <parent>

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-tika</artifactId> <artifactId>apache-tika</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-tika</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -1,9 +1,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-zookeeper</artifactId> <artifactId>apache-zookeeper</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>apache-zookeeper</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>

View File

@ -5,6 +5,7 @@
<groupId>com.baeldung.examples</groupId> <groupId>com.baeldung.examples</groupId>
<artifactId>asm</artifactId> <artifactId>asm</artifactId>
<version>1.0</version> <version>1.0</version>
<name>asm</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>

View File

@ -4,6 +4,7 @@
<groupId>com.atomix.io</groupId> <groupId>com.atomix.io</groupId>
<artifactId>atomix</artifactId> <artifactId>atomix</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>atomix</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>axon</artifactId> <artifactId>axon</artifactId>
<name>axon</name>
<parent> <parent>
<artifactId>parent-modules</artifactId> <artifactId>parent-modules</artifactId>

View File

@ -3,8 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd "> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>cas-server</artifactId> <artifactId>cas-server</artifactId>
<packaging>war</packaging>
<version>1.0</version> <version>1.0</version>
<name>cas-server</name>
<packaging>war</packaging>
<parent> <parent>
<artifactId>parent-boot-1</artifactId> <artifactId>parent-boot-1</artifactId>

View File

@ -1,3 +1,5 @@
### Relevant Articles: ### Relevant Articles:
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj) - [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
- [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi) - [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi)
- [Introduction to the Event Notification Model in CDI 2.0](https://www.baeldung.com/cdi-event-notification)

View File

@ -2,9 +2,9 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>cdi</artifactId> <artifactId>cdi</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>cdi</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -14,6 +14,16 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>${cdi-api.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>${weld-se-core.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.hamcrest</groupId> <groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId> <artifactId>hamcrest-core</artifactId>
@ -42,11 +52,6 @@
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version> <version>${aspectjweaver.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>${weld-se-core.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>
@ -54,13 +59,13 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<aspectjweaver.version>1.8.9</aspectjweaver.version> <cdi-api.version>2.0.SP1</cdi-api.version>
<weld-se-core.version>2.4.1.Final</weld-se-core.version> <weld-se-core.version>3.0.5.Final</weld-se-core.version>
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<hamcrest-core.version>1.3</hamcrest-core.version> <hamcrest-core.version>1.3</hamcrest-core.version>
<assertj-core.version>3.10.0</assertj-core.version> <assertj-core.version>3.10.0</assertj-core.version>
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,15 @@
package com.baeldung.cdi.cdi2observers.application;
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
public class BootstrappingApplication {
public static void main(String... args) {
SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance();
try (SeContainer container = containerInitializer.initialize()) {
container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!"));
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.cdi.cdi2observers.events;
public class ExampleEvent {
private final String eventMessage;
public ExampleEvent(String eventMessage) {
this.eventMessage = eventMessage;
}
public String getEventMessage() {
return eventMessage;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.cdi.cdi2observers.events;
import javax.enterprise.event.Event;
import javax.inject.Inject;
public class ExampleEventSource {
@Inject
Event<ExampleEvent> exampleEvent;
public void fireEvent() {
exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.cdi.cdi2observers.observers;
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
import javax.annotation.Priority;
import javax.enterprise.event.Observes;
public class AnotherExampleEventObserver {
public String onEvent(@Observes @Priority(2) ExampleEvent event) {
return event.getEventMessage();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.cdi.cdi2observers.observers;
import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
import com.baeldung.cdi.cdi2observers.services.TextService;
import javax.annotation.Priority;
import javax.enterprise.event.Observes;
public class ExampleEventObserver {
public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
return textService.parseText(event.getEventMessage());
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.cdi.cdi2observers.services;
public class TextService {
public String parseText(String text) {
return text.toUpperCase();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.cdi.cdi2observers.tests;
import com.baeldung.cdi.cdi2observers.services.TextService;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TextServiceUnitTest {
@Test
public void givenTextServiceInstance_whenCalledparseText_thenCorrect() {
TextService textService = new TextService();
assertThat(textService.parseText("Baeldung")).isEqualTo("BAELDUNG");
}
}

View File

@ -4,6 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>core-groovy</artifactId> <artifactId>core-groovy</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>core-groovy</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<parent> <parent>

View File

@ -4,3 +4,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference) - [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview) - [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another) - [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Deep Dive Into the New Java JIT Compiler Graal](https://www.baeldung.com/graal-java-jit-compiler)

5
core-java-11/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant articles
- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)

View File

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

View File

@ -0,0 +1,12 @@
#!/usr/local/bin/java --source 11
import java.util.Arrays;
public class Addition
{
public static void main(String[] args) {
System.out.println(Arrays.stream(args)
.mapToInt(Integer::parseInt)
.sum());
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NewStringAPIUnitTest {
@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
String output = "La ".repeat(2) + "Land";
is(output).equals("La La Land");
}
@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
is("\n\t hello \u2005".strip()).equals("hello");
}
@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
is("\n\t hello \u2005".trim()).equals("hello \u2005");
}
@Test
public void whenBlankString_thenReturnTrue() {
assertTrue("\n\t\u2005 ".isBlank());
}
@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
String multilineStr = "This is\n \n a multiline\n string.";
long lineCount = multilineStr.lines()
.filter(String::isBlank)
.count();
is(lineCount).equals(3L);
}
}

View File

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

View File

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

View File

@ -15,7 +15,6 @@
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing) - [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional) - [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java) - [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods) - [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency) - [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
@ -33,3 +32,8 @@
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance) - [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects) - [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic) - [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
- [Java @Override Annotation](https://www.baeldung.com/java-override)
- [Java @SuppressWarnings Annotation](https://www.baeldung.com/java-suppresswarnings)
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)

View File

@ -104,6 +104,24 @@
<artifactId>aspectjweaver</artifactId> <artifactId>aspectjweaver</artifactId>
<version>${asspectj.version}</version> <version>${asspectj.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -119,7 +137,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version> <version>${maven-compiler-plugin.version}</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
@ -142,6 +160,16 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<argLine>
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
</argLine>
<disableXmlReport>true</disableXmlReport>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
@ -159,9 +187,14 @@
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<asspectj.version>1.8.9</asspectj.version> <asspectj.version>1.8.9</asspectj.version>
<powermock.version>2.0.0-RC.4</powermock.version>
<jmockit.version>1.44</jmockit.version>
<avaitility.version>1.7.0</avaitility.version> <avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator.version>1.19</jmh-generator.version> <jmh-generator.version>1.19</jmh-generator.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version> <spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<!-- plugins -->
<maven-compiler-plugin.version>3.8.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.22.1</maven-surefire-plugin.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,22 @@
package com.baeldung.interfaces;
public interface Electronic {
//Constant variable
public static final String LED = "LED";
//Abstract method
public int getElectricityUse();
// Static method
public static boolean isEnergyEfficient(String electtronicType) {
if (electtronicType.equals(LED)) {
return true;
}
return false;
}
//Default method
public default void printDescription() {
System.out.println("Electronic Description");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.interfaces;
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.interfaces;
import java.util.Comparator;
public class EmployeeSalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee employeeA, Employee employeeB) {
if(employeeA.getSalary() < employeeB.getSalary()){
return -1;
}else if(employeeA.getSalary() > employeeB.getSalary()){
return 1;
}else{
return 0;
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces;
public interface HasColor {
public String getColor();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.multiinheritance.Transform;
public class Motorcycle implements Transform {
@Override
public void transform() {
// Implementation
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.interfaces;
public class Truck extends Vehicle {
@Override
public void transform() {
// implementation
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.multiinheritance.Transform;
public abstract class Vehicle implements Transform {
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces.multiinheritance;
public class Car implements Fly, Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces.multiinheritance;
public abstract interface Fly{
void fly();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
default void printSpecs(){
System.out.println("Transform Specification");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces.multiinheritance;
public class Vehicle implements Fly, Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
private double radius;
public Circle(double radius){
this.radius = radius;
}
@Override
public String name() {
return "Circle";
}
@Override
public double area() {
return Math.PI * (radius * radius);
}
@Override
public String getColor() {
return "green";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
public class DisplayShape {
private ArrayList<Shape> shapes;
public ArrayList<Shape> getShapes() {
return shapes;
}
public DisplayShape() {
shapes = new ArrayList<>();
}
public void add(Shape shape) {
shapes.add(shape);
}
public void display() {
for (Shape shape : shapes) {
System.out.println(shape.name() + " area: " + shape.area());
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.function.Predicate;
public class FunctionalMain {
public static void main(String[] args) {
Shape circleShape = new Circle(2);
Shape squareShape = new Square(2);
DisplayShape DisplayShape = new DisplayShape();
DisplayShape.add(circleShape);
DisplayShape.add(squareShape);
Predicate<Shape> checkArea = (shape) -> shape.area() < 5;
for (Shape shape : DisplayShape.getShapes()) {
if (checkArea.test(shape)) {
System.out.println(shape.name() + " " + shape.area());
}
}
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.interfaces.polymorphysim;
public class MainPolymorphic {
public static void main(String[] args){
Shape circleShape = new Circle(2);
Shape squareShape = new Square(2);
DisplayShape displayShape = new DisplayShape();
displayShape.add(circleShape);
displayShape.add(squareShape);
displayShape.display();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
import com.baeldung.interfaces.HasColor;
public interface Shape extends HasColor {
public abstract String name();
public abstract double area();
}

View File

@ -0,0 +1,25 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
private double width;
public Square(double width) {
this.width = width;
}
@Override
public String name() {
return "Square";
}
@Override
public double area() {
return width * width;
}
@Override
public String getColor() {
return "red";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.polymorphysim.Circle;
import com.baeldung.interfaces.polymorphysim.Shape;
import com.baeldung.interfaces.polymorphysim.Square;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class PolymorphysimUnitTest {
@Test
public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){
double expectedArea = 12.566370614359172;
Shape circle = new Circle(2);
double actualArea = circle.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
@Test
public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){
double expectedArea = 4;
Shape square = new Square(2);
double actualArea = square.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
}

View File

@ -0,0 +1,131 @@
package com.baeldung.java8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Test;
public class Java8PredicateChainUnitTest {
private List<String> names = Arrays.asList("Adam", "Alexander", "John", "Tom");
@Test
public void whenFilterList_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
@Test
public void whenFilterListWithMultipleFilters_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A"))
.filter(name -> name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithComplexPredicate_thenSuccess() {
List<String> result = names.stream()
.filter(name -> name.startsWith("A") && name.length() < 5)
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesInline_thenSuccess() {
List<String> result = names.stream()
.filter(((Predicate<String>) name -> name.startsWith("A")).and(name -> name.length() < 5))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingAnd_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("A");
Predicate<String> predicate2 = str -> str.length() < 5;
List<String> result = names.stream()
.filter(predicate1.and(predicate2))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Adam"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOr_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("John", "Tom"));
}
@Test
public void whenFilterListWithCombinedPredicatesUsingOrAndNegate_thenSuccess() {
Predicate<String> predicate1 = str -> str.startsWith("J");
Predicate<String> predicate2 = str -> str.length() < 4;
List<String> result = names.stream()
.filter(predicate1.or(predicate2.negate()))
.collect(Collectors.toList());
assertEquals(3, result.size());
assertThat(result, contains("Adam", "Alexander", "John"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingAnd_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> true, Predicate::and))
.collect(Collectors.toList());
assertEquals(1, result.size());
assertThat(result, contains("Alexander"));
}
@Test
public void whenFilterListWithCollectionOfPredicatesUsingOr_thenSuccess() {
List<Predicate<String>> allPredicates = new ArrayList<Predicate<String>>();
allPredicates.add(str -> str.startsWith("A"));
allPredicates.add(str -> str.contains("d"));
allPredicates.add(str -> str.length() > 4);
List<String> result = names.stream()
.filter(allPredicates.stream()
.reduce(x -> false, Predicate::or))
.collect(Collectors.toList());
assertEquals(2, result.size());
assertThat(result, contains("Adam", "Alexander"));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.time;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LocalDateTimeUnitTest {
@Test
public void givenLocalDateTimeMock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC"));
LocalDateTime dateTime = LocalDateTime.now(clock);
mockStatic(LocalDateTime.class);
when(LocalDateTime.now()).thenReturn(dateTime);
String dateTimeExpected = "2014-12-22T10:15:30";
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
@Test
public void givenFixedClock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-22T10:15:30.00Z"), ZoneId.of("UTC"));
String dateTimeExpected = "2014-12-22T10:15:30";
LocalDateTime dateTime = LocalDateTime.now(clock);
assertThat(dateTime).isEqualTo(dateTimeExpected);
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.time;
import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import static org.assertj.core.api.Assertions.assertThat;
public class LocalDateTimeWithJMockUnitTest {
@Test
public void givenLocalDateTimeWithJMock_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-21T10:15:30.00Z"), ZoneId.of("UTC"));
new MockUp<LocalDateTime>() {
@Mock
public LocalDateTime now() {
return LocalDateTime.now(clock);
}
};
String dateTimeExpected = "2014-12-21T10:15:30";
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
@Test
public void givenLocalDateTimeWithExpectations_whenNow_thenGetFixedLocalDateTime() {
Clock clock = Clock.fixed(Instant.parse("2014-12-23T10:15:30.00Z"), ZoneId.of("UTC"));
LocalDateTime dateTimeExpected = LocalDateTime.now(clock);
new Expectations(LocalDateTime.class) {
{
LocalDateTime.now();
result = dateTimeExpected;
}
};
LocalDateTime now = LocalDateTime.now();
assertThat(now).isEqualTo(dateTimeExpected);
}
}

View File

@ -9,7 +9,6 @@
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods) - [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors) - [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture) - [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api) - [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api) - [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)

View File

@ -1,7 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-9</artifactId> <artifactId>core-java-9</artifactId>
<version>0.2-SNAPSHOT</version> <version>0.2-SNAPSHOT</version>
<name>core-java-9</name> <name>core-java-9</name>

View File

@ -12,4 +12,4 @@
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide) - [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array) - [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations) - [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)

View File

@ -7,6 +7,14 @@ public class Employee implements Serializable {
private int id; private int id;
private String name; private String name;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { public int getId() {
return id; return id;
} }

View File

@ -0,0 +1,90 @@
package com.baeldung.sort;
import com.baeldung.arraycopy.model.Employee;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.junit.Assert.assertArrayEquals;
public class ArraySortUnitTest {
private Employee[] employees;
private int[] numbers;
private String[] strings;
private Employee john = new Employee(6, "John");
private Employee mary = new Employee(3, "Mary");
private Employee david = new Employee(4, "David");
@Before
public void setup() {
createEmployeesArray();
createNumbersArray();
createStringArray();
}
private void createEmployeesArray() {
employees = new Employee[]{john, mary, david};
}
private void createNumbersArray() {
numbers = new int[]{-8, 7, 5, 9, 10, -2, 3};
}
private void createStringArray() {
strings = new String[]{"learning", "java", "with", "baeldung"};
}
@Test
public void givenIntArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(numbers);
assertArrayEquals(new int[]{-8, -2, 3, 5, 7, 9, 10}, numbers);
}
@Test
public void givenIntArray_whenSortingDescending_thenCorrectlySorted() {
numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
assertArrayEquals(new int[]{10, 9, 7, 5, 3, -2, -8}, numbers);
}
@Test
public void givenStringArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(strings);
assertArrayEquals(new String[]{"baeldung", "java", "learning", "with"}, strings);
}
@Test
public void givenStringArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(strings, Comparator.reverseOrder());
assertArrayEquals(new String[]{"with", "learning", "java", "baeldung"}, strings);
}
@Test
public void givenObjectArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
@Test
public void givenObjectArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed());
assertArrayEquals(new Employee[]{mary, john, david}, employees);
}
@Test
public void givenObjectArray_whenSortingMultipleAttributesAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
}

View File

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

View File

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

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