Merge branch 'eugenp:master' into master

This commit is contained in:
Wynn Teo
2024-04-15 08:12:34 +08:00
committed by GitHub
224 changed files with 3946 additions and 594 deletions
@@ -1,23 +1,22 @@
package com.baeldung.algorithms.mergeintervals;
import static java.lang.Integer.max;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class MergeOverlappingIntervals {
public List<Interval> doMerge(List<Interval> intervals) {
// Sort the intervals based on start time
intervals.sort((one, two) -> one.start - two.start);
// Create somewhere to put the merged list, start it off with the earliest starting interval
intervals.sort(Comparator.comparingInt(interval -> interval.start));
ArrayList<Interval> merged = new ArrayList<>();
merged.add(intervals.get(0));
// Loop over each interval and merge if start time is before the end time of the
// previous interval
intervals.forEach(interval -> {
if (merged.get(merged.size() - 1).end > interval.start) {
merged.get(merged.size() - 1).setEnd(interval.end);
Interval lastMerged = merged.get(merged.size() - 1);
if (interval.start <= lastMerged.end){
lastMerged.setEnd(max(interval.end, lastMerged.end));
} else {
merged.add(interval);
}
@@ -25,5 +24,4 @@ public class MergeOverlappingIntervals {
return merged;
}
}
}
@@ -1,30 +1,38 @@
package com.baeldung.algorithms.mergeintervals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
class MergeIntervalsUnitTest {
private ArrayList<Interval> intervals = new ArrayList<>(Arrays.asList(
new Interval(2, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(1, 3)
private List<Interval> intervals = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(3, 5),
new Interval(13, 20),
new Interval(11, 15),
new Interval(15, 16),
new Interval(1, 3),
new Interval(4, 5),
new Interval(16, 17)
// @formatter:on
));
private ArrayList<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
new Interval(1, 5),
new Interval(11, 20)
private List<Interval> intervalsMerged = new ArrayList<>(Arrays.asList(
// @formatter:off
new Interval(1, 5),
new Interval(11, 20)
// @formatter:on
));
@Test
void givenIntervals_whenMerging_thenReturnMergedIntervals() {
MergeOverlappingIntervals merger = new MergeOverlappingIntervals();
ArrayList<Interval> result = (ArrayList<Interval>) merger.doMerge(intervals);
assertArrayEquals(intervalsMerged.toArray(), result.toArray());
List<Interval> result = merger.doMerge(intervals);
assertEquals(intervalsMerged, result);
}
}
}
+11
View File
@@ -40,6 +40,16 @@
<artifactId>fastexcel-reader</artifactId>
<version>${fastexcel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
@@ -64,6 +74,7 @@
<jexcel.version>1.0.9</jexcel.version>
<fastexcel.version>0.17.0</fastexcel.version>
<maven.resources.plugin.version>3.3.1</maven.resources.plugin.version>
<log4j.version>2.23.1</log4j.version>
</properties>
</project>
@@ -71,7 +71,7 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -112,7 +112,6 @@
<feign-core.version>11.2</feign-core.version>
<guice.version>5.1.0</guice.version>
<system-stubs-junit4.version>2.0.2</system-stubs-junit4.version>
<mockito-core.version>4.1.0</mockito-core.version>
<assertj-core.version>3.19.0</assertj-core.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
</properties>
@@ -0,0 +1,4 @@
package com.baeldung;
public class Unrelated {
}
@@ -1,7 +1,7 @@
package com.baeldung;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Set;
@@ -14,22 +14,22 @@ public class OuterUnitTest {
@Test
public void whenGetNestHostFromOuter_thenGetNestHost() {
is(Outer.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.class.getNestHost().getName());
}
@Test
public void whenGetNestHostFromInner_thenGetNestHost() {
is(Outer.Inner.class.getNestHost().getName()).equals(NEST_HOST_NAME);
assertEquals(NEST_HOST_NAME, Outer.Inner.class.getNestHost().getName());
}
@Test
public void whenCheckNestmatesForNestedClasses_thenGetTrue() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(true);
assertTrue(Outer.Inner.class.isNestmateOf(Outer.class));
}
@Test
public void whenCheckNestmatesForUnrelatedClasses_thenGetFalse() {
is(Outer.Inner.class.isNestmateOf(Outer.class)).equals(false);
assertFalse(Outer.Inner.class.isNestmateOf(Unrelated.class));
}
@Test
+1
View File
@@ -1,3 +1,4 @@
## Relevant Articles
- [Deprecate Finalization in Java 18](https://www.baeldung.com/java-18-deprecate-finalization)
- [Simple Web Server in Java 18](https://www.baeldung.com/simple-web-server-java-18)
- [Internet Address Resolution SPI in Java](https://www.baeldung.com/java-service-provider-interface)
@@ -3,3 +3,4 @@
- [Find the Equilibrium Indexes of an Array in Java](https://www.baeldung.com/java-equilibrium-index-array)
- [Moves Zeros to the End of an Array in Java](https://www.baeldung.com/java-array-sort-move-zeros-end)
- [Finding the Majority Element of an Array in Java](https://www.baeldung.com/java-array-find-majority-element)
- [Set Matrix Elements to Zero in Java](https://www.baeldung.com/java-set-matrix-elements-to-zero)
@@ -0,0 +1,147 @@
package com.baeldung.matrixtozero;
import java.util.*;
public class SetMatrixToZero{
static void setZeroesByNaiveApproach(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int [][] result = new int[row][col];
for(int i = 0; i<row; i++){
for(int j = 0; j < col; j++){
result[i][j] = matrix[i][j];
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(matrix[i][j] == 0){
for(int k = 0; k < col; k++){
result[i][k] = 0;
}
for(int k = 0; k < row; k++){
result[k][j] = 0;
}
}
}
}
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
matrix[i][j] = result[i][j];
}
}
}
static void setZeroesByTimeOptimizedApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
Set<Integer> rowSet = new HashSet<>();
Set<Integer> colSet = new HashSet<>();
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if (matrix[i][j] == 0){
rowSet.add(i);
colSet.add(j);
}
}
}
for(int row: rowSet){
for(int j = 0; j < cols; j++){
matrix[row][j] = 0;
}
}
for(int col: colSet) {
for(int i = 0; i < rows; i++){
matrix[i][col] = 0;
}
}
}
static boolean hasZeroInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == 0) {
return true;
}
}
return false;
}
static boolean hasZeroInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
return true;
}
}
return false;
}
static void markZeroesInMatrix(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
}
static void setZeroesInRows(int[][] matrix, int rows, int cols) {
for (int i = 1; i < rows; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInCols(int[][] matrix, int rows, int cols) {
for (int j = 1; j < cols; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < rows; i++) {
matrix[i][j] = 0;
}
}
}
}
static void setZeroesInFirstRow(int[][] matrix, int cols) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
static void setZeroesInFirstCol(int[][] matrix, int rows) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
static void setZeroesByOptimalApproach(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = hasZeroInFirstRow(matrix, cols);
boolean firstColZero = hasZeroInFirstCol(matrix, rows);
markZeroesInMatrix(matrix, rows, cols);
setZeroesInRows(matrix, rows, cols);
setZeroesInCols(matrix, rows, cols);
if (firstRowZero) {
setZeroesInFirstRow(matrix, cols);
}
if (firstColZero) {
setZeroesInFirstCol(matrix, rows);
}
}
}
@@ -0,0 +1,54 @@
package com.baeldung.matrixtozero;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class SetMatrixToZeroUnitTest{
@Test
void givenMatrix_whenUsingSetZeroesByNaiveApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByNaiveApproach(matrix);
assertArrayEquals(expected, matrix);
}
@Test
void givenMatrix_whenUsingSetZeroesByTimeOptimizedApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByTimeOptimizedApproach(matrix);
assertArrayEquals(expected, matrix);
}
@Test
void givenMatrix_whenUsingSetZeroesByOptimalApproach_thenSetZeroes() {
int[][] matrix = {
{1, 2, 3},
{4, 0, 6},
{7, 8, 9}
};
int[][] expected = {
{1, 0, 3},
{0, 0, 0},
{7, 0, 9}
};
SetMatrixToZero.setZeroesByOptimalApproach(matrix);
assertArrayEquals(expected, matrix);
}
}
@@ -13,4 +13,5 @@
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
- [PriorityQueue iterator() Method in Java](https://www.baeldung.com/java-priorityqueue-iterator)
- [Immutable vs Unmodifiable Collection in Java](https://www.baeldung.com/java-collection-immutable-unmodifiable-differences)
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
@@ -3,3 +3,5 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-5)
@@ -0,0 +1,64 @@
package com.baeldung.iteratorvsforeach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class IteratorVsForeachUnitTest {
private static Stream<Arguments> listProvider() {
return Stream.of(Arguments.of(List.of("String1", "String2", "unwanted"), List.of("String1", "String2")));
}
@Test
public void givenEmptyCollection_whenUsingForEach_thenNoElementsAreIterated() {
List<String> names = Collections.emptyList();
StringBuilder stringBuilder = new StringBuilder();
names.forEach(stringBuilder::append);
assertEquals("", stringBuilder.toString());
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringForEachIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
// Separate collection for items to be removed
List<String> toRemove = new ArrayList<>();
// Using forEach to identify items to remove
input.forEach(item -> {
if (item.equals("unwanted")) {
toRemove.add(item);
}
});
// Removing the identified items from the original list
mutableList.removeAll(toRemove);
assertIterableEquals(expected, mutableList);
}
@ParameterizedTest
@MethodSource("listProvider")
public void givenCollectionWithElements_whenRemovingElementDuringIteratorIteration_thenElementIsRemoved(List<String> input, List<String> expected) {
List<String> mutableList = new ArrayList<>(input);
Iterator<String> it = mutableList.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.equals("unwanted")) {
it.remove(); // Safely remove item
}
}
assertIterableEquals(expected, mutableList);
}
}
@@ -11,5 +11,6 @@ This module contains articles about core Java input and output (IO)
- [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads)
- [Convert an OutputStream to a Byte Array in Java](https://www.baeldung.com/java-outputstream-byte-array)
- [Reading a .gz File Line by Line Using GZIPInputStream](https://www.baeldung.com/java-gzipinputstream-read-gz-file-line-by-line)
- [Opening HTML File Using Java](https://www.baeldung.com/java-open-html-file)
- [[<-- Prev]](/core-java-modules/core-java-io-4)
@@ -0,0 +1,113 @@
package com.baeldung.printwriterwritevsprint;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
public class WriteVsPrintUnitTest {
Object outputFromPrintWriter;
Object outputFromPrintWriter() {
try (BufferedReader br = new BufferedReader(new FileReader("output.txt"))){
outputFromPrintWriter = br.readLine();
} catch (IOException e){
e.printStackTrace();
Assertions.fail();
}
return outputFromPrintWriter;
}
@Test
void whenUsingWriteInt_thenASCIICharacterIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(48);
printWriter.close();
assertEquals("0", outputFromPrintWriter());
}
@Test
void whenUsingWriteCharArrayFromOffset_thenCharArrayIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write(new char[]{'A','/','&','4','E'}, 1, 4 );
printWriter.close();
assertEquals("/&4E", outputFromPrintWriter());
}
@Test
void whenUsingWriteStringFromOffset_thenLengthOfStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.write("StringExample", 6, 7 );
printWriter.close();
assertEquals("Example", outputFromPrintWriter());
}
@Test
void whenUsingPrintBoolean_thenStringValueIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(true);
printWriter.close();
assertEquals("true", outputFromPrintWriter());
}
@Test
void whenUsingPrintChar_thenCharIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print('A');
printWriter.close();
assertEquals("A", outputFromPrintWriter());
}
@Test
void whenUsingPrintInt_thenValueOfIntIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print(420);
printWriter.close();
assertEquals("420", outputFromPrintWriter());
}
@Test
void whenUsingPrintString_thenStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
printWriter.print("RandomString");
printWriter.close();
assertEquals("RandomString", outputFromPrintWriter());
}
@Test
void whenUsingPrintObject_thenObjectToStringIsPrinted() throws FileNotFoundException {
PrintWriter printWriter = new PrintWriter("output.txt");
Map example = new HashMap();
printWriter.print(example);
printWriter.close();
assertEquals(example.toString(), outputFromPrintWriter());
}
}
@@ -20,28 +20,6 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<!-- this is all you need to write tests with JUnit Jupiter -->
<dependency>
<groupId>org.junit.jupiter</groupId>
@@ -63,18 +41,6 @@
<version>${junit-jupiter-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
-1
View File
@@ -260,7 +260,6 @@
<!-- util -->
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<mockito.version>4.6.1</mockito.version>
<!-- maven plugins -->
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<maven-javadoc-plugin.version>3.6.2</maven-javadoc-plugin.version>
@@ -10,3 +10,4 @@ This module contains articles about Object Oriented Programming (OOP) in Java
- [Law of Demeter in Java](https://www.baeldung.com/java-demeter-law)
- [Java Interface Naming Conventions](https://www.baeldung.com/java-interface-naming-conventions)
- [Difference Between Information Hiding and Encapsulation](https://www.baeldung.com/java-information-hiding-vs-encapsulation)
- [Statements Before super() in Java](https://www.baeldung.com/java-statements-before-super-constructor)
@@ -0,0 +1,44 @@
package com.baeldung.printnullvalues;
import java.util.Objects;
import java.util.Optional;
public class Employee {
private String name;
private int age;
private String department;
public Employee(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
public String toStringUsingNullCheck() {
return "Name: " + (name != null ? name : "Unknown") +
", Age: " + age +
", Department: " + (department != null ? department : "Unknown");
}
public String toStringUsingOptional() {
return "Name: " + Optional.ofNullable(name).orElse("Unknown") +
", Age: " + age +
", Department: " + Optional.ofNullable(department).orElse("Unknown");
}
private String getDefaultIfNull(String value, String defaultValue) {
return value != null ? value : defaultValue;
}
public String toStringUsingCustomHelper() {
return "Name: " + getDefaultIfNull(name, "Unknown") +
", Age: " + age +
", Department: " + getDefaultIfNull(department, "Unknown");
}
public String toStringUsingObjects() {
return "Name: " + Objects.toString(name, "Unknown") +
", Age: " + age +
", Department: " + Objects.toString(department, "Unknown");
}
}
@@ -0,0 +1,30 @@
package com.baeldung.printnullvalues;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PrintingNullValuesUnitTest {
Employee employee = new Employee(null, 30, null);
String expected = "Name: Unknown, Age: 30, Department: Unknown";
@Test
public void givenNullValues_whenToStringUsingNullCheck_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingNullCheck());
}
@Test
public void givenNullValues_whenToStringUsingOptional_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingOptional());
}
@Test
public void givenNullValues_whenToStringUsingCustomHelper_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingCustomHelper());
}
@Test
public void givenNullValues_whenToStringUsingObjects_thenCorrectStringReturned() {
assertEquals(expected, employee.toStringUsingObjects());
}
}
@@ -0,0 +1,2 @@
## Relevant Articles:
- [[<-- Prev]](/core-java-modules/core-java-networking-4)
@@ -0,0 +1,59 @@
<?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-networking-5</artifactId>
<packaging>jar</packaging>
<name>core-java-networking-5</name>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>${commons-validator.version}</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.ws.rs-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>${jersey-common.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-web.version}</version>
</dependency>
</dependencies>
<properties>
<commons-validator.version>1.7</commons-validator.version>
<jsoup.version>1.17.2</jsoup.version>
<httpclient.version>4.5.2</httpclient.version>
<javax.ws.rs-api.version>2.1.1</javax.ws.rs-api.version>
<jersey-common.version>2.22.2</jersey-common.version>
<spring-web.version>6.0.6</spring-web.version>
</properties>
</project>
@@ -0,0 +1,57 @@
package com.baeldung.redirectedurl;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static org.junit.Assert.assertEquals;
public class RedirectedUrlUnitTest {
String canonicalUrl = "http://www.baeldung.com/";
String expectedRedirectedUrl = "https://www.baeldung.com/";
@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpURLConnection_thenCorrectRedirectedUrlReturned() throws IOException {
URL url = new URL(canonicalUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
int status = connection.getResponseCode();
String redirectedUrl = null;
if (status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_MOVED_TEMP) {
redirectedUrl = connection.getHeaderField("Location");
}
connection.disconnect();
assertEquals(expectedRedirectedUrl, redirectedUrl);
}
@Test
public void givenOriginalUrl_whenFindRedirectUrlUsingHttpClient_thenCorrectRedirectedUrlReturned() throws IOException {
RequestConfig config = RequestConfig.custom()
.setRedirectsEnabled(false)
.build();
try (CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(config)
.build()) {
HttpGet httpGet = new HttpGet(canonicalUrl);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
String redirectedUrl = null;
if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) {
org.apache.http.Header[] headers = response.getHeaders("Location");
if (headers.length > 0) {
redirectedUrl = headers[0].getValue();
}
}
assertEquals(expectedRedirectedUrl, redirectedUrl);
}
}
}
}
@@ -0,0 +1,57 @@
package com.baeldung.complexnumbers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public record ComplexNumber(double real, double imaginary) {
public static ComplexNumber fromString(String complexNumberStr) {
Pattern pattern = Pattern.compile("(-?\\d*\\.?\\d+)?(?:([+-]?\\d*\\.?\\d+)i)?");
Matcher matcher = pattern.matcher(complexNumberStr.replaceAll("\\s", ""));
if (matcher.matches()) {
// Extract real and imaginary parts
String realPartStr = matcher.group(1);
String imaginaryPartStr = matcher.group(2);
// Parse real part (if present)
double real = (realPartStr != null) ? Double.parseDouble(realPartStr) : 0;
// Parse imaginary part (if present)
double imaginary = (imaginaryPartStr != null) ? Double.parseDouble(imaginaryPartStr) : 0;
return new ComplexNumber(real, imaginary);
} else {
throw new IllegalArgumentException("Invalid complex number format(" + complexNumberStr + "), supported format is `a+bi`");
}
}
public String toString() {
return real + "+" + imaginary + "i";
}
public ComplexNumber add(ComplexNumber that) {
return new ComplexNumber(real + that.real, imaginary + that.imaginary);
}
public ComplexNumber multiply(ComplexNumber that) {
double newReal = this.real * that.real - this.imaginary * that.imaginary;
double newImaginary = this.real * that.imaginary + this.imaginary * that.real;
return new ComplexNumber(newReal, newImaginary);
}
public ComplexNumber subtract(ComplexNumber that) {
return new ComplexNumber(real - that.real, imaginary - that.imaginary);
}
public ComplexNumber divide(ComplexNumber that) {
if(that.real == 0 && that.imaginary == 0 ){
throw new ArithmeticException("Division by 0 is not allowed!");
}
double c2d2 = Math.pow(that.real, 2) + Math.pow(that.imaginary, 2);
double newReal = (this.real * that.real + this.imaginary * that.imaginary) / c2d2;
double newImaginary = (this.imaginary * that.real - this.real * that.imaginary) / c2d2;
return new ComplexNumber(newReal, newImaginary);
}
}
@@ -0,0 +1,103 @@
package com.baeldung.complexnumbers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class ComplexNumberOperationsUnitTest {
@ParameterizedTest(name = "Multiplying {0} and {1}")
@CsvSource({
"3+2i, 1+7i, -11+23i",
"2, 4, 8",
"2, 4i, 8i",
"1+1i, 1+1i, 0+2i",
" 3+2i, 1 + 7i, -11 + 23i ",
"0+5i, 3+0i, 0+15i",
"0+0i, -2+0i, 0+0i",
"-3+2i, 1-7i, 11+23i",
"2+4i, 0, 0"
})
public void givenTwoComplexNumbers_multiplyAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber product = complex1.multiply(complex2);
Assertions.assertTrue(isSame(product, expected));
}
@ParameterizedTest(name = "Adding {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 4+9i",
"2, 4, 6",
"2, 4i, 2+4i",
"1+1i, 1+1i, 2+2i",
" 3+2i, 1 + 7i, 4 + 9i ",
"0+5i, 3+0i, 3+5i",
"0+0i, -2+0i, -2+0i",
"-3+2i, 1-7i, -2-5i",
"2+4i, 0, 2+4i"
})
public void givenTwoComplexNumbers_addThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.add(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@ParameterizedTest(name = "Subtracting {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 2-5i",
"2, 4, -2",
"2, 4i, 2-4i",
"1+1i, 1+1i, 0",
" 3+ 2i, 1+ 7i, 2-5i",
"0+5i, 3+0i, -3+5i",
"0+0i, -2+0i, 2+0i",
"-3+2i, 1-7i, -4+9i",
"2+4i, 0, 2+4i"
})
public void givenTwoComplexNumbers_subtractAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.subtract(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@ParameterizedTest(name = "Dividing {0} and {1}")
@CsvSource({
"3+2i, 1+7i, 0.34-0.38i",
"2, 4, 0.5",
"2, 4i, 0-0.5i",
"1+1i, 1+1i, 1",
"3 + 2i, 1 + 7i, 0.34-0.38i",
"0+5i, 3+0i, 0+1.6666666666666667i",
"0+0i, -2+0i, 0+0i",
"-3+2i, 1-7i, -0.34-0.38i",
"2+4i, 1, 2+4i"
})
public void givenTwoComplexNumbers_divideThemAndGetResult(String complexStr1, String complexStr2, String expectedStr) {
ComplexNumber complex1 = ComplexNumber.fromString(complexStr1);
ComplexNumber complex2 = ComplexNumber.fromString(complexStr2);
ComplexNumber expected = ComplexNumber.fromString(expectedStr);
ComplexNumber sum = complex1.divide(complex2);
Assertions.assertTrue(isSame(sum, expected));
}
@Test
public void givenAComplexNumberAsZero_handleDivideByZeroScenario() {
ComplexNumber complex1 = new ComplexNumber(1, 1);
ComplexNumber zero = new ComplexNumber(0, 0);
Exception exception = Assertions.assertThrows(ArithmeticException.class, () -> {
complex1.divide(zero);
});
Assertions.assertEquals(exception.getMessage(), "Division by 0 is not allowed!");
}
public boolean isSame(ComplexNumber result, ComplexNumber expected) {
return result.real() == expected.real() && result.imaginary() == expected.imaginary();
}
}
@@ -5,73 +5,70 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SymmetricSubstringMaxLengthUnitTest {
String input = "<><??>>";
String input = "abba";
int expected = 4;
@Test
public void givenString_whenUsingSymmetricSubstringExpansion_thenFindLongestSymmetricSubstring() {
int start = 0;
int mid = 0;
int last_gt = 0;
int end = 0;
int best = 0;
static int findLongestSymmetricSubstringUsingSymmetricApproach(String str) {
int maxLength = 1;
while (start < input.length()) {
int current = Math.min(mid - start, end - mid);
if (best < current) {
best = current;
}
if (end - mid == current && end < input.length()) {
if (input.charAt(end) == '?') {
end++;
} else if (input.charAt(end) == '>') {
end++;
last_gt = end;
} else {
end++;
mid = end;
start = Math.max(start, last_gt);
for (int i = 0; i < str.length(); i++) {
for (int j = i; j < str.length(); j++) {
int flag = 1;
for (int k = 0; k < (j - i + 1) / 2; k++) {
if (str.charAt(i + k) != str.charAt(j - k)) {
flag = 0;
break;
}
}
if (flag != 0 && (j - i + 1) > maxLength) {
maxLength = j - i + 1;
}
} else if (mid < input.length() && input.charAt(mid) == '?') {
mid++;
} else if (start < mid) {
start++;
} else {
start = Math.max(start, last_gt);
mid++;
end = Math.max(mid, end);
}
}
int result = 2 * best;
assertEquals(expected, result);
return maxLength;
}
@Test
public void givenString_whenUsingBruteForce_thenFindLongestSymmetricSubstring() {
int max = 0;
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j <= input.length(); j++) {
String t = input.substring(i, j);
if (t.length() % 2 == 0) {
int k = 0, l = t.length() - 1;
boolean isSym = true;
while (k < l && isSym) {
if (!(t.charAt(k) == '<' || t.charAt(k) == '?') && (t.charAt(l) == '>' || t.charAt(l) == '?')) {
isSym = false;
}
k++;
l--;
}
if (isSym) {
max = Math.max(max, t.length());
}
assertEquals(expected, findLongestSymmetricSubstringUsingBruteForce(input).length());
}
@Test
public void givenString_whenUsingSymmetricSubstring_thenFindLongestSymmetricSubstring() {
assertEquals(expected, findLongestSymmetricSubstringUsingSymmetricApproach(input));
}
private String findLongestSymmetricSubstringUsingBruteForce(String str) {
if (str == null || str.length() == 0) {
return "";
}
int maxLength = 0;
String longestPalindrome = "";
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j <= str.length(); j++) {
String substring = str.substring(i, j);
if (isPalindrome(substring) && substring.length() > maxLength) {
maxLength = substring.length();
longestPalindrome = substring;
}
}
}
assertEquals(expected, max);
return longestPalindrome;
}
private boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}
+1
View File
@@ -165,6 +165,7 @@
<module>core-java-networking</module>
<module>core-java-networking-2</module>
<module>core-java-networking-4</module>
<module>core-java-networking-5</module>
<module>core-java-nio</module>
<module>core-java-nio-2</module>
<module>core-java-numbers</module>
+8 -1
View File
@@ -20,7 +20,7 @@
<!-- Boot version compatible with spqr-boot-starter -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.6.4</version>
<version>2.6.15</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@@ -34,4 +34,11 @@
<module>graphql-spqr-boot-starter</module>
</modules>
<properties>
<org.slf4j.version>1.7.32</org.slf4j.version>
<logback.version>1.2.7</logback.version>
<!-- Can't update to the recent mockito version, without updating the spring boot version-->
<mockito.version>4.4.0</mockito.version>
</properties>
</project>
@@ -0,0 +1,41 @@
package com.baeldung.imageprocessing.imagetobufferedimage;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageToBufferedImage {
// Method 1: Using BufferedImage Constructor
public BufferedImage convertUsingConstructor(Image image) throws IllegalArgumentException {
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Image dimensions are invalid");
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
bufferedImage.getGraphics().drawImage(image, 0, 0, null);
return bufferedImage;
}
// Method 2: Casting Image to BufferedImage
public BufferedImage convertUsingCasting(Image image) throws ClassCastException {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
} else {
throw new ClassCastException("Image type is not compatible with BufferedImage");
}
}
// Method 3: Using ImageIO Class
public BufferedImage convertUsingImageIO(String filePath) throws IOException {
try {
File file = new File(filePath);
return ImageIO.read(file);
} catch (Exception e) {
throw new IOException("Error reading image file: " + e.getMessage());
}
}
}
@@ -0,0 +1,69 @@
package com.baeldung.image.resize.imagetobufferedimage;
import com.baeldung.imageprocessing.imagetobufferedimage.ImageToBufferedImage;
import org.junit.Test;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ImageToBufferedImageUnitTest {
Image image = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
public ImageToBufferedImageUnitTest() throws IOException {
}
@Test
public void whenConvertUsingConstructorWithValidDimensions_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingConstructor(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = IllegalArgumentException.class)
public void whenConvertUsingConstructorWithInvalidDimensions_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
converter.convertUsingConstructor(new BufferedImage(-100, -100, BufferedImage.TYPE_INT_ARGB));
}
@Test
public void whenConvertUsingCastingWithCompatibleImageType_thenImageGeneratedWithoutError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingCasting(image);
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = ClassCastException.class)
public void whenConvertUsingCastingWithIncompatibleImageType_thenImageGeneratedWithError() {
ImageToBufferedImage converter = new ImageToBufferedImage();
// PNG format is not directly supported by BufferedImage
Image image = new ImageIcon("src/main/resources/images/baeldung.png").getImage();
converter.convertUsingCasting(image);
}
@Test
public void whenConvertUsingImageIOWithValidFile_thenImageGeneratedWithoutError() throws IOException {
ImageToBufferedImage converter = new ImageToBufferedImage();
BufferedImage bufferedImage = converter.convertUsingImageIO("src/main/resources/images/sampleImage.jpg");
assertNotNull(bufferedImage);
assertEquals(image.getWidth(null), bufferedImage.getWidth());
assertEquals(image.getHeight(null), bufferedImage.getHeight());
}
@Test(expected = IOException.class)
public void whenConvertUsingImageIOWithInvalidFile_thenImageGeneratedWithError() throws IOException {
ImageToBufferedImage converter = new ImageToBufferedImage();
converter.convertUsingImageIO("invalid_file.jpg");
}
}

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