Merge remote-tracking branch 'origin/master'

This commit is contained in:
alexandru.borza
2023-05-12 20:19:50 +03:00
2825 changed files with 38918 additions and 8860 deletions
-1
View File
@@ -4,7 +4,6 @@
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-10</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-10</name>
<packaging>jar</packaging>
-1
View File
@@ -4,7 +4,6 @@
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-11-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-11-2</name>
<packaging>jar</packaging>
+1 -2
View File
@@ -4,7 +4,6 @@
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-11-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-11-3</name>
<packaging>jar</packaging>
@@ -14,7 +13,7 @@
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
-2
View File
@@ -4,10 +4,8 @@
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-11</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-11</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
-2
View File
@@ -4,10 +4,8 @@
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-12</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-12</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
-3
View File
@@ -3,12 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-13</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-13</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
+1
View File
@@ -13,3 +13,4 @@ This module contains articles about Java 14.
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
- [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok)
- [Record vs. Final Class in Java](https://www.baeldung.com/java-record-vs-final-class)
- [Custom Constructor in Java Records](https://www.baeldung.com/java-records-custom-constructor)
-1
View File
@@ -6,7 +6,6 @@
<artifactId>core-java-14</artifactId>
<name>core-java-14</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
@@ -0,0 +1,61 @@
package org.example;
import java.util.Objects;
public class StudentClassic {
private String name;
private int rollNo;
private int marks;
public StudentClassic(String name, int rollNo, int marks) {
this.name = name;
this.rollNo = rollNo;
this.marks = marks;
}
public String getName() {
return name;
}
public int getRollNo() {
return rollNo;
}
public int getMarks() {
return marks;
}
public void setName(String name) {
this.name = name;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public void setMarks(int marks) {
this.marks = marks;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StudentClassic that = (StudentClassic) o;
return rollNo == that.rollNo && marks == that.marks && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, rollNo, marks);
}
@Override
public String toString() {
return "StudentClassic{" +
"name='" + name + '\'' +
", rollNo=" + rollNo +
", marks=" + marks +
'}';
}
}
@@ -0,0 +1,19 @@
package org.example;
import java.util.Comparator;
import java.util.List;
public record StudentRecord(String name, int rollNo, int marks) {
public StudentRecord(String name){
this(name, 0,0);
}
public StudentRecord {
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Marks should be between 0 and 100.");
}
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
}
}
@@ -0,0 +1,22 @@
package org.example;
record StudentRecordV2(String name, int rollNo, int marks, char grade) {
public StudentRecordV2(String name, int rollNo, int marks) {
this(name, rollNo, marks, calculateGrade(marks));
}
private static char calculateGrade(int marks) {
if (marks >= 90) {
return 'A';
} else if (marks >= 80) {
return 'B';
} else if (marks >= 70) {
return 'C';
} else if (marks >= 60) {
return 'D';
} else {
return 'F';
}
}
}
@@ -0,0 +1,11 @@
package org.example;
import java.util.UUID;
record StudentRecordV3(String name, int rollNo, int marks, String id) {
public StudentRecordV3(String name, int rollNo, int marks) {
this(name, rollNo, marks, UUID.randomUUID().toString());
}
}
@@ -0,0 +1,37 @@
import org.example.StudentRecord;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class StudentRecordJUnitTest {
@Test
public void givenStudentRecordData_whenCreated_thenStudentPropertiesMatch() {
StudentRecord s1 = new StudentRecord("John", 1, 90);
StudentRecord s2 = new StudentRecord("Jane", 2, 80);
assertEquals("John", s1.name());
assertEquals(1, s1.rollNo());
assertEquals(90, s1.marks());
assertEquals("Jane", s2.name());
assertEquals(2, s2.rollNo());
assertEquals(80, s2.marks());
}
@Test
public void givenStudentRecordsList_whenSortingDataWithName_thenStudentsSorted(){
List<StudentRecord> studentRecords = List.of(
new StudentRecord("Dana", 1, 85),
new StudentRecord("Jim", 2, 90),
new StudentRecord("Jane", 3, 80)
);
List<StudentRecord> mutableStudentRecords = new ArrayList<>(studentRecords);
mutableStudentRecords.sort(Comparator.comparing(StudentRecord::name));
List<StudentRecord> sortedStudentRecords = List.copyOf(mutableStudentRecords);
assertEquals("Jane", sortedStudentRecords.get(1).name());
}
}
-1
View File
@@ -6,7 +6,6 @@
<artifactId>core-java-15</artifactId>
<name>core-java-15</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
-2
View File
@@ -4,10 +4,8 @@
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-16</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-16</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
+1
View File
@@ -6,3 +6,4 @@
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)
- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
-2
View File
@@ -4,10 +4,8 @@
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-17</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-17</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
<groupId>com.baeldung</groupId>
+1
View File
@@ -1,3 +1,4 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
+11 -9
View File
@@ -1,21 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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-19</artifactId>
<name>core-java-19</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>core-java-19</artifactId>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
@@ -30,4 +26,10 @@
</plugins>
</build>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
@@ -0,0 +1,20 @@
package com.baeldung.highcpu;
import java.util.LinkedList;
import java.util.List;
import java.util.function.IntUnaryOperator;
import java.util.stream.IntStream;
public class Application {
static List<Integer> generateList() {
return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
}
public static void main(String[] args) {
List<Integer> list = generateList();
long start = System.nanoTime();
int value = list.get(9500000);
System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
}
}
+2
View File
@@ -0,0 +1,2 @@
## Relevant Articles
- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
+65
View File
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>core-java-20</artifactId>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>20</source>
<target>20</target>
<compilerArgs>
<arg>--enable-preview</arg>
<arg>--add-modules=jdk.incubator.concurrent</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview --add-modules=jdk.incubator.concurrent</argLine>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,33 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
public class Controller {
private final Service service = new Service();
public void processRequest(HttpServletRequest request, HttpServletResponse response, User loggedInUser) {
Optional<Data> data = service.getData(request, loggedInUser);
if (data.isPresent()) {
try {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.print(data.get());
out.flush();
response.setStatus(200);
} catch (IOException e) {
response.setStatus(500);
}
} else {
response.setStatus(400);
}
}
}
@@ -0,0 +1,16 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id, User user) {
return user.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}
@@ -0,0 +1,42 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.*;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
private final Controller controller = new Controller();
private final ExecutorService executor = Executors.newFixedThreadPool(5);
public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
Future<?> future = executor.submit(() ->
controller.processRequest(request, response, user.get()));
future.get();
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}
@@ -0,0 +1,18 @@
package com.baeldung.scopedvalues.classic;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class Service {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request, User loggedInUser) {
String id = request.getParameter("data_id");
return repository.getData(id, loggedInUser);
}
}
@@ -0,0 +1,3 @@
package com.baeldung.scopedvalues.data;
public record Data(String id, String title, String description) {}
@@ -0,0 +1,3 @@
package com.baeldung.scopedvalues.data;
public record User(String id, String name, String password, boolean isAdmin) {}
@@ -0,0 +1,37 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
public class Controller {
private final Service internalService = new Service();
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
Optional<Data> data = internalService.getData(request);
ScopedValue.where(Server.LOGGED_IN_USER, null)
.run(internalService::extractData);
if (data.isPresent()) {
try {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.print(data.get());
out.flush();
response.setStatus(200);
} catch (IOException e) {
response.setStatus(500);
}
} else {
response.setStatus(400);
}
}
}
@@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id) {
User loggedInUser = Server.LOGGED_IN_USER.get();
return loggedInUser.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}
@@ -0,0 +1,41 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.util.List;
import java.util.Optional;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
private final Controller controller = new Controller();
public void serve(HttpServletRequest request, HttpServletResponse response) {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
ScopedValue.where(LOGGED_IN_USER, user.get())
.run(() -> controller.processRequest(request, response));
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}
@@ -0,0 +1,23 @@
package com.baeldung.scopedvalues.scoped;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class Service {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request) {
String id = request.getParameter("data_id");
return repository.getData(id);
}
public void extractData() {
User loggedInUser = Server.LOGGED_IN_USER.get();
assert loggedInUser == null;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.StructuredTaskScope;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class Controller {
private final InternalService internalService = new InternalService();
private final ExternalService externalService = new ExternalService();
public void processRequest(HttpServletRequest request, HttpServletResponse response) {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<Optional<Data>> internalData = scope.fork(() -> internalService.getData(request));
Future<String> externalData = scope.fork(externalService::getData);
try {
scope.join();
scope.throwIfFailed();
Optional<Data> data = internalData.resultNow();
if (data.isPresent()) {
PrintWriter out = response.getWriter();
response.setContentType("application/json");
out.println(data.get());
out.print(externalData.resultNow());
out.flush();
response.setStatus(200);
} else {
response.setStatus(400);
}
} catch (InterruptedException | ExecutionException | IOException e) {
response.setStatus(500);
}
}
}
}
@@ -0,0 +1,9 @@
package com.baeldung.scopedvalues.scoped.inheriting;
public class ExternalService {
public String getData() {
return "External data";
}
}
@@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Optional;
public class InternalService {
private final Repository repository = new Repository();
public Optional<Data> getData(HttpServletRequest request) {
String id = request.getParameter("data_id");
return repository.getData(id);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.Data;
import com.baeldung.scopedvalues.data.User;
import java.util.Optional;
public class Repository {
public Optional<Data> getData(String id) {
User loggedInUser = Server.LOGGED_IN_USER.get();
return loggedInUser.isAdmin()
? Optional.of(new Data(id, "Title 1", "Description 1"))
: Optional.empty();
}
}
@@ -0,0 +1,41 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import com.baeldung.scopedvalues.data.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdk.incubator.concurrent.ScopedValue;
import java.util.List;
import java.util.Optional;
public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
public final static ScopedValue<User> LOGGED_IN_USER = ScopedValue.newInstance();
private final Controller controller = new Controller();
public void serve(HttpServletRequest request, HttpServletResponse response) {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
ScopedValue.where(LOGGED_IN_USER, user.get())
.run(() -> controller.processRequest(request, response));
} else {
response.setStatus(401);
}
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
}
@@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.classic;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.ExecutionException;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws InterruptedException, IOException, ExecutionException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws InterruptedException, ExecutionException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}
@@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.scoped;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}
@@ -0,0 +1,52 @@
package com.baeldung.scopedvalues.scoped.inheriting;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class ServerUnitTest {
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private final StringWriter writer = new StringWriter();
private final Server server = new Server();
@Test
void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("admin");
when(request.getParameter("user_pw")).thenReturn("123456");
when(request.getParameter("data_id")).thenReturn("1");
when(response.getWriter()).thenReturn(new PrintWriter(writer));
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]\nExternal data");
}
@Test
void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
when(request.getParameter("user_name")).thenReturn("user");
when(request.getParameter("user_pw")).thenReturn("123456");
server.serve(request, response);
assertThat(writer.toString()).isEqualTo("");
}
}
@@ -10,4 +10,7 @@ This module contains articles about Java 8 core features
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array)
- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
- [Java Helper vs. Utility Classes](https://www.baeldung.com/java-helper-vs-utility-classes)
- [[<-- Prev]](/core-java-modules/core-java-8)
-1
View File
@@ -4,7 +4,6 @@
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-8-2</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8-2</name>
<packaging>jar</packaging>
@@ -0,0 +1,40 @@
package com.baeldung.helpervsutilityclasses;
class MyHelperClass {
public double discount;
public MyHelperClass(double discount) {
if (discount > 0 && discount < 1) {
this.discount = discount;
}
}
public double discountedPrice(double price) {
return price - (price * discount);
}
public static int getMaxNumber(int[] numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Ensure array is not empty");
}
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
public static int getMinNumber(int[] numbers) {
if (numbers.length == 0) {
throw new IllegalArgumentException("Ensure array is not empty");
}
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
return min;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.helpervsutilityclasses;
public final class MyUtilityClass {
private MyUtilityClass(){}
public static String returnUpperCase(String stringInput) {
return stringInput.toUpperCase();
}
public static String returnLowerCase(String stringInput) {
return stringInput.toLowerCase();
}
public static String[] splitStringInput(String stringInput, String delimiter) {
return stringInput.split(delimiter);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.helpervsutilityclasses;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyHelperClassUnitTest {
@Test
void whenCreatingHelperObject_thenHelperObjectShouldBeCreated() {
MyHelperClass myHelperClassObject = new MyHelperClass(0.10);
int[] numberArray = {15, 23, 66, 3, 51, 79};
assertNotNull(myHelperClassObject);
assertEquals(90, myHelperClassObject.discountedPrice(100.00));
assertEquals( 79, MyHelperClass.getMaxNumber(numberArray));
assertEquals(3, MyHelperClass.getMinNumber(numberArray));
}
}
@@ -0,0 +1,15 @@
package com.baeldung.helpervsutilityclasses;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyUtilityClassUnitTest {
@Test
void whenUsingUtilityMethods_thenAccessMethodsViaClassName(){
assertEquals( "INIUBONG", MyUtilityClass.returnUpperCase("iniubong"));
assertEquals("accra", MyUtilityClass.returnLowerCase("AcCrA"));
}
}
@@ -2,4 +2,5 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
@@ -4,7 +4,6 @@
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-8-datetime-2</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime-2</name>
<packaging>jar</packaging>
@@ -0,0 +1,20 @@
package com.baeldung.parsingDates;
import java.util.Arrays;
import java.util.List;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
public class SimpleDateTimeFormat {
public static LocalDate parseDate(String date) {
List<String> patternList = Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd");
for (String pattern : patternList) {
try {
return DateTimeFormat.forPattern(pattern).parseLocalDate(date);
} catch (IllegalArgumentException e) {
}
}
return null;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.parsingDates;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
public class SimpleDateTimeFormater {
public static LocalDate parseDate(String date) {
DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("[MM/dd/yyyy]" + "[dd-MM-yyyy]" + "[yyyy-MM-dd]"));
DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
return LocalDate.parse(date, dateTimeFormatter);
}
}
@@ -0,0 +1,18 @@
package com.baeldung.parsingDates;
import java.text.ParseException;
import java.util.Date;
import org.apache.commons.lang3.time.DateUtils;
public class SimpleDateUtils {
public static Date parseDate(String date) {
try {
return DateUtils.parseDateStrictly(date,
new String[]{"yyyy/MM/dd", "dd/MM/yyyy", "yyyy-MM-dd"});
} catch (ParseException ex) {
return null;
}
}
}
@@ -0,0 +1,19 @@
package com.baeldung.parsingDates;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class SimpleParseDate {
public Date parseDate(String dateString, List<String> formatStrings) {
for (String formatString : formatStrings) {
try {
return new SimpleDateFormat(formatString).parse(dateString);
} catch (ParseException e) {
}
}
return null;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.parsingDates;
import com.baeldung.parsingDates.SimpleDateTimeFormat;
import com.baeldung.parsingDates.SimpleDateTimeFormater;
import com.baeldung.parsingDates.SimpleDateUtils;
import com.baeldung.parsingDates.SimpleParseDate;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import org.junit.*;
import static org.junit.Assert.*;
import org.joda.time.LocalDate;
public class SimpleParseDateUnitTest {
@Test
public void whenInvalidInput_thenGettingUnexpectedResult() {
SimpleParseDate simpleParseDate = new SimpleParseDate();
String date = "2022-40-40";
assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString());
}
@Test
public void whenInvalidDate_thenAssertThrows() {
SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater();
assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04"));
assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04"));
}
@Test
public void whenDateIsCorrect_thenParseCorrect() {
SimpleDateUtils simpleDateUtils = new SimpleDateUtils();
assertNull(simpleDateUtils.parseDate("53/10/2014"));
assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString());
}
@Test
public void whenDateIsCorrect_thenResultCorrect() {
SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat();
assertNull(simpleDateTimeFormat.parseDate("53/10/2014"));
assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10"));
}
}
@@ -4,7 +4,6 @@
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-8-datetime</artifactId>
<version>${project.parent.version}</version>
<name>core-java-8-datetime</name>
<packaging>jar</packaging>
-1
View File
@@ -4,7 +4,6 @@
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-8</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-8</name>
<packaging>jar</packaging>
@@ -4,7 +4,6 @@
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-9-improvements</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9-improvements</name>
<parent>
@@ -8,5 +8,5 @@ This module contains articles about Project Jigsaw and the Java Platform Module
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
javac -d mods/com.baeldung.library.core $(find library-core/src/main -name "*.java")
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
javac --class-path outDir/library-core/:\
libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-test library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-core \
library-core/src/main/java/com/baeldung/library/core/Book.java \
library-core/src/main/java/com/baeldung/library/core/Library.java \
library-core/src/main/java/com/baeldung/library/core/Main.java \
library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
libs/junit-platform-engine-1.9.2.jar:\
libs/apiguardian-api-1.1.2.jar:\
libs/junit-jupiter-params-5.9.2.jar:\
libs/junit-jupiter-api-5.9.2.jar:\
libs/opentest4j-1.2.0.jar:\
libs/junit-platform-commons-1.9.2.jar \
-d outDir/library-core \
library-core/src/main/java/com/baeldung/library/core/Book.java \
library-core/src/main/java/com/baeldung/library/core/Library.java \
library-core/src/main/java/com/baeldung/library/core/Main.java
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
javac --module-path mods:libs -d mods/com.baeldung.library.test $(find library-test/src/test -name "*.java")
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
wget -P libs/ https://repo1.maven.org/maven2/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-commons/1.9.2/junit-platform-commons-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-engine/1.9.2/junit-platform-engine-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-reporting/1.9.2/junit-platform-reporting-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console/1.9.2/junit-platform-console-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/1.9.2/junit-platform-launcher-1.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.9.2/junit-jupiter-engine-5.9.2.jar /
wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-params/5.9.2/junit-jupiter-params-5.9.2.jar
@@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>core-java-9-jigsaw</artifactId>
<version>0.2-SNAPSHOT</version>
</parent>
<artifactId>library-core</artifactId>
<properties>
<maven.compiler.source>19</maven.compiler.source>
<maven.compiler.target>19</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>9</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<useModulePath>false</useModulePath>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,52 @@
package com.baeldung.library.core;
import java.util.Objects;
public class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + "]";
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Book book = (Book) o;
if (!Objects.equals(title, book.title)) {
return false;
}
return Objects.equals(author, book.author);
}
@Override
public int hashCode() {
int result = title != null ? title.hashCode() : 0;
result = 31 * result + (author != null ? author.hashCode() : 0);
return result;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.library.core;
import java.util.ArrayList;
import java.util.List;
public class Library {
private List<Book> books = new ArrayList<>();
public void addBook(Book book) {
books.add(book);
}
public List<Book> getBooks() {
return books;
}
void removeBook(Book book) {
books.remove(book);
}
protected void removeBookByAuthor(String author) {
books.removeIf(book -> book.getAuthor().equals(author));
}
}
@@ -0,0 +1,16 @@
package com.baeldung.library.core;
public class Main {
public static void main(String[] args) {
Library library = new Library();
library.addBook(new Book("The Lord of the Rings", "J.R.R. Tolkien"));
library.addBook(new Book("The Hobbit", "J.R.R. Tolkien"));
library.addBook(new Book("The Silmarillion", "J.R.R. Tolkien"));
library.addBook(new Book("The Chronicles of Narnia", "C.S. Lewis"));
library.addBook(new Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis"));
System.out.println("Welcome to our library!");
System.out.println("We have the following books:");
library.getBooks().forEach(System.out::println);
}
}
@@ -0,0 +1,3 @@
module com.baeldung.library.core {
exports com.baeldung.library.core;
}
@@ -0,0 +1,47 @@
package com.baeldung.library.core;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class LibraryUnitTest {
@Test
void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
library.removeBook(theLordOfTheRings);
int expected = 0;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
library.addBook(theLordOfTheRings);
library.addBook(theHobbit);
library.addBook(theSilmarillion);
library.addBook(theHungerGames);
library.removeBookByAuthor("J.R.R. Tolkien");
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
}
@@ -0,0 +1,53 @@
package com.baeldung.library.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.baeldung.library.core.Book;
import com.baeldung.library.core.Library;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
class LibraryUnitTest {
@Test
void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty()
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Library library = new Library();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
library.addBook(theLordOfTheRings);
Method removeBook = Library.class.getDeclaredMethod("removeBook", Book.class);
removeBook.setAccessible(true);
removeBook.invoke(library, theLordOfTheRings);
int expected = 0;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
@Test
void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
TestLibrary library = new TestLibrary();
Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
library.addBook(theLordOfTheRings);
library.addBook(theHobbit);
library.addBook(theSilmarillion);
library.addBook(theHungerGames);
library.removeBookByAuthor("J.R.R. Tolkien");
int expected = 1;
int actual = library.getBooks().size();
assertEquals(expected, actual);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.library.test;
import com.baeldung.library.core.Library;
public class TestLibrary extends Library {
@Override
public void removeBookByAuthor(final String author) {
super.removeBookByAuthor(author);
}
}
@@ -0,0 +1,5 @@
module com.baeldung.library.test {
requires com.baeldung.library.core;
requires org.junit.jupiter.api;
opens com.baeldung.library.test to org.junit.platform.commons;
}
+4 -1
View File
@@ -4,8 +4,11 @@
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-9-jigsaw</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9-jigsaw</name>
<packaging>pom</packaging>
<modules>
<module>library-core</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
java --module-path mods:libs \
--add-modules com.baeldung.library.core \
--add-opens com.baeldung.library.core/com.baeldung.library.core=org.junit.platform.commons \
--add-reads com.baeldung.library.core=org.junit.jupiter.api \
--patch-module com.baeldung.library.core=outDir/library-test \
--module org.junit.platform.console --select-class com.baeldung.library.core.LibraryUnitTest
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
java --module-path mods --module com.baeldung.library.core/com.baeldung.library.core.Main
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
java --module-path libs \
org.junit.platform.console.ConsoleLauncher \
--classpath ./outDir/library-core \
--select-class com.baeldung.library.core.LibraryUnitTest
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
java --module-path mods:libs \
--add-modules com.baeldung.library.test \
--add-opens com.baeldung.library.core/com.baeldung.library.core=com.baeldung.library.test \
org.junit.platform.console.ConsoleLauncher --select-class com.baeldung.library.test.LibraryUnitTest
@@ -4,7 +4,6 @@
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-9-new-features</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9-new-features</name>
<parent>
@@ -4,7 +4,6 @@
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-9-streams</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-9-streams</name>
<packaging>jar</packaging>
-1
View File
@@ -5,7 +5,6 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [Method Handles in Java](https://www.baeldung.com/java-method-handles)
- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
-1
View File
@@ -4,7 +4,6 @@
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-9</artifactId>
<version>0.2-SNAPSHOT</version>
<name>core-java-9</name>
<parent>
@@ -4,7 +4,6 @@
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-annotations</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-annotations</name>
<packaging>jar</packaging>
@@ -24,4 +23,12 @@
</resources>
</build>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</project>
@@ -17,7 +17,7 @@ public class ClassWithSuppressWarningsNames implements Serializable {
list.add(Integer.valueOf(value));
}
@SuppressWarnings("deprecated")
@SuppressWarnings("deprecation")
void suppressDeprecatedWarning() {
ClassWithSuppressWarningsNames cls = new ClassWithSuppressWarningsNames();
cls.deprecatedMethod(); // no warning here
@@ -11,3 +11,5 @@ This module contains articles about Java array fundamentals. They assume no prev
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Extending an Arrays Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
- [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index)
- [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays)
@@ -0,0 +1,28 @@
package com.baeldung.arrayindex;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
class ArrayIndex {
static int forLoop(int[] numbers, int target) {
for (int index = 0; index < numbers.length; index++) {
if (numbers[index] == target) {
return index;
}
}
return -1;
}
static int listIndexOf(Integer[] numbers, int target) {
List<Integer> list = Arrays.asList(numbers);
return list.indexOf(target);
}
static int intStream(int[] numbers, int target) {
return IntStream.range(0, numbers.length)
.filter(i -> numbers[i] == target)
.findFirst()
.orElse(-1);
}
}
@@ -0,0 +1,39 @@
package com.baeldung.array.compare;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
public class CompareByteArraysUnitTest {
private final static String INPUT = "I am a magic string.";
private final static byte[] ARRAY1 = INPUT.getBytes();
private final static byte[] ARRAY2 = INPUT.getBytes();
@Test
void whenUsingEqualsSign_thenTwoArraysAreNotEqual() {
assertFalse(ARRAY1 == ARRAY2);
}
@Test
void whenUsingEquals_thenTwoArraysAreNotEqual() {
assertFalse(ARRAY1.equals(ARRAY2));
}
@Test
void whenUsingArrayEquals_thenTwoArraysAreEqual() {
assertTrue(Arrays.equals(ARRAY1, ARRAY2));
}
@Test
void whenComparingStringArrays_thenGetExpectedResult() {
String[] strArray1 = new String[] { "Java", "is", "great" };
String[] strArray2 = new String[] { "Java", "is", "great" };
assertFalse(strArray1 == strArray2);
assertFalse(strArray1.equals(strArray2));
assertTrue(Arrays.equals(strArray1, strArray2));
}
}
@@ -0,0 +1,106 @@
package com.baeldung.arrayindex;
import static com.baeldung.arrayindex.ArrayIndex.forLoop;
import static com.baeldung.arrayindex.ArrayIndex.intStream;
import static com.baeldung.arrayindex.ArrayIndex.listIndexOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.junit.jupiter.api.Test;
import com.google.common.primitives.Ints;
class ArrayIndexUnitTest {
@Test
void givenIntegerArray_whenUseForLoop_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, forLoop(numbers, 30));
}
@Test
void givenIntegerArray_whenUseForLoop_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, forLoop(numbers, 100));
}
@Test
void givenIntegerArray_whenUseIndexOf_thenWillGetElementIndex() {
Integer[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, listIndexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseIndexOf_thenWillGetElementMinusOneIndex() {
Integer[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, listIndexOf(numbers, 100));
}
@Test
void givenIntegerArray_whenUseIntStream_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, intStream(numbers, 30));
}
@Test
void givenIntegerArray_whenUseIntStream_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, intStream(numbers, 100));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, Arrays.binarySearch(numbers, 30));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetUpperBoundMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-6, Arrays.binarySearch(numbers, 100));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetInArrayMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-2, Arrays.binarySearch(numbers, 15));
}
@Test
void givenIntegerArray_whenUseBinarySearch_thenWillGetLowerBoundMinusIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, Arrays.binarySearch(numbers, -15));
}
@Test
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, ArrayUtils.indexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseApacheCommonsStartingFromIndex_thenWillGetNegativeIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, ArrayUtils.indexOf(numbers, 30, 3));
}
@Test
void givenIntegerArray_whenUseApacheCommons_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, ArrayUtils.indexOf(numbers, 100));
}
@Test
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(2, Ints.indexOf(numbers, 30));
}
@Test
void givenIntegerArray_whenUseGuavaInts_thenWillGetElementMinusOneIndex() {
int[] numbers = { 10, 20, 30, 40, 50 };
assertEquals(-1, Ints.indexOf(numbers, 100));
}
}
@@ -0,0 +1,6 @@
## Core Java Booleans
This module contains articles about Java Booleans.
### Relevant Articles:
- [Convert Boolean to String in Java](https://www.baeldung.com/java-convert-boolean-to-string)
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-booleans</artifactId>
<name>core-java-booleans</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
</project>
@@ -0,0 +1,48 @@
package com.baeldung.booleans;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class BooleanToStringUnitTest {
String optionToString(String optionName, boolean optionValue) {
return String.format("The option '%s' is %s.", optionName, optionValue ? "Enabled" : "Disabled");
}
@Test
void givenPrimitiveBoolean_whenConvertingUsingTernaryOperator_thenSuccess() {
boolean primitiveBoolean = true;
assertEquals("true", primitiveBoolean ? "true" : "false");
primitiveBoolean = false;
assertEquals("false", primitiveBoolean ? "true" : "false");
assertEquals("The option 'IgnoreWarnings' is Enabled.", optionToString("IgnoreWarnings", true));
}
@Test
void givenBooleanObject_whenConvertingUsingBooleanToString_thenSuccess() {
Boolean myBoolean = Boolean.TRUE;
assertEquals("true", myBoolean.toString());
myBoolean = Boolean.FALSE;
assertEquals("false", myBoolean.toString());
Boolean nullBoolean = null;
assertThrows(NullPointerException.class, () -> nullBoolean.toString());
}
@Test
void givenBooleanObject_whenConvertingUsingStringValueOf_thenSuccess() {
Boolean myBoolean = Boolean.TRUE;
assertEquals("true", String.valueOf(myBoolean));
myBoolean = Boolean.FALSE;
assertEquals("false", String.valueOf(myBoolean));
Boolean nullBoolean = null;
assertEquals("null", String.valueOf(nullBoolean));
}
}
@@ -4,3 +4,4 @@ This module contains articles about Java Character Class
### Relevant Articles:
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
- [Difference Between Javas “char” and “String”](https://www.baeldung.com/java-char-vs-string)
-1
View File
@@ -4,7 +4,6 @@
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-char</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-char</name>
<packaging>jar</packaging>
@@ -0,0 +1,56 @@
package com.baeldung.charandstring;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import org.junit.jupiter.api.Test;
public class DifferenceBetweenCharAndStringUnitTest {
@Test
void whenPlusTwoChars_thenGetSumAsInteger() {
char h = 'H'; // the value is 72
char i = 'i'; // the value is 105
assertEquals(177, h + i);
assertInstanceOf(Integer.class, h + i);
}
@Test
void whenPlusTwoStrings_thenConcatenateThem() {
String i = "i";
String h = "H";
assertEquals("Hi", h + i);
}
@Test
void whenPlusCharsAndStrings_thenGetExpectedValues() {
char c = 'C';
assertEquals("C", "" + c);
char h = 'H'; // the value is 72
char i = 'i'; // the value is 105
assertEquals("Hi", "" + h + i);
assertEquals("Hi", h + "" + i);
assertEquals("177", h + i + "");
}
@Test
void whenStringChars_thenGetCharArray() {
char h = 'h';
char e = 'e';
char l = 'l';
char o = 'o';
String hello = "hello";
assertEquals(h, hello.charAt(0));
assertEquals(e, hello.charAt(1));
assertEquals(l, hello.charAt(2));
assertEquals(l, hello.charAt(3));
assertEquals(o, hello.charAt(4));
char[] chars = new char[] { h, e, l, l, o };
char[] charsFromString = hello.toCharArray();
assertArrayEquals(chars, charsFromString);
}
}
@@ -13,4 +13,4 @@
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Differences Between Iterator and Iterable and How to Use Them?](https://www.baeldung.com/java-iterator-vs-iterable)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-1) [[next -->]](/core-java-modules/core-java-collections-3)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections) [[next -->]](/core-java-modules/core-java-collections-3)
@@ -4,7 +4,6 @@
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-3</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-3</name>
<packaging>jar</packaging>
@@ -4,7 +4,6 @@
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-4</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-collections-4</name>
<packaging>jar</packaging>
@@ -3,5 +3,5 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -1,10 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
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-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-collections-5</name>
<packaging>jar</packaging>
@@ -55,4 +54,5 @@
<roaringbitmap.version>0.9.38</roaringbitmap.version>
<jmh.version>1.36</jmh.version>
</properties>
</project>

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