Merge remote-tracking branch 'upstream/master' into feature/BAEL-6695-BooleanValidation

This commit is contained in:
Niket Agrawal 2023-10-05 11:47:33 +05:30
commit 601ec56453
312 changed files with 4748 additions and 848 deletions

View File

@ -5,7 +5,7 @@ title: '[ISSUE] '
--- ---
**Article and Module Links** **Article and Module Links**
A link to the affected article and the affected module. The link to the module is the one in the "over on GitHub" standard phrase. A link to the affected article and the affected module. You can find the link to the module in the Conclusion section in the "on Github" standard phase.
**Describe the Issue** **Describe the Issue**
A clear and concise description of what the issue is. A clear and concise description of what the issue is.
@ -30,9 +30,3 @@ If applicable, add screenshots to help explain your problem.
**Additional Context** **Additional Context**
Add any other context about the issue here. Add any other context about the issue here.
Note that, unfortunately, we can only help with issues that are specifically and directly related to the article - not with your own, custom application.
StackOverflow is a great place to ask more general questions.
That's primarily because we get a large number of questions and - while we do try to go through as much as everything and help wherever we can, we can't really get back to all of them.

3
apache-poi-3/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant Articles
- [How To Convert Excel Data Into List Of Java Objects](https://www.baeldung.com/java-convert-excel-data-into-list)
- [Expand Columns with Apache POI](https://www.baeldung.com/java-apache-poi-expand-columns)

View File

@ -5,3 +5,4 @@
- [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting) - [Collecting Stream Elements into a List in Java](https://www.baeldung.com/java-stream-to-list-collecting)
- [New Features in Java 16](https://www.baeldung.com/java-16-new-features) - [New Features in Java 16](https://www.baeldung.com/java-16-new-features)
- [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector) - [Guide to Java 8 groupingBy Collector](https://www.baeldung.com/java-groupingby-collector)
- [Value-Based Classes in Java](https://www.baeldung.com/java-value-based-classes)

View File

@ -1,2 +1,3 @@
## Relevant Articles ## Relevant Articles
- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections) - [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections)
- [String Templates in Java 21](https://www.baeldung.com/java-21-string-templates)

View File

@ -12,6 +12,12 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
</parent> </parent>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
@ -20,14 +26,22 @@
<configuration> <configuration>
<source>21</source> <source>21</source>
<target>21</target> <target>21</target>
<compilerArgs>--enable-preview</compilerArgs> <!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
<debug>false</debug>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project> </project>

View File

@ -0,0 +1,11 @@
package com.baeldung.unnamed.variables;
public record Car<T extends Engine>(String name, String color, T engine) { }
abstract class Engine { }
class GasEngine extends Engine { }
class ElectricEngine extends Engine { }
class HybridEngine extends Engine { }

View File

@ -0,0 +1,50 @@
package com.baeldung.unnamed.variables;
public class UnnamedPatterns {
static String getObjectsColorWithNamedPattern(Object object) {
if (object instanceof Car(String name, String color, Engine engine)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithUnnamedPattern(Object object) {
if (object instanceof Car(_, String color, _)) {
return color;
}
return "No color!";
}
static String getObjectsColorWithSwitchAndNamedPattern(Object object) {
return switch (object) {
case Car(String name, String color, Engine engine) -> color;
default -> "No color!";
};
}
static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) {
return switch (object) {
case Car(_, String color, _) -> color;
default -> "No color!";
};
}
static String getEngineTypeWithNamedPattern(Car<?> car) {
return switch (car) {
case Car(String name, String color, GasEngine engine) -> "gas";
case Car(String name, String color, ElectricEngine engine) -> "electric";
case Car(String name, String color, HybridEngine engine) -> "hybrid";
default -> "none";
};
}
static String getEngineTypeWithUnnamedPattern(Car<?> car) {
return switch (car) {
case Car(_, _, GasEngine _) -> "gas";
case Car(_, _, ElectricEngine _) -> "electric";
case Car(_, _, HybridEngine _) -> "hybrid";
default -> "none";
};
}
}

View File

@ -0,0 +1,134 @@
package com.baeldung.unnamed.variables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class Transaction implements AutoCloseable {
@Override
public void close() {
System.out.println("Closed!");
}
}
public class UnnamedVariables {
static int countCarsOverLimitWithNamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var car : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static int countCarsOverLimitWithUnnamedVariable(Collection<Car<?>> cars, int limit) {
var total = 0;
var totalOverLimit = 0;
for (var _ : cars) {
total++;
if (total > limit) {
totalOverLimit++;
// side effect
}
}
return totalOverLimit;
}
static void sendNotificationToCarsWithNamedVariable(Collection<Car<?>> cars) {
sendOneTimeNotification();
for (int i = 0; i < cars.size(); i++) {
// Notify car
}
}
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> cars) {
for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) {
// Notify car
}
}
private static int sendOneTimeNotification() {
System.out.println("Sending one time notification!");
return 1;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue<Car<?>> cars) {
var x = cars.poll();
var y = cars.poll();
var z = cars.poll();
return x;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> cars) {
var car = cars.poll();
var _ = cars.poll();
var _ = cars.poll();
return car;
}
static void handleCarExceptionWithNamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException ex) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException ex) {
System.out.println("Got a runtime exception!");
}
}
static void handleCarExceptionWithUnnamedVariables(Car<?> car) {
try {
someOperationThatFails(car);
} catch (IllegalStateException | NumberFormatException _) {
System.out.println("Got an illegal state exception for: " + car.name());
} catch (RuntimeException _) {
System.out.println("Got a runtime exception!");
}
}
static void obtainTransactionAndUpdateCarWithNamedVariables(Car<?> car) {
try (var transaction = new Transaction()) {
updateCar(car);
}
}
static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car<?> car) {
try (var _ = new Transaction()) {
updateCar(car);
}
}
static void updateCar(Car<?> car) {
// Some update logic
System.out.println("Car updated!");
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car)
);
return carMap;
}
private static void someOperationThatFails(Car<?> car) {
throw new IllegalStateException("Triggered exception for: " + car.name());
}
}

View File

@ -0,0 +1,3 @@
void main() {
System.out.println("Hello, World!");
}

View File

@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldChild extends HelloWorldSuper {
void main() {
System.out.println("Hello, World!");
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.unnamedclasses;
public class HelloWorldSuper {
public static void main(String[] args) {
System.out.println("Hello from the superclass");
}
}

View File

@ -0,0 +1,6 @@
private String getMessage() {
return "Hello, World!";
}
void main() {
System.out.println(getMessage());
}

View File

@ -0,0 +1,13 @@
package com.baeldung.unnamed.variables;
import java.util.List;
class CarScenario {
protected final List<Car<?>> cars = List.of(
new Car<>("Mitsubishi", "blue", new GasEngine()),
new Car<>("Toyota", "red", new ElectricEngine()),
new Car<>("Jaguar", "white", new HybridEngine())
);
}

View File

@ -0,0 +1,44 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern;
import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class UnnamedPatternsUnitTest extends CarScenario {
@Test
public void whenExtractingColorWithNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() {
assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0)));
}
@Test
public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() {
assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0)));
}
}

View File

@ -0,0 +1,93 @@
package com.baeldung.unnamed.variables;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable;
import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.LinkedList;
import org.junit.jupiter.api.Test;
public class UnnamedVariablesUnitTest extends CarScenario {
@Test
public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2));
}
@Test
public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() {
assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2));
}
@Test
public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars));
}
@Test
public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() {
assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars));
}
@Test
public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() {
var carQueue = new LinkedList<>(cars);
assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name());
assertEquals(0, carQueue.size());
}
@Test
public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0)));
}
@Test
public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() {
assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0)));
}
@Test
public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
@Test
public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() {
var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars);
assertEquals(1, carsByLetter.get("M").size());
assertEquals(1, carsByLetter.get("T").size());
assertEquals(1, carsByLetter.get("J").size());
}
}

View File

@ -4,3 +4,4 @@ This module contains articles about Java 9 streams
### Relevant Articles: ### Relevant Articles:
- [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach) - [How to Break from Java Stream forEach](https://www.baeldung.com/java-break-stream-foreach)
- [Creating Stream of Regex Matches](https://www.baeldung.com/java-stream-regex-matches)

View File

@ -9,3 +9,4 @@ This module contains complete guides about arrays in Java
- [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception) - [Guide to ArrayStoreException](https://www.baeldung.com/java-arraystoreexception)
- [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array) - [Creating a Generic Array in Java](https://www.baeldung.com/java-generic-array)
- [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size) - [Maximum Size of Java Arrays](https://www.baeldung.com/java-arrays-max-size)
- [Merge Two Arrays and Remove Duplicates in Java](https://www.baeldung.com/java-merge-two-arrays-delete-duplicates)

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)

View File

@ -14,4 +14,3 @@ This module contains articles about advanced operations on arrays in Java. They
- [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays) - [Slicing Arrays in Java](https://www.baeldung.com/java-slicing-arrays)
- [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays) - [Combining Two or More Byte Arrays](https://www.baeldung.com/java-concatenate-byte-arrays)
- [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise) - [Calculating the Sum of Two Arrays in Java](https://www.baeldung.com/java-sum-arrays-element-wise)
- [Find the Middle Element of an Array in Java](https://www.baeldung.com/java-array-middle-item)

View File

@ -0,0 +1,29 @@
package com.baeldung.incrementchar;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class IncrementCharUnitTest {
@Test
void whenUsingForLoop_thenGenerateCharacters(){
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
List<Character> characters = new ArrayList<>();
for (char character = 'A'; character <= 'Z'; character++) {
characters.add(character);
}
Assertions.assertEquals(characters, allCapitalCharacters);
}
@Test
void whenUsingStreams_thenGenerateCharacters() {
final List<Character> allCapitalCharacters = Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
final List<Character> characters = IntStream.rangeClosed('A', 'Z').mapToObj(c -> (char) c).collect(Collectors.toList());
Assertions.assertEquals(characters, allCapitalCharacters);
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class SkipFirstElementExample {
private final List<String> stringList = new ArrayList<>();
private final Set<String> stringSet = new HashSet<>();
private final Map<String, String> stringMap = new HashMap<>();
public SkipFirstElementExample() {
// Initializing a List
stringList.add("Monday");
stringList.add("Tuesday");
stringList.add("Wednesday");
stringList.add("Thursday");
stringList.add("Friday");
stringList.add("Saturday");
stringList.add("Sunday");
// Initializing a Set
stringSet.add("Monday");
stringSet.add("Tuesday");
stringSet.add("Wednesday");
stringSet.add("Thursday");
stringSet.add("Friday");
stringSet.add("Saturday");
stringSet.add("Sunday");
// Initializing a Map
stringMap.put("Monday", "The day when coffee is a life support system.");
stringMap.put("Tuesday", "The day you realize that Monday's optimism was a lie.");
stringMap.put("Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.");
stringMap.put("Thursday", "The day that says, 'Hold my beer, Friday is coming!'");
stringMap.put("Friday", "The golden child of the weekdays. The superhero of the workweek.");
stringMap.put("Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'");
stringMap.put("Sunday", "The day before you have to adult again.");
}
void skippingFirstElementInListWithForLoop(List<String> stringList) {
for (int i = 1; i < stringList.size(); i++) {
process(stringList.get(i));
}
}
void skippingFirstElementInListWithWhileLoop(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInSetWithWhileLoop(Set<String> stringSet) {
final Iterator<String> iterator = stringSet.iterator();
if (iterator.hasNext()) {
iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
}
}
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> stringList) {
final Iterator<String> iterator = stringList.iterator();
String firstElement = null;
if (iterator.hasNext()) {
firstElement = iterator.next();
}
while (iterator.hasNext()) {
process(iterator.next());
// additional logic using fistElement
}
}
void skippingFirstElementInMapWithStreamSkip(Map<String, String> stringMap) {
stringMap.entrySet().stream().skip(1).forEach(this::process);
}
void skippingFirstElementInListWithSubList(List<String> stringList) {
for (final String element : stringList.subList(1, stringList.size())) {
process(element);
}
}
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> stringList) {
for (int i = 0; i < stringList.size(); i++) {
if (i == 0) {
// do something else
} else {
process(stringList.get(i));
}
}
}
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> stringList) {
int counter = 0;
while (counter < stringList.size()) {
if (counter != 0) {
process(stringList.get(counter));
}
++counter;
}
}
void skippingFirstElementInListWithReduce(List<String> stringList) {
stringList.stream().reduce((skip, element) -> {
process(element);
return element;
});
}
protected void process(String string) {
System.out.println(string);
}
protected void process(Entry<String, String> mapEntry) {
System.out.println(mapEntry);
}
}

View File

@ -0,0 +1,122 @@
package com.baeldung.skippingfirstelement;
import static org.junit.jupiter.api.Assertions.*;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
@EnabledForJreRange(min = JRE.JAVA_9)
class SkipFirstElementExampleUnitTest {
private static TestableSkipFirstElement testableSkip = new TestableSkipFirstElement();
@BeforeEach
void setup() {
testableSkip.reset();
}
private static Stream<Arguments> listProvider() {
return Stream.of(
Arguments.of(
List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"),
List.of("Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"))
);
}
private static Stream<Arguments> mapProvider() {
return Stream.of(
Arguments.of(
Map.of(
"Monday", "The day when coffee is a life support system.",
"Tuesday", "The day you realize that Monday's optimism was a lie.",
"Wednesday", "Hump Day, or as it's known, the 'Is it Friday yet?' day.",
"Thursday", "The day that says, 'Hold my beer, Friday is coming!'",
"Friday", "The golden child of the weekdays. The superhero of the workweek.",
"Saturday", "The day of rest? More like the day of 'What can I binge-watch next?'",
"Sunday", "The day before you have to adult again."
)
)
);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoop(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoop(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInSetWithWhileLoop(List<String> input) {
testableSkip.skippingFirstElementInSetWithWhileLoop(new HashSet<>(input));
Set<?> actual = new HashSet<>(testableSkip.getResult());
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopStoringFirstElement(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopStoringFirstElement(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("mapProvider")
void skippingFirstElementInMapWithStreamSkip(Map<String, String> input) {
testableSkip.skippingFirstElementInMapWithStreamSkip(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual.size(), input.size() - 1);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithSubList(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithSubList(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithForLoopWithAdditionalCheck(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithForLoopWithAdditionalCheck(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithWhileLoopWithCounter(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithWhileLoopWithCounter(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
@ParameterizedTest
@MethodSource("listProvider")
void skippingFirstElementInListWithReduce(List<String> input, List<String> expected) {
testableSkip.skippingFirstElementInListWithReduce(input);
List<?> actual = testableSkip.getResult();
assertEquals(actual, expected);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.skippingfirstelement;
import java.util.List;
public interface TestableSkip {
void reset();
List<?> getResult();
}

View File

@ -0,0 +1,37 @@
package com.baeldung.skippingfirstelement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
public class TestableSkipFirstElement extends SkipFirstElementExample implements TestableSkip {
private List<String> processedList = new ArrayList<>();
private List<Entry<String, String>> processedEntryList = new ArrayList<>();
@Override
public void process(String string) {
processedList.add(string);
}
@Override
public void process(Entry<String, String> stringEntry) {
processedEntryList.add(stringEntry);
}
@Override
public void reset() {
processedList.clear();
processedEntryList.clear();
}
@Override
public List<?> getResult() {
if (!processedList.isEmpty())
return processedList;
return processedEntryList;
}
}

View File

@ -0,0 +1,6 @@
## Core Java Collections ArrayList
This module contains articles about the Java ArrayList collection
### Relevant Articles:
- [Create an ArrayList with Multiple Object Types](https://www.baeldung.com/arraylist-with-multiple-object-types)

View File

@ -0,0 +1,32 @@
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-array-list-2</artifactId>
<name>core-java-collections-array-list-2</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven-compiler-plugin.source}</source>
<target>${maven-compiler-plugin.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven-compiler-plugin.source>17</maven-compiler-plugin.source>
<maven-compiler-plugin.target>17</maven-compiler-plugin.target>
</properties>
</project>

View File

@ -0,0 +1,51 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Predicate;
public class AlternativeMultipeTypeList {
public static void main(String[] args) {
// List of Parent Class
ArrayList<Number> myList = new ArrayList<>();
myList.add(1.2);
myList.add(2);
myList.add(-3.5);
// List of Interface type
ArrayList<Map> diffMapList = new ArrayList<>();
diffMapList.add(new HashMap<>());
diffMapList.add(new TreeMap<>());
diffMapList.add(new LinkedHashMap<>());
// List of Custom Object
ArrayList<CustomObject> objList = new ArrayList<>();
objList.add(new CustomObject("String"));
objList.add(new CustomObject(2));
// List via Functional Interface
List<Object> dataList = new ArrayList<>();
Predicate<Object> myPredicate = inputData -> (inputData instanceof String || inputData instanceof Integer);
UserFunctionalInterface myInterface = (listObj, data) -> {
if (myPredicate.test(data))
listObj.add(data);
else
System.out.println("Skipping input as data not allowed for class: " + data.getClass()
.getSimpleName());
return listObj;
};
myInterface.addToList(dataList, Integer.valueOf(2));
myInterface.addToList(dataList, Double.valueOf(3.33));
myInterface.addToList(dataList, "String Value");
myInterface.printList(dataList);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.list.multipleobjecttypes;
public class CustomObject {
String classData;
Integer intData;
CustomObject(String classData) {
this.classData = classData;
}
CustomObject(Integer intData) {
this.intData = intData;
}
public String getClassData() {
return this.classData;
}
public Integer getIntData() {
return this.intData;
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.list.multipleobjecttypes;
import java.math.BigInteger;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultipleObjectTypeArrayList {
public static void main(String[] args) {
ArrayList<Object> multiTypeList = new ArrayList<>();
multiTypeList.add(Integer.valueOf(10));
multiTypeList.add(Double.valueOf(11.5));
multiTypeList.add("String Data");
multiTypeList.add(Arrays.asList(1, 2, 3));
multiTypeList.add(new CustomObject("Class Data"));
multiTypeList.add(BigInteger.valueOf(123456789));
multiTypeList.add(LocalDate.of(2023, 9, 19));
for (Object dataObj : multiTypeList) {
if (dataObj instanceof Integer intData)
System.out.println("Integer Data : " + intData);
else if (dataObj instanceof Double doubleData)
System.out.println("Double Data : " + doubleData);
else if (dataObj instanceof String stringData)
System.out.println("String Data : " + stringData);
else if (dataObj instanceof List<?> intList)
System.out.println("List Data : " + intList);
else if (dataObj instanceof CustomObject customObj)
System.out.println("CustomObject Data : " + customObj.getClassData());
else if (dataObj instanceof BigInteger bigIntData)
System.out.println("BigInteger Data : " + bigIntData);
else if (dataObj instanceof LocalDate localDate)
System.out.println("LocalDate Data : " + localDate.toString());
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.list.multipleobjecttypes;
import java.util.List;
@FunctionalInterface
public interface UserFunctionalInterface {
List<Object> addToList(List<Object> list, Object data);
default void printList(List<Object> dataList) {
for (Object data : dataList) {
if (data instanceof String stringData)
System.out.println("String Data: " + stringData);
if (data instanceof Integer intData)
System.out.println("Integer Data: " + intData);
}
}
}

View File

@ -0,0 +1,2 @@
## Relevant Articles
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)

View File

@ -0,0 +1,15 @@
<?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-collections-list-6</artifactId>
<name>core-java-collections-list-6</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>

View File

@ -0,0 +1,44 @@
package com.baeldung.lists;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
public class StringListCaseInsensitiveContainsUnitTest {
private final static List<String> THE_LIST = List.of("Game of Thrones", "Forrest Gump", "American Beauty", "Pretty Woman", "Catch Me If You Can");
@Test
void whenUsingContains_thenGetExpectedResult() {
assertFalse(THE_LIST.contains("catch me if you can"));
}
boolean ignoreCaseContainsForLoop(List<String> list, String value) {
for (String e : list) {
if (value.equalsIgnoreCase(e))
return true;
}
return false;
}
@Test
void whenUsingIgnoreCaseContainsForLoop_thenGetExpectedResult() {
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "CATCH me if you CAN"));
assertTrue(ignoreCaseContainsForLoop(THE_LIST, "game of thrones"));
assertFalse(ignoreCaseContainsForLoop(THE_LIST, "The Godfather"));
}
@Test
void whenUsingIgnoreCaseContainsStream_thenGetExpectedResult() {
assertTrue(THE_LIST.stream()
.anyMatch(e -> e.equalsIgnoreCase("CATCH me if you CAN")));
assertTrue(THE_LIST.stream()
.anyMatch("game of thrones"::equalsIgnoreCase));
assertFalse(THE_LIST.stream()
.anyMatch("The Godfather"::equalsIgnoreCase));
}
}

View File

@ -1,76 +0,0 @@
package java.com.baeldung.objecttomap;
import com.google.gson.Gson;
import org.junit.Assert;
import org.junit.Test;
import wiremock.com.fasterxml.jackson.core.type.TypeReference;
import wiremock.com.fasterxml.jackson.databind.ObjectMapper;
import wiremock.com.google.common.reflect.TypeToken;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ObjectToMapUnitTest {
Employee employee = new Employee("John", 3000.0);
@Test
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
Map<String, Object> map = convertUsingReflection(employee);
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
@Test
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
Gson gson = new Gson();
String json = gson.toJson(employee);
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
Assert.assertEquals(employee.getName(), map.get("name"));
Assert.assertEquals(employee.getSalary(), map.get("salary"));
}
private static class Employee {
private String name;
private Double salary;
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double age) {
this.salary = salary;
}
}
}

View File

@ -0,0 +1,128 @@
package com.baeldung.objecttomap;
import static org.junit.Assert.assertEquals;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ObjectToMapUnitTest {
Employee employee = new Employee("John", 3000.0);
@Test
public void givenJavaObject_whenUsingReflection_thenConvertToMap() throws IllegalAccessException {
Map<String, Object> map = convertUsingReflection(employee);
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
private Map<String, Object> convertUsingReflection(Object object) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>();
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(object));
}
return map;
}
@Test
public void givenJavaObject_whenUsingJackson_thenConvertToMap() {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = objectMapper.convertValue(employee, new TypeReference<Map<String, Object>>() {});
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void givenJavaObject_whenUsingGson_thenConvertToMap() {
Gson gson = new Gson();
String json = gson.toJson(employee);
Map<String, Object> map = gson.fromJson(json, new TypeToken<Map<String, Object>>() {}.getType());
assertEquals(employee.getName(), map.get("name"));
assertEquals(employee.getSalary(), map.get("salary"));
}
@Test
public void given_UnsortedMap_whenSortingByValueDescending_thenValuesAreInDescendingOrder() {
Map<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("three", 3);
unsortedMap.put("five", 5);
unsortedMap.put("two", 2);
unsortedMap.put("four", 4);
Map<String, Integer> sortedMap = sortMapByValueDescending(unsortedMap);
assertEquals(5, sortedMap.size());
final Iterator<Integer> iterator = sortedMap.values().iterator();
assertEquals(5, (int) iterator.next());
assertEquals(4, (int) iterator.next());
assertEquals(3, (int) iterator.next());
assertEquals(2, (int) iterator.next());
assertEquals(1, (int) iterator.next());
}
@Test
public void given_UnsortedMap_whenUsingTreeMap_thenKeysAreInDescendingOrder() {
SortedMap<String, Integer> treeMap = new TreeMap<>(Comparator.reverseOrder());
treeMap.put("one", 1);
treeMap.put("three", 3);
treeMap.put("five", 5);
treeMap.put("two", 2);
treeMap.put("four", 4);
assertEquals(5, treeMap.size());
final Iterator<String> iterator = treeMap.keySet().iterator();
assertEquals("two", iterator.next());
assertEquals("three", iterator.next());
assertEquals("one", iterator.next());
assertEquals("four", iterator.next());
assertEquals("five", iterator.next());
}
private static class Employee {
private String name;
private Double salary;
public Employee(String name, Double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double age) {
this.salary = salary;
}
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValueDescending(Map<K, V> map) {
return map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
}

View File

@ -3,4 +3,4 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [Code Snippets in Java API Documentation](https://www.baeldung.com/java-doc-code-snippets)

View File

@ -0,0 +1,18 @@
package com.baeldung.snippettag;
/**
*
* External code snippet showing the loop process in binary search method.
* {@snippet class="BinarySearch" region="binary"}
*
* Time Zone
* {@snippet file="application.properties" region="zone"}
*
*/
public class GreetingsExternalSnippet {
public void helloBinarySearch() {
System.out.println("Hi, it's great knowing that binary search uses a loop under the hood");
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.snippettag;
/**
* The code below shows a full highlighted line
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight
* }
* }
*
* highlighting a substring
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight substring="println"
* }
* }
*
* highlighting texts on multiple lines
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @highlight region substring="println"
* String country = "USA";
* System.out.println("Hello From Team " + country); // @end
* }
* }
*
*/
public class GreetingsHighlightTag {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.snippettag;
/**
* The code below shows the content of {@code helloBaeldung()} method
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung");
* }
* }
*/
public class GreetingsInlineSnippet {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.snippettag;
/**
*
* Using the replace tag
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @replace regex='".*"' replacement="..."
* }
* }
* Using the link tag
* {@snippet :
* public void helloBaeldung() {
* System.out.println("Hello From Team Baeldung"); // @link substring="System.out" target="System#out"
* }
* }
*
*/
public class GreetingsReplaceAndLinkTag {
public void helloBaeldung() {
System.out.println("Hello From Team Baeldung");
}
}

View File

@ -0,0 +1,27 @@
public class BinarySearch {
public int search(int[] list, int item) {
int index = Integer.MAX_VALUE;
int low = 0;
int high = list.length - 1;
// @start region="binary"
while (low <= high) {
int mid = high - low;
int guess = list[mid];
if (guess == item) {
index = mid;
break;
} else if (guess > item) {
low = mid - 1;
} else {
low = mid + 1;
}
low++;
}
// @end region="binary"
return index;
}
}

View File

@ -0,0 +1,4 @@
# @start region="zone"
local.timezone = GMT+1
local.zip = 94123
# @end region="zone"

View File

@ -0,0 +1,2 @@
test-link*
0.*

View File

@ -0,0 +1,8 @@
## Core Java IO
This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [[<-- Prev]](/core-java-modules/core-java-io-4)

View File

@ -0,0 +1,66 @@
<?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-io-5</artifactId>
<name>core-java-io-5</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Mime Type Resolution Libraries -->
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>${jmime-magic.version}</version>
</dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-util</artifactId>
<version>${jodd-util.version}</version>
</dependency>
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>${simplemagic.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-io-5</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Mime Type Libraries -->
<tika.version>2.8.0</tika.version>
<jmime-magic.version>0.1.5</jmime-magic.version>
<jodd-util.version>6.2.1</jodd-util.version>
<simplemagic.version>1.17</simplemagic.version>
</properties>
</project>

View File

@ -11,10 +11,8 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.tika.mime.MimeTypeException; import org.apache.tika.mime.MimeTypeException;
import org.junit.Test;
import com.j256.simplemagic.ContentType; import com.j256.simplemagic.ContentType;
import org.junit.Test;
public class ExtensionFromMimeTypeUnitTest { public class ExtensionFromMimeTypeUnitTest {
private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg"; private static final String IMAGE_JPEG_MIME_TYPE = "image/jpeg";
@ -37,14 +35,14 @@ public class ExtensionFromMimeTypeUnitTest {
} }
@Test @Test
public void whenUsingMimetypesFileTypeMap_thenGetFileExtension() { public void whenUsingSimpleMagic_thenGetFileExtension() {
List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe"); List<String> expectedExtensions = Arrays.asList("jpeg", "jpg", "jpe");
String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions(); String[] detectedExtensions = ContentType.fromMimeType(IMAGE_JPEG_MIME_TYPE).getFileExtensions();
assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions); assertThat(detectedExtensions).containsExactlyElementsOf(expectedExtensions);
} }
@Test @Test
public void whenUsingCustomLogic_thenGetFileExtension() { public void whenUsingCustomMap_thenGetFileExtension() {
Map<String, Set<String>> mimeExtensionsMap = new HashMap<>(); Map<String, Set<String>> mimeExtensionsMap = new HashMap<>();
List<String> expectedExtensions = Arrays.asList(".jpg", ".jpe", ".jpeg"); List<String> expectedExtensions = Arrays.asList(".jpg", ".jpe", ".jpeg");
addMimeExtensions(mimeExtensionsMap, "image/jpeg", ".jpg"); addMimeExtensions(mimeExtensionsMap, "image/jpeg", ".jpg");

View File

@ -7,3 +7,4 @@ This module contains articles about core Java input/output(IO) APIs.
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path) - [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty) - [Check if a File Is Empty in Java](https://www.baeldung.com/java-check-file-empty)
- [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths) - [Converting Relative to Absolute Paths in Java](https://www.baeldung.com/java-from-relative-to-absolute-paths)
- [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file)

View File

@ -43,17 +43,6 @@
<version>${angus-activation.version}</version> <version>${angus-activation.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-util</artifactId>
<version>${jodd-util.version}</version>
</dependency>
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>${simplemagic.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -153,8 +142,6 @@
<fscontext.version>4.4.2</fscontext.version> <fscontext.version>4.4.2</fscontext.version>
<jakarta-activation-api.version>2.1.2</jakarta-activation-api.version> <jakarta-activation-api.version>2.1.2</jakarta-activation-api.version>
<angus-activation.version>2.0.1</angus-activation.version> <angus-activation.version>2.0.1</angus-activation.version>
<jodd-util.version>6.2.1</jodd-util.version>
<simplemagic.version>1.17</simplemagic.version>
</properties> </properties>
</project> </project>

View File

@ -18,7 +18,11 @@
<artifactId>mapstruct</artifactId> <artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version> <version>${mapstruct.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -0,0 +1,47 @@
package com.baeldung.compareobjects;
import java.util.Objects;
public class Address {
private String streetAddress;
private String city;
private String postalCode;
public Address(String streetAddress, String city, String postalCode) {
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "Address{" + "streetAddress='" + streetAddress + '\'' + ", city='" + city + '\'' + ", postalCode='" + postalCode + '\'' + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Address address = (Address) o;
return Objects.equals(streetAddress, address.streetAddress) && Objects.equals(city, address.city) && Objects.equals(postalCode, address.postalCode);
}
@Override
public int hashCode() {
return Objects.hash(streetAddress, city, postalCode);
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.compareobjects;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.builder.DiffExclude;
public class Person {
private String firstName;
private String lastName;
private int age;
private List<PhoneNumber> phoneNumbers;
@DiffExclude
private Address address;
public Person(String firstName, String lastName, int age, List<PhoneNumber> phoneNumbers, Address address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phoneNumbers = phoneNumbers;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public List<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
public Address getAddress() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(phoneNumbers, person.phoneNumbers) && Objects.equals(address, person.address);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age, phoneNumbers, address);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.compareobjects;
import org.apache.commons.lang3.builder.DiffBuilder;
import org.apache.commons.lang3.builder.DiffResult;
import org.apache.commons.lang3.builder.ToStringStyle;
public class PersonDiffBuilder {
public static DiffResult compare(Person first, Person second) {
DiffBuilder diffBuilder = new DiffBuilder(first, second, ToStringStyle.DEFAULT_STYLE).append("person", first.getFirstName(), second.getFirstName())
.append("lastName", first.getLastName(), second.getLastName())
.append("streetAddress", first.getAddress()
.getStreetAddress(), second.getAddress()
.getStreetAddress())
.append("city", first.getAddress()
.getCity(), second.getAddress()
.getCity())
.append("postalCode", first.getAddress()
.getPostalCode(), second.getAddress()
.getPostalCode())
.append("age", first.getAge(), second.getAge());
for (int i = 0; i < first.getPhoneNumbers()
.size(); i++) {
diffBuilder.append("phoneNumbers[" + i + "].number", first.getPhoneNumbers()
.get(i)
.getNumber(), second.getPhoneNumbers()
.get(i)
.getNumber());
}
return diffBuilder.build();
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.compareobjects;
import org.apache.commons.lang3.builder.DiffResult;
import org.apache.commons.lang3.builder.ReflectionDiffBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class PersonReflectionDiffBuilder {
public static DiffResult compare(Person first, Person second) {
return new ReflectionDiffBuilder<>(first, second, ToStringStyle.SHORT_PREFIX_STYLE).build();
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.compareobjects;
import java.util.Objects;
import org.apache.commons.lang3.builder.DiffExclude;
public class PhoneNumber {
private String type;
private String number;
public PhoneNumber(String type, String number) {
this.type = type;
this.number = number;
}
public String getType() {
return type;
}
public String getNumber() {
return number;
}
@Override
public String toString() {
return "PhoneNumber{" + "type='" + type + '\'' + ", number='" + number + '\'' + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
PhoneNumber that = (PhoneNumber) o;
return Objects.equals(number, that.number);
}
@Override
public int hashCode() {
return Objects.hash(number);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.compareobjects;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.Diff;
import org.apache.commons.lang3.builder.DiffResult;
import org.junit.jupiter.api.Test;
public class PersonDiffBuilderUnitTest {
@Test
void givenTwoPeopleDifferent_whenComparingWithDiffBuilder_thenDifferencesFound() {
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
Address address1 = new Address("123 Main St", "London", "12345");
Address address2 = new Address("123 Main St", "Paris", "54321");
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
DiffResult<Person> diff = PersonDiffBuilder.compare(person1, person2);
for (Diff<?> d : diff.getDiffs()) {
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
}
assertFalse(diff.getDiffs()
.isEmpty());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.compareobjects;
import static org.junit.jupiter.api.Assertions.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.builder.Diff;
import org.apache.commons.lang3.builder.DiffResult;
import org.junit.jupiter.api.Test;
public class PersonReflectionDiffBuilderUnitTest {
@Test
void givenTwoPeopleDifferent_whenComparingWithReflectionDiffBuilder_thenDifferencesFound() {
List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));
List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));
Address address1 = new Address("123 Main St", "London", "12345");
Address address2 = new Address("123 Main St", "Paris", "54321");
Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);
DiffResult<Person> diff = PersonReflectionDiffBuilder.compare(person1, person2);
for (Diff<?> d : diff.getDiffs()) {
System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
}
assertFalse(diff.getDiffs()
.isEmpty());
}
}

View File

@ -4,4 +4,5 @@
- [Integer.class vs Integer.TYPE vs int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int) - [Integer.class vs Integer.TYPE vs int.class](https://www.baeldung.com/java-integer-class-vs-type-vs-int)
- [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian) - [Does Java Read Integers in Little Endian or Big Endian?](https://www.baeldung.com/java-integers-little-big-endian)
- [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits) - [How to Split an Integer Number Into Digits in Java](https://www.baeldung.com/java-integer-individual-digits)
- [Java Double vs. BigDecimal](https://www.baeldung.com/java-double-vs-bigdecimal)
- More articles: [[<-- prev]](../core-java-numbers-5) - More articles: [[<-- prev]](../core-java-numbers-5)

View File

@ -25,8 +25,12 @@
<version>${commons-codec}</version> <version>${commons-codec}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>core-java-numbers-6</finalName> <finalName>core-java-numbers-6</finalName>
<resources> <resources>
@ -39,5 +43,6 @@
<properties> <properties>
<commons-codec>1.15</commons-codec> <commons-codec>1.15</commons-codec>
<guava.version>32.1.2-jre</guava.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,8 @@
package com.baeldung.bigintegerroot;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.bigintegerroot;
public class BigIntegerHolder {
private BigIntegerHolder() {
}
public static final String BIG_NUMBER = "179769313000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
public static final String VERY_BIG_NUMBER = "32473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834";
public static final String INSANELY_BIG_NUMBER = "3247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834324739274923749279342847923749237492374987230480128343247392749237492793428479237492374923749872304801283432473927492374927934284792374923749237498723048012834";
}

View File

@ -0,0 +1,60 @@
package com.baeldung.bigintegerroot;
import static com.baeldung.bigintegerroot.BigIntegerHolder.*;
import com.baeldung.bigintegerroot.algorithms.Newton;
import com.baeldung.bigintegerroot.algorithms.NewtonPlus;
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Warmup(iterations = 1)
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.MINUTES)
@Fork(1)
@State(Scope.Benchmark)
public class BigIntegerSquareRootBenchmark {
@Param({BIG_NUMBER, VERY_BIG_NUMBER, INSANELY_BIG_NUMBER})
public String number;
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void calculateRootWithJava(Blackhole blackhole) {
final BigInteger integer = new BigInteger(number);
final BigInteger root = integer.sqrt();
blackhole.consume(root);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void calculateRootWithGuava(Blackhole blackhole) {
final BigInteger integer = new BigInteger(number);
final BigInteger root = BigIntegerMath.sqrt(integer, RoundingMode.DOWN);
blackhole.consume(root);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void calculateRootWithNewtonPlus(Blackhole blackhole) {
final BigInteger integer = new BigInteger(number);
final BigInteger root = NewtonPlus.sqrt(integer);
blackhole.consume(root);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void calculateRootWithNewton(Blackhole blackhole) {
final BigInteger integer = new BigInteger(number);
final BigInteger root = Newton.sqrt(integer);
blackhole.consume(root);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.bigintegerroot.algorithms;
import java.math.BigInteger;
public class Newton {
private Newton() {
}
public static BigInteger sqrt(BigInteger n) {
// Initial approximation
BigInteger x = n.divide(BigInteger.TWO);
// Tolerance level (small positive integer)
BigInteger tolerance = BigInteger.ONE;
while (true) {
// x_new = 0.5 * (x + n / x)
BigInteger xNew = x.add(n.divide(x)).divide(BigInteger.TWO);
// Check for convergence within tolerance
if (x.subtract(xNew).abs().compareTo(tolerance) <= 0) {
return xNew;
}
x = xNew;
}
}
}

View File

@ -0,0 +1,108 @@
package com.baeldung.bigintegerroot.algorithms;
import java.math.BigInteger;
public class NewtonPlus {
private NewtonPlus() {
}
// A fast square root by Ryan Scott White.
public static BigInteger sqrt(BigInteger x) {
if (x.compareTo(BigInteger.valueOf(144838757784765629L)) < 0) {
long xAsLong = x.longValue();
long vInt = (long)Math.sqrt(xAsLong);
if (vInt * vInt > xAsLong)
vInt--;
return BigInteger.valueOf(vInt); }
double xAsDub = x.doubleValue();
BigInteger val;
if (xAsDub < 2.1267e37) // 2.12e37 largest here
// since sqrt(long.max*long.max) > long.max
{
long vInt = (long)Math.sqrt(xAsDub);
val = BigInteger.valueOf
((vInt + x.divide(BigInteger.valueOf(vInt)).longValue()) >> 1);
}
else if (xAsDub < 4.3322e127) {
// Convert a double to a BigInteger
long bits = Double.doubleToLongBits(Math.sqrt(xAsDub));
int exp = ((int) (bits >> 52) & 0x7ff) - 1075;
val = BigInteger.valueOf((bits & ((1L << 52)) - 1) | (1L << 52)).shiftLeft(exp);
val = x.divide(val).add(val).shiftRight(1);
if (xAsDub > 2e63) {
val = x.divide(val).add(val).shiftRight(1); }
}
else // handle large numbers over 4.3322e127
{
int xLen = x.bitLength();
int wantedPrecision = ((xLen + 1) / 2);
int xLenMod = xLen + (xLen & 1) + 1;
//////// Do the first Sqrt on Hardware ////////
long tempX = x.shiftRight(xLenMod - 63).longValue();
double tempSqrt1 = Math.sqrt(tempX);
long valLong = Double.doubleToLongBits(tempSqrt1) & 0x1fffffffffffffL;
if (valLong == 0)
valLong = 1L << 53;
//////// Classic Newton Iterations ////////
val = BigInteger.valueOf(valLong).shiftLeft(53 - 1)
.add((x.shiftRight(xLenMod -
(3 * 53))).divide(BigInteger.valueOf(valLong)));
int size = 106;
for (; size < 256; size <<= 1) {
val = val.shiftLeft(size - 1).add(x.shiftRight
(xLenMod - (3*size)).divide(val));}
if (xAsDub > 4e254) { // 4e254 = 1<<845.77
int numOfNewtonSteps = 31 -
Integer.numberOfLeadingZeros(wantedPrecision / size)+1;
////// Apply Starting Size ////////
int wantedSize = (wantedPrecision >> numOfNewtonSteps) + 2;
int needToShiftBy = size - wantedSize;
val = val.shiftRight(needToShiftBy);
size = wantedSize;
do {
//////// Newton Plus Iteration ////////
int shiftX = xLenMod - (3 * size);
BigInteger valSqrd = val.multiply(val).shiftLeft(size - 1);
BigInteger valSU = x.shiftRight(shiftX).subtract(valSqrd);
val = val.shiftLeft(size).add(valSU.divide(val));
size *= 2;
} while (size < wantedPrecision);
}
val = val.shiftRight(size - wantedPrecision);
}
// Detect a round ups. This function can be further optimized - see article.
// For a ~7% speed bump the following line can be removed but round-ups will occur.
if (val.multiply(val).compareTo(x) > 0)
val = val.subtract(BigInteger.ONE);
// Enabling the below will guarantee an error is stopped for larger numbers.
// Note: As of this writing, there are no known errors.
BigInteger tmp = val.multiply(val);
if (tmp.compareTo(x) > 0) {
System.out.println("val^2(" + val.multiply(val).toString()
+ ") ≥ x(" + x.toString()+")");
System.console().readLine();
//throw new Exception("Sqrt function had internal error - value too high");
}
if (tmp.add(val.shiftLeft(1)).add(BigInteger.ONE).compareTo(x) <= 0) {
System.out.println("(val+1)^2("
+ val.add(BigInteger.ONE).multiply(val.add(BigInteger.ONE)).toString()
+ ") ≥ x(" + x.toString() + ")");
System.console().readLine();
//throw new Exception("Sqrt function had internal error - value too low");
}
return val;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.bigintegerroot;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.baeldung.bigintegerroot.algorithms.Newton;
import com.baeldung.bigintegerroot.algorithms.NewtonPlus;
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.stream.Stream;
import org.apache.commons.math3.util.Pair;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class BigIntegerSquareRootUnitTest {
@ParameterizedTest
@ValueSource(strings = {
BigIntegerHolder.BIG_NUMBER,
BigIntegerHolder.VERY_BIG_NUMBER,
BigIntegerHolder.VERY_BIG_NUMBER
})
void squareRootTest(String number) {
final BigInteger bigInteger = new BigInteger(number);
final BigInteger javaRoot = bigInteger.sqrt();
final BigInteger guavaRoot = BigIntegerMath.sqrt(bigInteger, RoundingMode.DOWN);
final BigInteger newtonRoot = Newton.sqrt(bigInteger);
final BigInteger newtonPlusRoot = NewtonPlus.sqrt(bigInteger);
assertTrue(Stream.of(
new Pair<>(javaRoot, guavaRoot),
new Pair<>(guavaRoot, newtonRoot),
new Pair<>(newtonRoot, newtonPlusRoot)
).allMatch(pair -> pair.getFirst().equals(pair.getSecond())));
}
}

View File

@ -18,6 +18,18 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>${commons-lang3.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,15 @@
package com.baeldung.floatdoubleconversions;
public class FloatAndDoubleConversions {
public static void main(String args[]){
float vatRate = 14.432511f;
System.out.println("vatRate:"+vatRate);
Float localTaxRate = 20.12434f;
System.out.println("localTaxRate:"+localTaxRate);
double shootingAverage = 56.00000000000001;
System.out.println("shootingAverage:"+shootingAverage);
Double assistAverage = 81.123000000045;
System.out.println("assistAverage:"+assistAverage);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.floatdoubleconversions;
import org.junit.Assert;
import org.junit.Test;
public class FloatDoubleConversionsTest {
@Test
public void whenDoubleType_thenFloatTypeSuccess(){
double interestRatesYearly = 13.333333333333334;
float interest = (float) interestRatesYearly;
System.out.println(interest); //13.333333
Assert.assertTrue(Float.class.isInstance(interest));//true
Double monthlyRates = 2.111111111111112;
float rates = monthlyRates.floatValue();
System.out.println(rates); //2.1111112
Assert.assertTrue(Float.class.isInstance(rates));//true
}
@Test
public void whenFloatType_thenDoubleTypeSuccess(){
float gradeAverage =2.05f;
double average = gradeAverage;
System.out.println(average); //2.049999952316284
Assert.assertTrue(Double.class.isInstance(average));//true
Float monthlyRates = 2.1111112f;
Double rates = monthlyRates.doubleValue();
System.out.println(rates); //2.1111112
Assert.assertTrue(Double.class.isInstance(rates));//true
}
}

View File

@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml

View File

@ -0,0 +1,7 @@
## Core Java OS
This module contains articles about working with the operating system (OS) in Java
### Relevant Articles:

View File

@ -0,0 +1,42 @@
<?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-os</artifactId>
<name>core-java-os</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<build>
<finalName>core-java-os</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.system;
public class EnvironmentExample {
public void getUserName() {
String username = System.getenv("USERNAME");
System.out.println("User: " + username);
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.system;
public class PropertiesExample {
public void getUserName() {
String username = System.getProperty("user.name");
System.out.println("User: " + username);
}
public void getCustomProp() {
String customProperty = System.getProperty("custom.prop");
System.out.println("Custom property: " + customProperty);
}
public void getCustomPropWithFallback() {
String customProperty = System.getProperty("non-existent-property", "default value");
System.out.println("Custom property: " + customProperty);
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.system;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
public class WhenDetectingOSUnitTest {
private DetectOS os = new DetectOS();
@Test
public void whenUsingSystemProperty_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystem();
Assert.assertEquals(expected, actual);
}
@Test
public void whenUsingSystemUtils_shouldReturnOS() {
String expected = "Windows 10";
String actual = os.getOperatingSystemSystemUtils();
Assert.assertEquals(expected, actual);
}
}

View File

@ -1,64 +0,0 @@
package com.baeldung.system.exit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.security.Permission;
import static org.junit.Assert.assertEquals;
@Ignore("This test is ignored because it tests deprecated code")
public class SystemExitUnitTest {
private SecurityManager securityManager;
private SystemExitExample example;
@Before
public void setUp() {
example = new SystemExitExample();
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
@After
public void tearDown() throws Exception {
System.setSecurityManager(securityManager);
}
@Test
public void testExit() throws Exception {
try {
example.readFile();
} catch (ExitException e) {
assertEquals("Exit status", 2, e.status);
}
}
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = 1L;
public final int status;
public ExitException(int status) {
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
@Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.alphanumeric;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
@Warmup(iterations = 1)
@Measurement(iterations = 1, time = 1, timeUnit = TimeUnit.MINUTES)
@Fork(1)
public class AlphanumericPerformanceBenchmark {
private static final String TEST_STRING = "ABC123abc123";
private static final String REGEX = "[^[a-zA-Z0-9]*$]";
private static final Pattern PATTERN = Pattern.compile(REGEX);
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericRegex(Blackhole blackhole) {
final Matcher matcher = PATTERN.matcher(TEST_STRING);
boolean result = matcher.matches();
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericRegexDirectlyOnString(Blackhole blackhole) {
boolean result = TEST_STRING.matches(REGEX);
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIteration(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!isAlphanumeric(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCharacterChecks(Blackhole blackhole) {
boolean result = true;
for (int i = 0; i < TEST_STRING.length(); ++i) {
final int codePoint = TEST_STRING.codePointAt(i);
if (!Character.isAlphabetic(codePoint) || !Character.isDigit(codePoint)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithCopy(Blackhole blackhole) {
boolean result = true;
for (final char c : TEST_STRING.toCharArray()) {
if (!isAlphanumeric(c)) {
result = false;
break;
}
}
blackhole.consume(result);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void alphanumericIterationWithStream(Blackhole blackhole) {
boolean result = TEST_STRING.chars().allMatch(this::isAlphanumeric);
blackhole.consume(result);
}
public boolean isAlphanumeric(final int codePoint) {
return (codePoint >= 65 && codePoint <= 90) ||
(codePoint >= 97 && codePoint <= 172) ||
(codePoint >= 48 && codePoint <= 57);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.alphanumeric;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class AlphanumericUnitTest {
private AlphanumericPerformanceBenchmark alphanumericPerformanceBenchmark = new AlphanumericPerformanceBenchmark();
@ParameterizedTest
@CsvSource({
"A,true",
"B,true",
"C,true",
"1,true",
"2,true",
"3,true",
"!,false",
"@,false",
"#,false",
"$,false",
"%,false"
})
void shouldCorrectlyIdentifyAlphanumericCharacterTest(char character, boolean result) {
boolean actual = alphanumericPerformanceBenchmark.isAlphanumeric(character);
assertEquals(actual, result);
}
}

View File

@ -12,3 +12,4 @@ This module contains articles about string-related algorithms.
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer) - [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters) - [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)
- [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring)
- [Check if Letter Is Emoji With Java](https://www.baeldung.com/java-check-letter-emoji)

View File

@ -11,4 +11,3 @@
- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number) - [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes) - [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string) - [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
- [Replacing Single Quote with \ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)

View File

@ -10,3 +10,5 @@
- [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters) - [Check if a String Contains Non-Alphanumeric Characters](https://www.baeldung.com/java-string-test-special-characters)
- [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars) - [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars)
- [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods) - [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods)
- [Replacing Single Quote with \ in Java String](https://www.baeldung.com/java-replacing-single-quote-string)

View File

@ -28,13 +28,14 @@
<!--<module>core-java-streams-2</module> --> <!--<module>core-java-streams-2</module> -->
<!--<module>core-java-sun</module> --> <!--<module>core-java-sun</module> -->
<module>core-java-9-improvements</module> <module>core-java-9-improvements</module>
<module>core-java-collections-array-list</module>
<module>core-java-9-streams</module> <module>core-java-9-streams</module>
<module>core-java-9</module> <module>core-java-9</module>
<module>core-java-10</module> <module>core-java-10</module>
<module>core-java-11</module> <module>core-java-11</module>
<module>core-java-11-2</module> <module>core-java-11-2</module>
<module>core-java-11-3</module> <module>core-java-11-3</module>
<module>core-java-collections-array-list</module>
<module>core-java-collections-array-list-2</module>
<module>core-java-collections-list-4</module> <module>core-java-collections-list-4</module>
<module>core-java-collections-list-5</module> <module>core-java-collections-list-5</module>
<module>core-java-collections-maps-4</module> <module>core-java-collections-maps-4</module>
@ -78,6 +79,7 @@
<module>core-java-collections-list</module> <module>core-java-collections-list</module>
<module>core-java-collections-list-2</module> <module>core-java-collections-list-2</module>
<module>core-java-collections-list-3</module> <module>core-java-collections-list-3</module>
<module>core-java-collections-list-6</module>
<module>core-java-collections-maps</module> <module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module> <module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module> <module>core-java-collections-maps-3</module>
@ -108,6 +110,7 @@
<module>core-java-io-2</module> <module>core-java-io-2</module>
<module>core-java-io-3</module> <module>core-java-io-3</module>
<module>core-java-io-4</module> <module>core-java-io-4</module>
<module>core-java-io-5</module>
<module>core-java-io-apis</module> <module>core-java-io-apis</module>
<module>core-java-io-apis-2</module> <module>core-java-io-apis-2</module>
<module>core-java-io-conversions</module> <module>core-java-io-conversions</module>

View File

@ -12,6 +12,7 @@
<groupId>org.jenkins-ci.plugins</groupId> <groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId> <artifactId>plugin</artifactId>
<version>2.33</version> <version>2.33</version>
<relativePath/>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -4,3 +4,4 @@
- [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders) - [A Guide to Rolling File Appenders](http://www.baeldung.com/java-logging-rolling-file-appenders)
- [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions) - [Logging Exceptions Using SLF4J](https://www.baeldung.com/slf4j-log-exceptions)
- [Log4j Warning: “No Appenders Could Be Found for Logger”](https://www.baeldung.com/log4j-no-appenders-found) - [Log4j Warning: “No Appenders Could Be Found for Logger”](https://www.baeldung.com/log4j-no-appenders-found)
- [A Guide to Log4j and the log4j.properties File in Java](https://www.baeldung.com/java-log4j-properties-guide)

View File

@ -9,3 +9,4 @@
- [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins) - [Log4j 2 Plugins](https://www.baeldung.com/log4j2-plugins)
- [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info) - [Printing Thread Info in Log File Using Log4j2](https://www.baeldung.com/log4j2-print-thread-info)
- [Log4j2 Logging to Both File and Console](https://www.baeldung.com/java-log4j2-file-and-console) - [Log4j2 Logging to Both File and Console](https://www.baeldung.com/java-log4j2-file-and-console)
- [Log4j 2 Configuration Using a Properties File](https://www.baeldung.com/java-log4j2-config-with-prop-file)

View File

@ -17,30 +17,39 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-core</artifactId> <artifactId>camel-spring-boot-starter</artifactId>
<version>${env.camel.version}</version> <version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-starter</artifactId>
<version>${camel.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.apache.camel</groupId>
<artifactId>camel-spring-javaconfig</artifactId> <artifactId>camel-test-spring-junit5</artifactId>
<version>${env.camel.version}</version> <version>${camel.version}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.junit.platform</groupId>
<artifactId>camel-jackson</artifactId> <artifactId>junit-platform-launcher</artifactId>
<version>${env.camel.version}</version> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.camel</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>camel-test</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<version>${env.camel.version}</version> </dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<properties> <properties>
<env.camel.version>3.14.7</env.camel.version> <camel.version>3.21.0</camel.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,11 @@
package com.baeldung.camel.apache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -5,14 +5,17 @@ import java.util.Date;
import org.apache.camel.Exchange; import org.apache.camel.Exchange;
import org.apache.camel.Processor; import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
@Component
public class FileProcessor implements Processor { public class FileProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception { public void process(Exchange exchange) throws Exception {
String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class); String originalFileName = (String) exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
Date date = new Date(); Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String changedFileName = dateFormat.format(date) + originalFileName; String changedFileName = dateFormat.format(date) + originalFileName;
exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName); exchange.getIn().setHeader(Exchange.FILE_NAME, changedFileName);
} }

View File

@ -1,7 +1,9 @@
package com.baeldung.camel.apache.file; package com.baeldung.camel.apache.file;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
@Component
public class FileRouter extends RouteBuilder { public class FileRouter extends RouteBuilder {
private static final String SOURCE_FOLDER = "src/test/source-folder"; private static final String SOURCE_FOLDER = "src/test/source-folder";

View File

@ -1,11 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean id="fileRouter" class="com.baeldung.camel.apache.file.FileRouter" /> <context:component-scan base-package="com.baeldung.camel.apache"/>
<bean id="fileProcessor" class="com.baeldung.camel.apache.file.FileProcessor" /> <context:annotation-config />
<camelContext xmlns="http://camel.apache.org/schema/spring"> <camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="fileRouter" /> <routeBuilder ref="fileRouter" />

View File

@ -1,31 +1,65 @@
package com.apache.baeldung.camel.jackson; package com.apache.baeldung.camel.jackson;
import com.baeldung.camel.apache.Application;
import com.baeldung.camel.apache.jackson.Fruit;
import org.apache.camel.Configuration;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.ListJacksonDataFormat;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.annotation.DirtiesContext;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.apache.camel.builder.RouteBuilder; import static org.springframework.test.util.AssertionErrors.assertEquals;
import org.apache.camel.component.jackson.ListJacksonDataFormat; import static org.springframework.test.util.AssertionErrors.assertNotNull;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import com.baeldung.camel.apache.jackson.Fruit; @CamelSpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@SpringBootTest(classes = {Application.class, FruitArrayJacksonUnmarshalUnitTest.TestConfig.class})
public class FruitArrayJacksonUnmarshalUnitTest {
public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport { @Autowired
private ProducerTemplate template;
@EndpointInject("mock:marshalledObject")
private MockEndpoint mock;
@Configuration
static class TestConfig {
@Bean
RoutesBuilder route() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new ListJacksonDataFormat(Fruit.class))
.to("mock:marshalledObject");
}
};
}
}
@Test @Test
public void givenJsonFruitArray_whenUnmarshalled_thenSuccess() throws Exception { public void givenJsonFruitArray_whenUnmarshalled_thenSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:marshalledObject"); mock.setExpectedMessageCount(1);
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(List.class); mock.message(0).body().isInstanceOf(List.class);
String json = readJsonFromFile("/json/fruit-array.json"); String json = readJsonFromFile("/json/fruit-array.json");
template.sendBody("direct:jsonInput", json); template.sendBody("direct:jsonInput", json);
assertMockEndpointsSatisfied(); mock.assertIsSatisfied();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Fruit> fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(List.class); List<Fruit> fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(List.class);
@ -42,21 +76,9 @@ public class FruitArrayJacksonUnmarshalUnitTest extends CamelTestSupport {
assertEquals("Fruit id", 101, fruit.getId()); assertEquals("Fruit id", 101, fruit.getId());
} }
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new ListJacksonDataFormat(Fruit.class))
.to("mock:marshalledObject");
}
};
}
private String readJsonFromFile(String path) throws URISyntaxException, IOException { private String readJsonFromFile(String path) throws URISyntaxException, IOException {
URL resource = FruitArrayJacksonUnmarshalUnitTest.class.getResource(path); URL resource = FruitArrayJacksonUnmarshalUnitTest.class.getResource(path);
return new String(Files.readAllBytes(Paths.get(resource.toURI()))); return new String(Files.readAllBytes(Paths.get(resource.toURI())), StandardCharsets.UTF_8);
} }
} }

View File

@ -1,32 +1,64 @@
package com.apache.baeldung.camel.jackson; package com.apache.baeldung.camel.jackson;
import com.baeldung.camel.apache.Application;
import com.baeldung.camel.apache.jackson.Fruit;
import com.baeldung.camel.apache.jackson.FruitList;
import org.apache.camel.Configuration;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.apache.camel.builder.RouteBuilder; import static org.springframework.test.util.AssertionErrors.assertEquals;
import org.apache.camel.component.jackson.JacksonDataFormat; import static org.springframework.test.util.AssertionErrors.assertNotNull;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import com.baeldung.camel.apache.jackson.Fruit; @CamelSpringBootTest
import com.baeldung.camel.apache.jackson.FruitList; @SpringBootTest(classes = {Application.class, FruitListJacksonUnmarshalUnitTest.TestConfig.class})
public class FruitListJacksonUnmarshalUnitTest {
public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport { @Autowired
private ProducerTemplate template;
@EndpointInject("mock:marshalledObject")
private MockEndpoint mock;
@Configuration
static class TestConfig {
@Bean
RoutesBuilder route() {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new JacksonDataFormat(FruitList.class))
.to("mock:marshalledObject");
}
};
}
}
@Test @Test
public void givenJsonFruitList_whenUnmarshalled_thenSuccess() throws Exception { public void givenJsonFruitList_whenUnmarshalled_thenSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:marshalledObject"); mock.setExpectedMessageCount(1);
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(FruitList.class); mock.message(0).body().isInstanceOf(FruitList.class);
String json = readJsonFromFile("/json/fruit-list.json"); String json = readJsonFromFile("/json/fruit-list.json");
template.sendBody("direct:jsonInput", json); template.sendBody("direct:jsonInput", json);
assertMockEndpointsSatisfied(); mock.assertIsSatisfied();
FruitList fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(FruitList.class); FruitList fruitList = mock.getReceivedExchanges().get(0).getIn().getBody(FruitList.class);
assertNotNull("Fruit lists should not be null", fruitList); assertNotNull("Fruit lists should not be null", fruitList);
@ -43,20 +75,9 @@ public class FruitListJacksonUnmarshalUnitTest extends CamelTestSupport {
assertEquals("Fruit id", 101, fruit.getId()); assertEquals("Fruit id", 101, fruit.getId());
} }
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:jsonInput").unmarshal(new JacksonDataFormat(FruitList.class))
.to("mock:marshalledObject");
}
};
}
private String readJsonFromFile(String path) throws URISyntaxException, IOException { private String readJsonFromFile(String path) throws URISyntaxException, IOException {
URL resource = FruitListJacksonUnmarshalUnitTest.class.getResource(path); URL resource = FruitListJacksonUnmarshalUnitTest.class.getResource(path);
return new String(Files.readAllBytes(Paths.get(resource.toURI()))); return new String(Files.readAllBytes(Paths.get(resource.toURI())), StandardCharsets.UTF_8);
} }
} }

View File

@ -1,16 +1,21 @@
package com.apache.camel.file.processor; package com.apache.camel.file.processor;
import java.io.File; import com.baeldung.camel.apache.file.FileProcessor;
import org.apache.camel.CamelContext; import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.DefaultCamelContext;
import org.awaitility.Awaitility;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.baeldung.camel.apache.file.FileProcessor; import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class FileProcessorIntegrationTest { public class FileProcessorIntegrationTest {
@ -52,7 +57,7 @@ public class FileProcessorIntegrationTest {
} }
@Test @Test
public void moveFolderContentJavaDSLTest() throws Exception { public void givenJavaDSLRoute_whenCamelStart_thenMoveFolderContent() throws Exception {
final CamelContext camelContext = new DefaultCamelContext(); final CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new RouteBuilder() { camelContext.addRoutes(new RouteBuilder() {
@Override @Override
@ -61,15 +66,26 @@ public class FileProcessorIntegrationTest {
} }
}); });
camelContext.start(); camelContext.start();
Thread.sleep(DURATION_MILIS); verifyFolderContent();
camelContext.stop(); camelContext.stop();
} }
@Test @Test
public void moveFolderContentSpringDSLTest() throws InterruptedException { public void givenSpringDSLRoute_whenCamelStart_thenMoveFolderContent() throws InterruptedException {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml"); ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("camel-context-test.xml");
Thread.sleep(DURATION_MILIS); verifyFolderContent();
applicationContext.close(); applicationContext.close();
}
private void verifyFolderContent() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
File destinationFile1 = new File(DESTINATION_FOLDER + "/" + dateFormat.format(date) + "File1.txt");
File destinationFile2 = new File(DESTINATION_FOLDER + "/" + dateFormat.format(date) + "File2.txt");
Awaitility.await().atMost(DURATION_MILIS, TimeUnit.MILLISECONDS).untilAsserted(() -> {
assertThat(destinationFile1.exists()).isTrue();
assertThat(destinationFile2.exists()).isTrue();
});
} }
} }

View File

@ -7,6 +7,7 @@
<artifactId>micronaut</artifactId> <artifactId>micronaut</artifactId>
<version>0.1</version> <version>0.1</version>
<name>micronaut</name> <name>micronaut</name>
<packaging>${packaging}</packaging>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
@ -18,7 +19,7 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>bom</artifactId> <artifactId>micronaut-bom</artifactId>
<version>${micronaut.version}</version> <version>${micronaut.version}</version>
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
@ -29,120 +30,136 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>http-client</artifactId> <artifactId>micronaut-runtime</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-client</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>http-server-netty</artifactId> <artifactId>micronaut-http-server-netty</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>inject</artifactId> <artifactId>micronaut-inject</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>runtime</artifactId> <artifactId>micronaut-validation</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${annotation.api.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>inject-java</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.projectreactor</groupId> <groupId>io.micronaut.rxjava3</groupId>
<artifactId>reactor-core</artifactId> <artifactId>micronaut-rxjava3</artifactId>
<version>${reactor.version}</version> <scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut.rxjava3</groupId>
<artifactId>micronaut-rxjava3-http-client</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.micronaut.serde</groupId>
<artifactId>micronaut-serde-jackson</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.micronaut.test</groupId>
<artifactId>micronaut-test-junit5</artifactId>
<scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>io.micronaut.build</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>micronaut-maven-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${exec.mainClass}</mainClass>
</transformer>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
</transformers>
</configuration>
</execution>
</executions>
</plugin> </plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath/>
<argument>${exec.mainClass}</argument>
</arguments>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.plugin.version}</version>
<configuration> <configuration>
<source>${jdk.version}</source> <source>${jdk.version}</source>
<target>${jdk.version}</target> <target>${jdk.version}</target>
<compilerArgs> <compilerArgs>
<arg>-parameters</arg> <arg>-parameters</arg>
</compilerArgs> </compilerArgs>
<annotationProcessorPaths> <!-- Uncomment to enable incremental compilation -->
<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->
<annotationProcessorPaths combine.self="append">
<path> <path>
<groupId>io.micronaut</groupId> <groupId>io.micronaut</groupId>
<artifactId>inject-java</artifactId> <artifactId>micronaut-inject-java</artifactId>
<version>${micronaut.version}</version>
</path>
<path>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-http-validation</artifactId>
<version>${micronaut.version}</version> <version>${micronaut.version}</version>
</path> </path>
</annotationProcessorPaths> </annotationProcessorPaths>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${shade.plugin.version}</version>
<executions>
<execution>
<id>default-shade</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</pluginManagement>
</build> </build>
<properties> <properties>
<!-- <exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass> --> <!-- <exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass> -->
<exec.mainClass>com.baeldung.micronaut.vs.springboot.CompareApplication</exec.mainClass> <exec.mainClass>com.baeldung.micronaut.vs.springboot.CompareApplication</exec.mainClass>
<micronaut.version>1.0.0.RC2</micronaut.version> <micronaut.version>3.10.1</micronaut.version>
<jdk.version>17</jdk.version> <jdk.version>17</jdk.version>
<annotation.api.version>1.3.2</annotation.api.version> <release.version>17</release.version>
<reactor.version>3.1.6.RELEASE</reactor.version> <packaging>jar</packaging>
<compiler.plugin.version>3.7.0</compiler.plugin.version> <compiler.plugin.version>3.7.0</compiler.plugin.version>
<shade.plugin.version>3.1.0</shade.plugin.version> <micronaut.runtime>netty</micronaut.runtime>
<shade.plugin.version>3.2.0</shade.plugin.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,42 @@
package com.baeldung.micronaut.apiversioning.custom.client;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.async.annotation.SingleResult;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.rxjava3.core.Flowable;
@Client("/")
@Header(name = HttpHeaders.ACCEPT, value = "application/json")
public interface BirdCountClient {
@Get(
uri = "/bird/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@Header(name = "api-key", value = "11")
@SingleResult
Flowable<String> countV1(@QueryValue("max") @Nullable Integer max);
@Get(
uri = "/bird/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@Header(name = "api-key", value = "10")
@SingleResult
Flowable<String> countV2(@QueryValue("max") @Nullable Integer max);
@Get(
uri = "/bird/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@Header(name = "api-key", value = "")
@SingleResult
Flowable<String> countDefault(@QueryValue("max") @Nullable Integer max);
}

View File

@ -0,0 +1,36 @@
package com.baeldung.micronaut.apiversioning.custom.server;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.version.annotation.Version;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import io.reactivex.rxjava3.core.Flowable;
import java.util.stream.Stream;
@Controller("/bird")
public class BirdCountController {
@Get(value = "/count", produces = {"application/json"})
@Version("1")
public Flowable<String> countV1(@QueryValue("max") @Nullable Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Bird " + index)
.limit(max == null ? 10 : max)
);
}
@Get(value = "/count", produces = {"application/json"})
@Version("2")
public Flowable<String> countV2(@QueryValue("max") @NonNull Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Bird " + index)
.limit(max)
);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.micronaut.apiversioning.custom.server;
import io.micronaut.context.annotation.Requires;
import io.micronaut.context.annotation.Value;
import io.micronaut.http.HttpRequest;
import io.micronaut.web.router.version.resolution.RequestVersionResolver;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.util.Optional;
@Singleton
@Requires(property = "my.router.versioning.enabled", value = "true")
public class CustomVersionResolver implements RequestVersionResolver {
@Inject
@Value("${micronaut.router.versioning.default-version}")
private String defaultVersion;
@Override
public Optional<String> resolve(HttpRequest<?> request) {
var apiKey = Optional.ofNullable(request.getHeaders().get("api-key"));
if (apiKey.isPresent() && !apiKey.get().isEmpty()) {
return Optional.of(Integer.parseInt(apiKey.get()) % 2 == 0 ? "2" : "1");
}
return Optional.of(defaultVersion);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.micronaut.apiversioning.header.client;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.async.annotation.SingleResult;
import io.micronaut.core.version.annotation.Version;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.rxjava3.core.Flowable;
@Client("/")
@Header(name = HttpHeaders.ACCEPT, value = "application/json")
public interface DogCountClient {
@Get(
uri = "/dog/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@Version("1")
@SingleResult
Flowable<String> countV1(@QueryValue("max") @Nullable Integer max);
@Get(
uri = "/dog/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@Version("2")
@SingleResult
Flowable<String> countV2(@QueryValue("max") @Nullable Integer max);
@Get(
uri = "/dog/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@SingleResult
Flowable<String> countDefault(@QueryValue("max") @Nullable Integer max);
}

View File

@ -0,0 +1,36 @@
package com.baeldung.micronaut.apiversioning.header.server;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.version.annotation.Version;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import io.reactivex.rxjava3.core.Flowable;
import java.util.stream.Stream;
@Controller("/dog")
public class DogCountController {
@Get(value = "/count", produces = {"application/json"})
@Version("1")
public Flowable<String> countV1(@QueryValue("max") @Nullable Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Dog " + index)
.limit(max == null ? 10 : max)
);
}
@Get(value = "/count", produces = {"application/json"})
@Version("2")
public Flowable<String> countV2(@QueryValue("max") @NonNull Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Dog " + index)
.limit(max)
);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.micronaut.apiversioning.param.client;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.async.annotation.SingleResult;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.http.client.annotation.Client;
import io.reactivex.rxjava3.core.Flowable;
@Client("/")
@Header(name = HttpHeaders.ACCEPT, value = "application/json")
public interface CatCountClient {
@Get(
uri = "/cat/count",
consumes = {"application/json"},
produces = {"application/json"}
)
@SingleResult
Flowable<String> count(@QueryValue("max") @Nullable Integer max, @QueryValue(value = "v", defaultValue = "1") @Nullable Integer version);
}

View File

@ -0,0 +1,37 @@
package com.baeldung.micronaut.apiversioning.param.server;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.version.annotation.Version;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import io.reactivex.rxjava3.core.Flowable;
import java.util.stream.Stream;
@Controller("/cat")
public class CatCountController {
@Get(value = "/count", produces = {"application/json"})
@Version("1")
public Flowable<String> countV1(@QueryValue("max") @Nullable Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Cat " + index)
.limit(max == null ? 10 : max)
);
}
@Get(value = "/count", produces = {"application/json"})
@Version("2")
public Flowable<String> countV2(@QueryValue("max") @NonNull Integer max) {
return Flowable.fromStream(
Stream.iterate(0, i -> i + 1)
.map(index -> "Cat " + index)
.limit(max)
);
}
}

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