Merge branch 'eugenp:master' into master
This commit is contained in:
commit
b62cf9c77c
|
@ -5,4 +5,5 @@
|
||||||
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
|
||||||
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
- [Calculate Distance Between Two Coordinates in Java](https://www.baeldung.com/java-find-distance-between-points)
|
||||||
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
- [Rotate Arrays in Java](https://www.baeldung.com/java-rotate-arrays)
|
||||||
|
- [Find Missing Number From a Given Array in Java](https://www.baeldung.com/java-array-find-missing-number)
|
||||||
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
|
||||||
|
|
|
@ -0,0 +1,153 @@
|
||||||
|
package com.baeldung.algorithms.weightedaverage;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.BiConsumer;
|
||||||
|
import java.util.function.BinaryOperator;
|
||||||
|
import java.util.function.Function;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import java.util.stream.Collector;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class WeightedAverageUnitTest {
|
||||||
|
|
||||||
|
private List<Values> values = Arrays.asList(
|
||||||
|
new Values(1, 10),
|
||||||
|
new Values(3, 20),
|
||||||
|
new Values(5, 30),
|
||||||
|
new Values(7, 50),
|
||||||
|
new Values(9, 40)
|
||||||
|
);
|
||||||
|
|
||||||
|
private Double expected = 6.2;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void twoPass() {
|
||||||
|
double top = values.stream()
|
||||||
|
.mapToDouble(v -> v.value * v.weight)
|
||||||
|
.sum();
|
||||||
|
double bottom = values.stream()
|
||||||
|
.mapToDouble(v -> v.weight)
|
||||||
|
.sum();
|
||||||
|
|
||||||
|
double result = top / bottom;
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void onePass() {
|
||||||
|
double top = 0;
|
||||||
|
double bottom = 0;
|
||||||
|
|
||||||
|
for (Values v : values) {
|
||||||
|
top += (v.value * v.weight);
|
||||||
|
bottom += v.weight;
|
||||||
|
}
|
||||||
|
|
||||||
|
double result = top / bottom;
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void expanding() {
|
||||||
|
double result = values.stream()
|
||||||
|
.flatMap(v -> Collections.nCopies(v.weight, v.value).stream())
|
||||||
|
.mapToInt(v -> v)
|
||||||
|
.average()
|
||||||
|
.getAsDouble();
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void reduce() {
|
||||||
|
class WeightedAverage {
|
||||||
|
final double top;
|
||||||
|
final double bottom;
|
||||||
|
|
||||||
|
public WeightedAverage(double top, double bottom) {
|
||||||
|
this.top = top;
|
||||||
|
this.bottom = bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
double average() {
|
||||||
|
return top / bottom;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
double result = values.stream()
|
||||||
|
.reduce(new WeightedAverage(0, 0),
|
||||||
|
(acc, next) -> new WeightedAverage(
|
||||||
|
acc.top + (next.value * next.weight),
|
||||||
|
acc.bottom + next.weight),
|
||||||
|
(left, right) -> new WeightedAverage(
|
||||||
|
left.top + right.top,
|
||||||
|
left.bottom + right.bottom))
|
||||||
|
.average();
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void customCollector() {
|
||||||
|
class WeightedAverage implements Collector<Values, WeightedAverage.RunningTotals, Double> {
|
||||||
|
class RunningTotals {
|
||||||
|
double top;
|
||||||
|
double bottom;
|
||||||
|
|
||||||
|
public RunningTotals() {
|
||||||
|
this.top = 0;
|
||||||
|
this.bottom = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Supplier<RunningTotals> supplier() {
|
||||||
|
return RunningTotals::new;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BiConsumer<RunningTotals, Values> accumulator() {
|
||||||
|
return (current, next) -> {
|
||||||
|
current.top += (next.value * next.weight);
|
||||||
|
current.bottom += next.weight;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public BinaryOperator<RunningTotals> combiner() {
|
||||||
|
return (left, right) -> {
|
||||||
|
left.top += right.top;
|
||||||
|
left.bottom += right.bottom;
|
||||||
|
|
||||||
|
return left;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Function<RunningTotals, Double> finisher() {
|
||||||
|
return rt -> rt.top / rt.bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Set<Characteristics> characteristics() {
|
||||||
|
return Collections.singleton(Characteristics.UNORDERED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
double result = values.stream()
|
||||||
|
.collect(new WeightedAverage());
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class Values {
|
||||||
|
int value;
|
||||||
|
int weight;
|
||||||
|
|
||||||
|
public Values(int value, int weight) {
|
||||||
|
this.value = value;
|
||||||
|
this.weight = weight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -15,3 +15,4 @@ You can build the project from the command line using: *mvn clean install*, or i
|
||||||
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)
|
- [bootstrap-server in Kafka Configuration](https://www.baeldung.com/java-kafka-bootstrap-server)
|
||||||
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
|
- [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka)
|
||||||
- [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering)
|
- [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering)
|
||||||
|
- [Read Multiple Messages with Apache Kafka](https://www.baeldung.com/kafka-read-multiple-messages)
|
||||||
|
|
|
@ -76,7 +76,7 @@
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<poi.version>5.2.3</poi.version>
|
<poi.version>5.2.5</poi.version>
|
||||||
<poiji.version>4.1.1</poiji.version>
|
<poiji.version>4.1.1</poiji.version>
|
||||||
<fastexcel.version>0.15.7</fastexcel.version>
|
<fastexcel.version>0.15.7</fastexcel.version>
|
||||||
<jxl.version>2.6.12</jxl.version>
|
<jxl.version>2.6.12</jxl.version>
|
||||||
|
|
|
@ -0,0 +1,53 @@
|
||||||
|
package com.baeldung.poi.rowstyle;
|
||||||
|
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import org.apache.poi.ss.usermodel.Cell;
|
||||||
|
import org.apache.poi.ss.usermodel.CellStyle;
|
||||||
|
import org.apache.poi.ss.usermodel.Font;
|
||||||
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
|
import org.apache.poi.ss.usermodel.Sheet;
|
||||||
|
import org.apache.poi.ss.usermodel.Workbook;
|
||||||
|
|
||||||
|
public class PoiUtils {
|
||||||
|
|
||||||
|
private PoiUtils() {
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void newCell(Row row, String value) {
|
||||||
|
short cellNum = row.getLastCellNum();
|
||||||
|
if (cellNum == -1)
|
||||||
|
cellNum = 0;
|
||||||
|
|
||||||
|
Cell cell = row.createCell(cellNum);
|
||||||
|
cell.setCellValue(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Row newRow(Sheet sheet, String... rowValues) {
|
||||||
|
Row row = sheet.createRow(sheet.getLastRowNum() + 1);
|
||||||
|
|
||||||
|
for (String value : rowValues) {
|
||||||
|
newCell(row, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static CellStyle boldFontStyle(Workbook workbook) {
|
||||||
|
Font boldFont = workbook.createFont();
|
||||||
|
boldFont.setBold(true);
|
||||||
|
|
||||||
|
CellStyle boldStyle = workbook.createCellStyle();
|
||||||
|
boldStyle.setFont(boldFont);
|
||||||
|
|
||||||
|
return boldStyle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void write(Workbook workbook, Path path) throws IOException {
|
||||||
|
try (FileOutputStream fileOut = new FileOutputStream(path.toFile())) {
|
||||||
|
workbook.write(fileOut);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,150 @@
|
||||||
|
package com.baeldung.poi.rowstyle;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
|
||||||
|
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||||
|
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||||
|
import org.apache.poi.ss.usermodel.CellStyle;
|
||||||
|
import org.apache.poi.ss.usermodel.Row;
|
||||||
|
import org.apache.poi.ss.usermodel.Sheet;
|
||||||
|
import org.apache.poi.ss.usermodel.Workbook;
|
||||||
|
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class PoiBoldStyleIntegrationTest {
|
||||||
|
|
||||||
|
private void writeSampleSheet(Path destination, Workbook workbook) throws IOException {
|
||||||
|
Sheet sheet = workbook.createSheet();
|
||||||
|
CellStyle boldStyle = PoiUtils.boldFontStyle(workbook);
|
||||||
|
|
||||||
|
Row header = PoiUtils.newRow(sheet, "Name", "Value", "Details");
|
||||||
|
header.setRowStyle(boldStyle);
|
||||||
|
|
||||||
|
PoiUtils.newRow(sheet, "Albert", "A", "First");
|
||||||
|
PoiUtils.newRow(sheet, "Jane", "B", "Second");
|
||||||
|
PoiUtils.newRow(sheet, "Zack", "C", "Third");
|
||||||
|
|
||||||
|
PoiUtils.write(workbook, destination);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void assertRowStyleAppliedAndDefaultCellStylesDontMatch(Path sheetFile) throws IOException, InvalidFormatException {
|
||||||
|
try (Workbook workbook = new XSSFWorkbook(sheetFile.toFile())) {
|
||||||
|
Sheet sheet = workbook.getSheetAt(0);
|
||||||
|
Row row0 = sheet.getRow(0);
|
||||||
|
|
||||||
|
XSSFCellStyle rowStyle = (XSSFCellStyle) row0.getRowStyle();
|
||||||
|
assertTrue(rowStyle.getFont()
|
||||||
|
.getBold());
|
||||||
|
|
||||||
|
row0.forEach(cell -> {
|
||||||
|
XSSFCellStyle style = (XSSFCellStyle) cell.getCellStyle();
|
||||||
|
assertNotEquals(rowStyle, style);
|
||||||
|
});
|
||||||
|
|
||||||
|
Row row1 = sheet.getRow(1);
|
||||||
|
XSSFCellStyle row1Style = (XSSFCellStyle) row1.getRowStyle();
|
||||||
|
assertNull(row1Style);
|
||||||
|
|
||||||
|
Files.delete(sheetFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenXssfWorkbook_whenSetRowStyle1stRow_thenOnly1stRowStyled() throws IOException, InvalidFormatException {
|
||||||
|
Path sheetFile = Files.createTempFile("xssf-row-style", ".xlsx");
|
||||||
|
|
||||||
|
try (Workbook workbook = new XSSFWorkbook()) {
|
||||||
|
writeSampleSheet(sheetFile, workbook);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertRowStyleAppliedAndDefaultCellStylesDontMatch(sheetFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSxssfWorkbook_whenSetRowStyle_thenOnly1stRowStyled() throws IOException, InvalidFormatException {
|
||||||
|
Path sheetFile = Files.createTempFile("sxssf-row-style", ".xlsx");
|
||||||
|
|
||||||
|
try (Workbook workbook = new SXSSFWorkbook()) {
|
||||||
|
writeSampleSheet(sheetFile, workbook);
|
||||||
|
}
|
||||||
|
|
||||||
|
assertRowStyleAppliedAndDefaultCellStylesDontMatch(sheetFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenHssfWorkbook_whenSetRowStyle_thenOnly1stRowStyled() throws IOException {
|
||||||
|
Path sheetFile = Files.createTempFile("hssf-row-style", ".xls");
|
||||||
|
|
||||||
|
try (Workbook workbook = new HSSFWorkbook()) {
|
||||||
|
writeSampleSheet(sheetFile, workbook);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Workbook workbook = new HSSFWorkbook(Files.newInputStream(sheetFile))) {
|
||||||
|
Sheet sheet = workbook.getSheetAt(0);
|
||||||
|
Row row0 = sheet.getRow(0);
|
||||||
|
|
||||||
|
HSSFCellStyle rowStyle = (HSSFCellStyle) row0.getRowStyle();
|
||||||
|
assertTrue(rowStyle.getFont(workbook)
|
||||||
|
.getBold());
|
||||||
|
|
||||||
|
row0.forEach(cell -> {
|
||||||
|
HSSFCellStyle style = (HSSFCellStyle) cell.getCellStyle();
|
||||||
|
assertNotEquals(rowStyle, style);
|
||||||
|
});
|
||||||
|
|
||||||
|
Row row1 = sheet.getRow(1);
|
||||||
|
HSSFCellStyle row1Style = (HSSFCellStyle) row1.getRowStyle();
|
||||||
|
assertNull(row1Style);
|
||||||
|
|
||||||
|
Files.delete(sheetFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenXssfWorkbook_whenSetCellStyleForEachRow_thenAllCellsContainStyle() throws IOException, InvalidFormatException {
|
||||||
|
Path sheetFile = Files.createTempFile("xssf-cell-style", ".xlsx");
|
||||||
|
|
||||||
|
try (Workbook workbook = new XSSFWorkbook()) {
|
||||||
|
Sheet sheet = workbook.createSheet();
|
||||||
|
CellStyle boldStyle = PoiUtils.boldFontStyle(workbook);
|
||||||
|
|
||||||
|
Row header = PoiUtils.newRow(sheet, "Name", "Value", "Details");
|
||||||
|
header.forEach(cell -> cell.setCellStyle(boldStyle));
|
||||||
|
|
||||||
|
PoiUtils.newRow(sheet, "Albert", "A", "First");
|
||||||
|
PoiUtils.newRow(sheet, "Jane", "B", "Second");
|
||||||
|
PoiUtils.newRow(sheet, "Zack", "C", "Third");
|
||||||
|
|
||||||
|
PoiUtils.write(workbook, sheetFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
try (Workbook workbook = new XSSFWorkbook(sheetFile.toFile())) {
|
||||||
|
Sheet sheet = workbook.getSheetAt(0);
|
||||||
|
Row row0 = sheet.getRow(0);
|
||||||
|
|
||||||
|
XSSFCellStyle rowStyle = (XSSFCellStyle) row0.getRowStyle();
|
||||||
|
assertNull(rowStyle);
|
||||||
|
|
||||||
|
row0.forEach(cell -> {
|
||||||
|
XSSFCellStyle style = (XSSFCellStyle) cell.getCellStyle();
|
||||||
|
assertTrue(style.getFont()
|
||||||
|
.getBold());
|
||||||
|
});
|
||||||
|
|
||||||
|
Row row1 = sheet.getRow(1);
|
||||||
|
rowStyle = (XSSFCellStyle) row1.getRowStyle();
|
||||||
|
assertNull(rowStyle);
|
||||||
|
|
||||||
|
Files.delete(sheetFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
package com.baeldung.jfrview;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class JFRExample {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
JFRExample se = new JFRExample();
|
||||||
|
se.insertToList(new ArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void insertToList(List<Object> list) {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
list.add(new Object());
|
||||||
|
}
|
||||||
|
} catch (OutOfMemoryError e) {
|
||||||
|
System.out.println("Out of Memory. Exiting");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -9,4 +9,6 @@
|
||||||
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
|
- [Round the Date in Java](https://www.baeldung.com/java-round-the-date)
|
||||||
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
- [Representing Furthest Possible Date in Java](https://www.baeldung.com/java-date-represent-max)
|
||||||
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
- [Retrieving Unix Time in Java](https://www.baeldung.com/java-retrieve-unix-time)
|
||||||
|
- [Calculate Months Between Two Dates in Java](https://www.baeldung.com/java-months-difference-two-dates)
|
||||||
|
- [Format LocalDate to ISO 8601 With T and Z](https://www.baeldung.com/java-format-localdate-iso-8601-t-z)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.daterangeoverlap;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.joda.time.Interval;
|
||||||
|
|
||||||
|
public class DateRangeOverlapChecker {
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingCalendarAndDuration(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
|
||||||
|
long overlap = Math.min(end1.getTimeInMillis(), end2.getTimeInMillis()) - Math.max(start1.getTimeInMillis(), start2.getTimeInMillis());
|
||||||
|
return overlap >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingLocalDateAndDuration(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
|
||||||
|
long overlap = Math.min(end1.toEpochDay(), end2.toEpochDay()) - Math.max(start1.toEpochDay(), start2.toEpochDay());
|
||||||
|
return overlap >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingJodaTime(DateTime start1, DateTime end1, DateTime start2, DateTime end2) {
|
||||||
|
Interval interval1 = new Interval(start1, end1);
|
||||||
|
Interval interval2 = new Interval(start2, end2);
|
||||||
|
return interval1.overlaps(interval2);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingCalendarAndCondition(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
|
||||||
|
return !(end1.before(start2) || start1.after(end2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingLocalDateAndCondition(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
|
||||||
|
return !(end1.isBefore(start2) || start1.isAfter(end2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingCalendarAndFindMin(Calendar start1, Calendar end1, Calendar start2, Calendar end2) {
|
||||||
|
long overlap1 = Math.min(end1.getTimeInMillis() - start1.getTimeInMillis(), end1.getTimeInMillis() - start2.getTimeInMillis());
|
||||||
|
long overlap2 = Math.min(end2.getTimeInMillis() - start2.getTimeInMillis(), end2.getTimeInMillis() - start1.getTimeInMillis());
|
||||||
|
return Math.min(overlap1, overlap2) / (24 * 60 * 60 * 1000) >= 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isOverlapUsingLocalDateAndFindMin(LocalDate start1, LocalDate end1, LocalDate start2, LocalDate end2) {
|
||||||
|
long overlap1 = Math.min(end1.toEpochDay() - start1.toEpochDay(), end1.toEpochDay() - start2.toEpochDay());
|
||||||
|
long overlap2 = Math.min(end2.toEpochDay() - start2.toEpochDay(), end2.toEpochDay() - start1.toEpochDay());
|
||||||
|
return Math.min(overlap1, overlap2) >= 0;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,158 @@
|
||||||
|
package com.baeldung.daterangeoverlap;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class DateRangeOverlapCheckerUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPartialOverlappingRanges_thenReturnsTrue() {
|
||||||
|
Calendar start1 = Calendar.getInstance();
|
||||||
|
start1.set(2024, 11, 15);
|
||||||
|
Calendar end1 = Calendar.getInstance();
|
||||||
|
end1.set(2024, 11, 20);
|
||||||
|
|
||||||
|
Calendar start2 = Calendar.getInstance();
|
||||||
|
start2.set(2024, 11, 18);
|
||||||
|
Calendar end2 = Calendar.getInstance();
|
||||||
|
end2.set(2024, 11, 22);
|
||||||
|
|
||||||
|
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
|
||||||
|
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
|
||||||
|
|
||||||
|
LocalDate startLD2 = LocalDate.of(2024, 12, 18);
|
||||||
|
LocalDate endLD2 = LocalDate.of(2024, 12, 22);
|
||||||
|
|
||||||
|
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
|
||||||
|
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
|
||||||
|
DateTime startJT2 = new DateTime(2024, 12, 18, 0, 0);
|
||||||
|
DateTime endJT2 = new DateTime(2024, 12, 22, 0, 0);
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFullOverlappingRanges_thenReturnsTrue() {
|
||||||
|
Calendar start1 = Calendar.getInstance();
|
||||||
|
start1.set(2024, 11, 15);
|
||||||
|
Calendar end1 = Calendar.getInstance();
|
||||||
|
end1.set(2024, 11, 20);
|
||||||
|
|
||||||
|
Calendar start2 = Calendar.getInstance();
|
||||||
|
start2.set(2024, 11, 16);
|
||||||
|
Calendar end2 = Calendar.getInstance();
|
||||||
|
end2.set(2024, 11, 18);
|
||||||
|
|
||||||
|
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
|
||||||
|
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
|
||||||
|
|
||||||
|
LocalDate startLD2 = LocalDate.of(2024, 12, 16);
|
||||||
|
LocalDate endLD2 = LocalDate.of(2024, 12, 18);
|
||||||
|
|
||||||
|
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
|
||||||
|
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
|
||||||
|
DateTime startJT2 = new DateTime(2024, 12, 16, 0, 0);
|
||||||
|
DateTime endJT2 = new DateTime(2024, 12, 18, 0, 0);
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenConsecutiveRanges_thenReturnsFalse() {
|
||||||
|
Calendar start1 = Calendar.getInstance();
|
||||||
|
start1.set(2024, 11, 15);
|
||||||
|
Calendar end1 = Calendar.getInstance();
|
||||||
|
end1.set(2024, 11, 20);
|
||||||
|
|
||||||
|
Calendar start2 = Calendar.getInstance();
|
||||||
|
start2.set(2024, 11, 21);
|
||||||
|
Calendar end2 = Calendar.getInstance();
|
||||||
|
end2.set(2024, 11, 24);
|
||||||
|
|
||||||
|
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
|
||||||
|
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
|
||||||
|
|
||||||
|
LocalDate startLD2 = LocalDate.of(2024, 12, 21);
|
||||||
|
LocalDate endLD2 = LocalDate.of(2024, 12, 24);
|
||||||
|
|
||||||
|
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
|
||||||
|
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
|
||||||
|
DateTime startJT2 = new DateTime(2024, 12, 21, 0, 0);
|
||||||
|
DateTime endJT2 = new DateTime(2024, 12, 24, 0, 0);
|
||||||
|
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZeroRangeRanges_thenReturnsTrue() {
|
||||||
|
Calendar start1 = Calendar.getInstance();
|
||||||
|
start1.set(2024, 11, 15);
|
||||||
|
Calendar end1 = Calendar.getInstance();
|
||||||
|
end1.set(2024, 11, 20);
|
||||||
|
|
||||||
|
Calendar start2 = Calendar.getInstance();
|
||||||
|
start2.set(2024, 11, 20);
|
||||||
|
Calendar end2 = Calendar.getInstance();
|
||||||
|
end2.set(2024, 11, 20);
|
||||||
|
|
||||||
|
LocalDate startLD1 = LocalDate.of(2024, 12, 15);
|
||||||
|
LocalDate endLD1 = LocalDate.of(2024, 12, 20);
|
||||||
|
|
||||||
|
LocalDate startLD2 = LocalDate.of(2024, 12, 20);
|
||||||
|
LocalDate endLD2 = LocalDate.of(2024, 12, 20);
|
||||||
|
|
||||||
|
DateTime startJT1 = new DateTime(2024, 12, 15, 0, 0);
|
||||||
|
DateTime endJT1 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
|
||||||
|
DateTime startJT2 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
DateTime endJT2 = new DateTime(2024, 12, 20, 0, 0);
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndDuration(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndDuration(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndCondition(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndCondition(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingCalendarAndFindMin(start1, end1, start2, end2));
|
||||||
|
assertTrue(DateRangeOverlapChecker.isOverlapUsingLocalDateAndFindMin(startLD1, endLD1, startLD2, endLD2));
|
||||||
|
|
||||||
|
//the overlaps method considers two intervals as overlapping only if they have a non-zero duration.
|
||||||
|
assertFalse(DateRangeOverlapChecker.isOverlapUsingJodaTime(startJT1, endJT1, startJT2, endJT2));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.zoneoffsetandzoneidof;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class ZoneOffSetAndZoneIdOfUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOffsetDateTimeWithUTCZoneOffset_thenOffsetShouldBeUTC() {
|
||||||
|
OffsetDateTime dateTimeWithOffset = OffsetDateTime.now(ZoneOffset.UTC);
|
||||||
|
assertEquals(dateTimeWithOffset.getOffset(), ZoneOffset.UTC);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenZonedDateTimeWithUTCZoneId_thenZoneShouldBeUTC() {
|
||||||
|
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
|
||||||
|
assertEquals(zonedDateTime.getZone(), ZoneId.of("UTC"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,70 @@
|
||||||
|
package com.baeldung.unicodechar;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class UnicodeCharFromCodePointHexStringUnitTest {
|
||||||
|
private static final String U_CHECK = "✅"; // U+2705
|
||||||
|
private static final String U_STRONG = "强"; // U+5F3A
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenEscapeUAndNumberInString_thenGetExpectedUnicodeStr() {
|
||||||
|
String check = "\u2705";
|
||||||
|
assertEquals(U_CHECK, check);
|
||||||
|
|
||||||
|
String strong = "\u5F3A";
|
||||||
|
assertEquals(U_STRONG, strong);
|
||||||
|
|
||||||
|
// "A" U+0041
|
||||||
|
assertEquals("A", "\u0041");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenConcatUAndNumberAsString_thenDoNotGetExpectedUnicodeStr() {
|
||||||
|
String check = "\\u" + "2705";
|
||||||
|
assertEquals("\\u2705", check);
|
||||||
|
|
||||||
|
String strong = "\\u" + "5F3A";
|
||||||
|
assertEquals("\\u5F3A", strong);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenCastHexCodePointToCharAndConvertCharToString_thenGetExpectedUnicodeStr() {
|
||||||
|
|
||||||
|
int codePoint = Integer.parseInt("2705", 16); //Decimal int: 9989
|
||||||
|
char[] checkChar = Character.toChars(codePoint);
|
||||||
|
String check = String.valueOf(checkChar);
|
||||||
|
assertEquals(U_CHECK, check);
|
||||||
|
|
||||||
|
// For Java 11 and later versions
|
||||||
|
// assertEquals(U_CHECK, Character.toString(codePoint));
|
||||||
|
|
||||||
|
codePoint = Integer.parseInt("5F3A", 16); //Decimal int: 24378
|
||||||
|
char[] strongChar = Character.toChars(codePoint);
|
||||||
|
String strong = String.valueOf(strongChar);
|
||||||
|
assertEquals(U_STRONG, strong);
|
||||||
|
|
||||||
|
// For Java 11 and later versions
|
||||||
|
// assertEquals(U_STRONG, Character.toString(codePoint));
|
||||||
|
}
|
||||||
|
|
||||||
|
String stringFromCodePointHex(String codePointHex) {
|
||||||
|
int codePoint = Integer.parseInt(codePointHex, 16);
|
||||||
|
|
||||||
|
// For Java 11 and later versions: return Character.toString(codePoint)
|
||||||
|
|
||||||
|
char[] chars = Character.toChars(codePoint);
|
||||||
|
return String.valueOf(chars);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenUsingstringFromCodePointHex_thenGetExpectedUnicodeStr() {
|
||||||
|
assertEquals("A", stringFromCodePointHex("0041"));
|
||||||
|
assertEquals(U_CHECK, stringFromCodePointHex("2705"));
|
||||||
|
assertEquals(U_STRONG, stringFromCodePointHex("5F3A"));
|
||||||
|
}
|
||||||
|
}
|
|
@ -11,4 +11,6 @@
|
||||||
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
|
- [Intro to Vector Class in Java](https://www.baeldung.com/java-vector-guide)
|
||||||
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
|
- [HashSet toArray() Method in Java](https://www.baeldung.com/java-hashset-toarray)
|
||||||
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
|
- [Time Complexity of Java Collections Sort in Java](https://www.baeldung.com/java-time-complexity-collections-sort)
|
||||||
|
- [Check if List Contains at Least One Enum](https://www.baeldung.com/java-list-check-enum-presence)
|
||||||
|
- [Comparison of for Loops and Iterators](https://www.baeldung.com/java-for-loops-vs-iterators)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
|
||||||
|
|
|
@ -1,2 +1,5 @@
|
||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)
|
- [Check if a List Contains a String Element While Ignoring Case](https://www.baeldung.com/java-list-search-case-insensitive)
|
||||||
|
- [Removing the Last Node in a Linked List](https://www.baeldung.com/java-linked-list-remove-last-element)
|
||||||
|
- [Call a Method on Each Element of a List in Java](https://www.baeldung.com/java-call-method-each-list-item)
|
||||||
|
- [Sorting One List Based on Another List in Java](https://www.baeldung.com/java-sorting-one-list-using-another)
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.resetlistiterator;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.ListIterator;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
|
public class ResetListIteratorUnitTest {
|
||||||
|
|
||||||
|
private static final List<String> MY_LIST = List.of("A", "B", "C", "D", "E", "F", "G");
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenRecreateAnListIterator_thenGetTheExpectedResult() {
|
||||||
|
ListIterator<String> lit = MY_LIST.listIterator();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
|
||||||
|
lit = MY_LIST.listIterator();
|
||||||
|
|
||||||
|
assertFalse(lit.hasPrevious());
|
||||||
|
assertEquals("A", lit.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void whenBackwardIterationToTheFirst_thenGetTheExpectedResult() {
|
||||||
|
ListIterator<String> lit = MY_LIST.listIterator();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
lit.next();
|
||||||
|
|
||||||
|
|
||||||
|
while (lit.hasPrevious()) {
|
||||||
|
lit.previous();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertFalse(lit.hasPrevious());
|
||||||
|
assertEquals("A", lit.next());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -5,6 +5,6 @@
|
||||||
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
- [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair)
|
||||||
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file)
|
||||||
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
|
- [Limiting the Max Size of a HashMap in Java](https://www.baeldung.com/java-hashmap-size-bound)
|
||||||
- [How to Sort LinkedHashMap By Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
- [How to Sort LinkedHashMap by Values in Java](https://www.baeldung.com/java-sort-linkedhashmap-using-values)
|
||||||
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
|
- [How to Increment a Map Value in Java](https://www.baeldung.com/java-increment-map-value)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-6)
|
||||||
|
|
|
@ -12,4 +12,5 @@ This module contains articles about basic Java concurrency
|
||||||
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
|
- [How to Get the Number of Threads in a Java Process](https://www.baeldung.com/java-get-number-of-threads)
|
||||||
- [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name)
|
- [Set the Name of a Thread in Java](https://www.baeldung.com/java-set-thread-name)
|
||||||
- [Thread vs. Single Thread Executor Service](https://www.baeldung.com/java-single-thread-executor-service)
|
- [Thread vs. Single Thread Executor Service](https://www.baeldung.com/java-single-thread-executor-service)
|
||||||
|
- [Difference Between a Future and a Promise in Java](https://www.baeldung.com/java-future-vs-promise-comparison)
|
||||||
- [[<-- Prev]](../core-java-concurrency-basic)[[Next -->]](../core-java-concurrency-basic-3)
|
- [[<-- Prev]](../core-java-concurrency-basic)[[Next -->]](../core-java-concurrency-basic-3)
|
||||||
|
|
|
@ -13,4 +13,5 @@ This module contains articles about basic Java concurrency.
|
||||||
- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic)
|
- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic)
|
||||||
- [Convert From List of CompletableFuture to CompletableFuture List](https://www.baeldung.com/java-completablefuture-list-convert)
|
- [Convert From List of CompletableFuture to CompletableFuture List](https://www.baeldung.com/java-completablefuture-list-convert)
|
||||||
- [Synchronize a Static Variable Among Different Threads](https://www.baeldung.com/java-synchronize-static-variable-different-threads)
|
- [Synchronize a Static Variable Among Different Threads](https://www.baeldung.com/java-synchronize-static-variable-different-threads)
|
||||||
|
- [Difference Between execute() and submit() in Executor Service](https://www.baeldung.com/java-execute-vs-submit-executor-service)
|
||||||
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
- [[<-- Prev]](../core-java-concurrency-basic-2)
|
||||||
|
|
|
@ -0,0 +1,5 @@
|
||||||
|
## Core Date Operations (Part 4)
|
||||||
|
This module contains articles about date operations in Java.
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
|
|
@ -0,0 +1,46 @@
|
||||||
|
<?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-date-operations-4</artifactId>
|
||||||
|
<name>core-java-date-operations-4</name>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<configuration>
|
||||||
|
<source>11</source>
|
||||||
|
<target>11</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>joda-time</groupId>
|
||||||
|
<artifactId>joda-time</artifactId>
|
||||||
|
<version>${joda-time.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<joda-time.version>2.12.6</joda-time.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,46 @@
|
||||||
|
package com.baeldung.calculateweekdays;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
public class CalculateWeekdays {
|
||||||
|
|
||||||
|
public long getWorkingDaysWithStream(LocalDate start, LocalDate end){
|
||||||
|
return start.datesUntil(end)
|
||||||
|
.map(LocalDate::getDayOfWeek)
|
||||||
|
.filter(day -> !Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).contains(day))
|
||||||
|
.count();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getWorkingDaysWithoutStream(LocalDate start, LocalDate end) {
|
||||||
|
boolean startOnWeekend = false;
|
||||||
|
|
||||||
|
// If starting at the weekend, move to following Monday
|
||||||
|
if(start.getDayOfWeek().getValue() > 5){
|
||||||
|
start = start.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
|
||||||
|
startOnWeekend = true;
|
||||||
|
}
|
||||||
|
boolean endOnWeekend = false;
|
||||||
|
// If ending at the weekend, move to previous Friday
|
||||||
|
if(end.getDayOfWeek().getValue() > 5){
|
||||||
|
end = end.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
|
||||||
|
endOnWeekend = true;
|
||||||
|
}
|
||||||
|
// Cover case where starting on Saturday and ending following Sunday
|
||||||
|
if(start.isAfter(end)){
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// Get total weeks
|
||||||
|
long weeks = ChronoUnit.WEEKS.between(start, end);
|
||||||
|
|
||||||
|
long addValue = startOnWeekend || endOnWeekend ? 1 : 0;
|
||||||
|
|
||||||
|
// Add on days that did not make up a full week
|
||||||
|
return ( weeks * 5 ) + ( end.getDayOfWeek().getValue() - start.getDayOfWeek().getValue() ) + addValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,83 @@
|
||||||
|
package com.baeldung.calculateweekdays;
|
||||||
|
|
||||||
|
import static junit.framework.TestCase.assertEquals;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class CalculateWeekdaysUnitTest {
|
||||||
|
|
||||||
|
// Start Saturday end following Sunday (answer is 0)
|
||||||
|
LocalDate startTomorrow = LocalDate.of(2023, 12, 2);
|
||||||
|
LocalDate endTomorrow = LocalDate.of(2023, 12, 3);
|
||||||
|
|
||||||
|
// Three week gap with midweek start and finish (answer is 17)
|
||||||
|
LocalDate startThreeWeeks = LocalDate.of(2023, 11, 28);
|
||||||
|
LocalDate endThreeWeeks = LocalDate.of(2023, 12, 21);
|
||||||
|
|
||||||
|
// Three week gap with midweek start and weekend finish (answer is 17)
|
||||||
|
LocalDate startThreeWeeks2 = LocalDate.of(2023, 11, 6);
|
||||||
|
LocalDate endThreeWeeks2 = LocalDate.of(2023, 12, 30);
|
||||||
|
|
||||||
|
// Week gap start and end on weekend (answer is 40)
|
||||||
|
LocalDate startThreeWeeksWeekend = LocalDate.of(2023, 12, 2);
|
||||||
|
LocalDate endThreeWeeksWeekend = LocalDate.of(2023, 12, 9);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDaysOnSameWeekend_whenUsingStreams_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithStream(startTomorrow, endTomorrow);
|
||||||
|
assertEquals(0, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenTwoDaysOnSameWeekend_whenUsingMaths_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithoutStream(startTomorrow, endTomorrow);
|
||||||
|
assertEquals(0, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAThreeWeekGapMidweekDates_whenUsingStreams_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithStream(startThreeWeeks, endThreeWeeks);
|
||||||
|
assertEquals(17, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAThreeWeekGapMidweekDates_whenUsingMaths_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithoutStream(startThreeWeeks, endThreeWeeks);
|
||||||
|
assertEquals(17, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenThreeWeekGapMidweekAndWeekendDates_whenUsingStreams_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithStream(startThreeWeeksWeekend, endThreeWeeksWeekend);
|
||||||
|
assertEquals(5, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenThreeWeekGapMidweekAndWeekendDates_whenUsingMaths_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithoutStream(startThreeWeeksWeekend, endThreeWeeksWeekend);
|
||||||
|
assertEquals(5, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenThreeWeekGapWeekendDates_whenUsingStreams_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithStream(startThreeWeeks2, endThreeWeeks2);
|
||||||
|
assertEquals(40, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenThreeWeekGapWeekendDates_whenUsingMaths_thenCalculateWeekdays(){
|
||||||
|
CalculateWeekdays c = new CalculateWeekdays();
|
||||||
|
long result = c.getWorkingDaysWithoutStream(startThreeWeeks2, endThreeWeeks2);
|
||||||
|
assertEquals(40, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,74 @@
|
||||||
|
package com.baeldung.longtodate;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
|
import org.joda.time.DateTimeZone;
|
||||||
|
import org.joda.time.Instant;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class LongToDateUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLongValue_whenUsingInstantClass_thenConvert() {
|
||||||
|
Instant expectedDate = Instant.parse("2020-09-08T12:16:40Z");
|
||||||
|
long seconds = 1599567400L;
|
||||||
|
|
||||||
|
Instant date = Instant.ofEpochSecond(seconds);
|
||||||
|
|
||||||
|
assertEquals(expectedDate, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLongValue_whenUsingLocalDateClass_thenConvert() {
|
||||||
|
LocalDate expectedDate = LocalDate.of(2023, 10, 17);
|
||||||
|
long epochDay = 19647L;
|
||||||
|
|
||||||
|
LocalDate date = LocalDate.ofEpochDay(epochDay);
|
||||||
|
|
||||||
|
assertEquals(expectedDate, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLongValue_whenUsingDateClass_thenConvert() throws ParseException {
|
||||||
|
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
|
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||||
|
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
|
||||||
|
long milliseconds = 1689458400000L;
|
||||||
|
|
||||||
|
Date date = new Date(milliseconds);
|
||||||
|
|
||||||
|
assertEquals(expectedDate, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLongValue_whenUsingCalendarClass_thenConvert() throws ParseException {
|
||||||
|
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||||
|
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||||
|
Date expectedDate = dateFormat.parse("2023-07-15 22:00:00");
|
||||||
|
long milliseconds = 1689458400000L;
|
||||||
|
|
||||||
|
Calendar calendar = Calendar.getInstance();
|
||||||
|
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||||
|
calendar.setTimeInMillis(milliseconds);
|
||||||
|
|
||||||
|
assertEquals(expectedDate, calendar.getTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenLongValue_whenUsingJodaTimeLocalDateClass_thenConvert() {
|
||||||
|
org.joda.time.LocalDate expectedDate = new org.joda.time.LocalDate(2023, 7, 15);
|
||||||
|
long milliseconds = 1689458400000L;
|
||||||
|
|
||||||
|
org.joda.time.LocalDate date = new org.joda.time.LocalDate(milliseconds, DateTimeZone.UTC);
|
||||||
|
|
||||||
|
assertEquals(expectedDate, date);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
## Java Date/time conversion Cookbooks and Examples
|
||||||
|
|
||||||
|
This module contains articles about converting between Java date and time objects.
|
||||||
|
|
||||||
|
### Relevant Articles:
|
||||||
|
|
|
@ -0,0 +1,57 @@
|
||||||
|
<?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-datetime-conversion-2</artifactId>
|
||||||
|
<version>${project.parent.version}</version>
|
||||||
|
<name>core-java-datetime-conversion-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>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>joda-time</groupId>
|
||||||
|
<artifactId>joda-time</artifactId>
|
||||||
|
<version>${joda-time.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-lang3</artifactId>
|
||||||
|
<version>${commons-lang3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.msarhan</groupId>
|
||||||
|
<artifactId>ummalqura-calendar</artifactId>
|
||||||
|
<version>${ummalqura-calendar.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<finalName>core-java-datetime-conversion-2</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>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<joda-time.version>2.12.5</joda-time.version>
|
||||||
|
<ummalqura-calendar.version>2.0.2</ummalqura-calendar.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,34 @@
|
||||||
|
package com.baeldung.gregoriantohijri;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.chrono.ChronoLocalDate;
|
||||||
|
import java.time.chrono.HijrahChronology;
|
||||||
|
import java.time.chrono.HijrahDate;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
|
||||||
|
import org.joda.time.chrono.IslamicChronology;
|
||||||
|
|
||||||
|
import com.github.msarhan.ummalqura.calendar.UmmalquraCalendar;
|
||||||
|
|
||||||
|
public class GregorianToHijriDateConverter {
|
||||||
|
public static HijrahDate usingHijrahChronology(LocalDate gregorianDate) {
|
||||||
|
HijrahChronology hijrahChronology = HijrahChronology.INSTANCE;
|
||||||
|
ChronoLocalDate hijriChronoLocalDate = hijrahChronology.date(gregorianDate);
|
||||||
|
return HijrahDate.from(hijriChronoLocalDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HijrahDate usingFromMethod(LocalDate gregorianDate) {
|
||||||
|
return HijrahDate.from(gregorianDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static org.joda.time.DateTime usingJodaDate(org.joda.time.DateTime gregorianDate) {
|
||||||
|
return gregorianDate.withChronology(IslamicChronology.getInstance());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static UmmalquraCalendar usingUmmalquraCalendar(GregorianCalendar gregorianCalendar) throws ParseException {
|
||||||
|
UmmalquraCalendar hijriCalendar = new UmmalquraCalendar();
|
||||||
|
hijriCalendar.setTime(gregorianCalendar.getTime());
|
||||||
|
return hijriCalendar;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,53 @@
|
||||||
|
package com.baeldung.gregoriantohijri;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.text.ParseException;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.chrono.HijrahDate;
|
||||||
|
import java.time.temporal.ChronoField;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.GregorianCalendar;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.github.msarhan.ummalqura.calendar.UmmalquraCalendar;
|
||||||
|
|
||||||
|
public class GregorianToHijriDateConverterUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenGregorianDate_whenUsingHijrahChronologyClass_thenConvertHijriDate() {
|
||||||
|
LocalDate gregorianDate = LocalDate.of(2013, 3, 31);
|
||||||
|
HijrahDate hijriDate = GregorianToHijriDateConverter.usingHijrahChronology(gregorianDate);
|
||||||
|
assertEquals(1434, hijriDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(5, hijriDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(19, hijriDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenGregorianDate_whenUsingFromMethod_thenConvertHijriDate() {
|
||||||
|
LocalDate gregorianDate = LocalDate.of(2013, 3, 31);
|
||||||
|
HijrahDate hijriDate = GregorianToHijriDateConverter.usingFromMethod(gregorianDate);
|
||||||
|
assertEquals(1434, hijriDate.get(ChronoField.YEAR));
|
||||||
|
assertEquals(5, hijriDate.get(ChronoField.MONTH_OF_YEAR));
|
||||||
|
assertEquals(19, hijriDate.get(ChronoField.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenGregorianDate_whenUsingJodaDate_thenConvertHijriDate() {
|
||||||
|
DateTime gregorianDate = new DateTime(2013, 3, 31, 0, 0, 0);
|
||||||
|
DateTime hijriDate = GregorianToHijriDateConverter.usingJodaDate(gregorianDate);
|
||||||
|
assertEquals(1434, hijriDate.getYear());
|
||||||
|
assertEquals(5, hijriDate.getMonthOfYear());
|
||||||
|
assertEquals(19, hijriDate.getDayOfMonth());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenGregorianDate_whenUsingUmmalquraCalendar_thenConvertHijriDate() throws ParseException {
|
||||||
|
GregorianCalendar gregorianCalendar = new GregorianCalendar(2013, Calendar.MARCH, 31);
|
||||||
|
UmmalquraCalendar ummalquraCalendar = GregorianToHijriDateConverter.usingUmmalquraCalendar(gregorianCalendar);
|
||||||
|
assertEquals(1434, ummalquraCalendar.get(Calendar.YEAR));
|
||||||
|
assertEquals(5, ummalquraCalendar.get(Calendar.MONTH) + 1);
|
||||||
|
assertEquals(19, ummalquraCalendar.get(Calendar.DAY_OF_MONTH));
|
||||||
|
}
|
||||||
|
}
|
|
@ -12,3 +12,4 @@ This module contains articles about converting between Java date and time object
|
||||||
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
|
- [Convert Epoch Time to LocalDate and LocalDateTime](https://www.baeldung.com/java-convert-epoch-localdate)
|
||||||
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
|
- [Convert Timestamp String to Long in Java](https://www.baeldung.com/java-convert-timestamp-string-long)
|
||||||
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)
|
- [Convert Long Timestamp to LocalDateTime in Java](https://www.baeldung.com/java-convert-long-timestamp-localdatetime)
|
||||||
|
- [Convert Joda-Time DateTime to Date and Vice Versa](https://www.baeldung.com/java-convert-joda-time-datetime-to-date)
|
||||||
|
|
|
@ -13,6 +13,14 @@
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>joda-time</groupId>
|
||||||
|
<artifactId>joda-time</artifactId>
|
||||||
|
<version>${joda-time.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -22,4 +30,8 @@
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<joda-time.version>2.12.5</joda-time.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,114 @@
|
||||||
|
package com.baeldung.timestamp;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.text.MessageFormat;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.OffsetDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
import java.time.ZonedDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.Calendar;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import org.joda.time.DateTime;
|
||||||
|
import org.joda.time.format.DateTimeFormat;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class CurrentTimeAsFileNameUnitTest {
|
||||||
|
|
||||||
|
static final String TIMESTAMP_FORMAT = "yyyyMMddHHmmss";
|
||||||
|
static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(TIMESTAMP_FORMAT);
|
||||||
|
static final SimpleDateFormat SIMPLEDATE_FORMAT = new SimpleDateFormat(TIMESTAMP_FORMAT);
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingCalendar_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = SIMPLEDATE_FORMAT.format(Calendar.getInstance().getTime());
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingDate_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = SIMPLEDATE_FORMAT.format(new Date());
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingInstant_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = Instant
|
||||||
|
.now()
|
||||||
|
.truncatedTo(ChronoUnit.SECONDS)
|
||||||
|
.toString()
|
||||||
|
.replaceAll("[:TZ-]", "");
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingLocalDateTime_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = LocalDateTime.now().format(DATETIME_FORMATTER);
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingZonedDateTime_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = ZonedDateTime
|
||||||
|
.now(ZoneId.of("Europe/Paris"))
|
||||||
|
.format(DATETIME_FORMATTER);
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingOffsetDateTime_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = OffsetDateTime
|
||||||
|
.of(LocalDateTime.now(), ZoneOffset.of("+01:00"))
|
||||||
|
.format(DATETIME_FORMATTER);
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingJodaDateTime_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = DateTime.now().toString(TIMESTAMP_FORMAT);
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingJodaInstant_thenCurrentTimeAsFileName() {
|
||||||
|
String currentTime = DateTimeFormat
|
||||||
|
.forPattern(TIMESTAMP_FORMAT)
|
||||||
|
.print(org.joda.time.Instant.now()
|
||||||
|
.toDateTime());
|
||||||
|
String fileName = getFileName(currentTime);
|
||||||
|
|
||||||
|
assertTrue(verifyFileName(fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
String getFileName(String currentTime) {
|
||||||
|
return MessageFormat.format("{0}.txt", currentTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean verifyFileName(String fileName) {
|
||||||
|
return Pattern
|
||||||
|
.compile("[0-9]{14}+\\.txt", Pattern.CASE_INSENSITIVE)
|
||||||
|
.matcher(fileName)
|
||||||
|
.matches();
|
||||||
|
}
|
||||||
|
}
|
|
@ -6,3 +6,4 @@
|
||||||
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
|
||||||
- [Use Cases for Static Methods in Java](https://www.baeldung.com/java-static-methods-use-cases)
|
- [Use Cases for Static Methods in Java](https://www.baeldung.com/java-static-methods-use-cases)
|
||||||
- [TriFunction Interface in Java](https://www.baeldung.com/java-trifunction)
|
- [TriFunction Interface in Java](https://www.baeldung.com/java-trifunction)
|
||||||
|
- [Lazy Field Initialization with Lambdas](https://www.baeldung.com/java-lambda-lazy-field-initialization)
|
||||||
|
|
|
@ -9,7 +9,7 @@ This module contains articles about core Java input and output (IO)
|
||||||
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
|
- [SequenceInputStream Class in Java](https://www.baeldung.com/java-sequenceinputstream)
|
||||||
- [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map)
|
- [Read a File Into a Map in Java](https://www.baeldung.com/java-read-file-into-map)
|
||||||
- [Read User Input Until a Condition Is Met](https://www.baeldung.com/java-read-input-until-condition)
|
- [Read User Input Until a Condition Is Met](https://www.baeldung.com/java-read-input-until-condition)
|
||||||
- [Java Scanner.skip method with examples](https://www.baeldung.com/java-scanner-skip)
|
- [Java Scanner.skip Method with Examples](https://www.baeldung.com/java-scanner-skip)
|
||||||
- [Generate the MD5 Checksum for a File in Java](https://www.baeldung.com/java-md5-checksum-file)
|
- [Generate the MD5 Checksum for a File in Java](https://www.baeldung.com/java-md5-checksum-file)
|
||||||
- [Getting the Filename From a String Containing an Absolute File Path](https://www.baeldung.com/java-filename-full-path)
|
- [Getting the Filename From a String Containing an Absolute File Path](https://www.baeldung.com/java-filename-full-path)
|
||||||
- [Mocking Java InputStream Object](https://www.baeldung.com/java-mocking-inputstream)
|
- [Mocking Java InputStream Object](https://www.baeldung.com/java-mocking-inputstream)
|
||||||
|
|
|
@ -6,5 +6,7 @@ This module contains articles about core Java input and output (IO)
|
||||||
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
|
- [Get File Extension From MIME Type in Java](https://www.baeldung.com/java-mime-type-file-extension)
|
||||||
- [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks)
|
- [How to Remove Line Breaks From a File in Java](https://www.baeldung.com/java-file-remove-line-breaks)
|
||||||
- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream)
|
- [Difference Between ZipFile and ZipInputStream in Java](https://www.baeldung.com/java-zipfile-vs-zipinputstream)
|
||||||
|
- [How to Write Strings to OutputStream in Java](https://www.baeldung.com/java-write-string-outputstream)
|
||||||
|
- [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several)
|
||||||
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
- [[<-- Prev]](/core-java-modules/core-java-io-4)
|
||||||
|
|
||||||
|
|
|
@ -9,3 +9,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||||
- [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)
|
- [Detect EOF in Java](https://www.baeldung.com/java-file-detect-end-of-file)
|
||||||
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
|
- [PrintWriter vs. FileWriter in Java](https://www.baeldung.com/java-printwriter-filewriter-difference)
|
||||||
|
- [Read Input Character-by-Character in Java](https://www.baeldung.com/java-read-input-character)
|
||||||
|
- [Difference Between flush() and close() in Java FileWriter](https://www.baeldung.com/java-filewriter-flush-vs-close)
|
||||||
|
|
|
@ -11,5 +11,5 @@ This module contains articles about core Java input/output(IO) APIs.
|
||||||
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
- [Quick Use of FilenameFilter](https://www.baeldung.com/java-filename-filter)
|
||||||
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
|
||||||
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
|
||||||
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
- [Read Multiple Inputs on the Same Line in Java](https://www.baeldung.com/java-read-multiple-inputs-same-line)
|
||||||
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
- [Write Console Output to Text File in Java](https://www.baeldung.com/java-write-console-output-file)
|
|
@ -0,0 +1,7 @@
|
||||||
|
FROM maven:3.9-amazoncorretto-17
|
||||||
|
WORKDIR /app
|
||||||
|
COPY /src/test/java/com/baeldung/setenvironment/SettingDockerEnvironmentVariableUnitTest.java \
|
||||||
|
./src/test/java/com/baeldung/setenvironment/
|
||||||
|
COPY /docker-pom.xml ./
|
||||||
|
ENV CUSTOM_DOCKER_ENV_VARIABLE=TRUE
|
||||||
|
ENTRYPOINT mvn -f docker-pom.xml test
|
|
@ -10,4 +10,7 @@ This module contains articles about core features in the Java language
|
||||||
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
- [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code)
|
||||||
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
- [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects)
|
||||||
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
|
- [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null)
|
||||||
|
- [Compress and Uncompress Byte Array Using Deflater/Inflater](https://www.baeldung.com/java-compress-uncompress-byte-array)
|
||||||
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables)
|
||||||
|
- [What Is the Error: “Non-static method cannot be referenced from a static context”?](https://www.baeldung.com/java-non-static-method-cannot-be-referenced-from-a-static-context)
|
||||||
|
- [Recursively Sum the Integers in an Array](https://www.baeldung.com/java-recursive-sum-integer-array)
|
||||||
|
|
|
@ -0,0 +1,42 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-lang-6</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>testcontainers</artifactId>
|
||||||
|
<version>${testcontainers.junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>${testcontainers.junit.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>5.10.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
|
<version>5.10.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<testcontainers.junit.version>1.19.3</testcontainers.junit.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -33,6 +33,25 @@
|
||||||
<artifactId>jmh-generator-annprocess</artifactId>
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
<version>${jmh.version}</version>
|
<version>${jmh.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit-pioneer</groupId>
|
||||||
|
<artifactId>junit-pioneer</artifactId>
|
||||||
|
<version>${junit.pioneer.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>testcontainers</artifactId>
|
||||||
|
<version>${testcontaienr.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>${testcontaienr.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
<build>
|
<build>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
@ -53,6 +72,8 @@
|
||||||
<version>${jmh.version}</version>
|
<version>${jmh.version}</version>
|
||||||
</path>
|
</path>
|
||||||
</annotationProcessorPaths>
|
</annotationProcessorPaths>
|
||||||
|
<source>14</source>
|
||||||
|
<target>14</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
|
@ -61,6 +82,8 @@
|
||||||
<properties>
|
<properties>
|
||||||
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
<mapstruct.version>1.6.0.Beta1</mapstruct.version>
|
||||||
<jmh.version>1.37</jmh.version>
|
<jmh.version>1.37</jmh.version>
|
||||||
|
<junit.pioneer.version>2.2.0</junit.pioneer.version>
|
||||||
|
<testcontaienr.version>1.19.3</testcontaienr.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -0,0 +1,44 @@
|
||||||
|
package com.baeldung.setenvironment;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Tag;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||||
|
|
||||||
|
class SettingChildProcessEnvironmentVariableUnitTest {
|
||||||
|
|
||||||
|
public static final String ENVIRONMENT_VARIABLE_NAME = "test";
|
||||||
|
public static final String ENVIRONMENT_VARIABLE_VALUE = "Hello World";
|
||||||
|
public static final String CHILD_PROCESS_CONDITION = "CHILD_PROCESS_TEST";
|
||||||
|
public static final String CHILD_PROCESS_VALUE = "true";
|
||||||
|
public static final String CHILD_PROCESS_TAG = "child_process";
|
||||||
|
public static final String TAG = String.format("-Dgroups=%s", CHILD_PROCESS_TAG);
|
||||||
|
private final String testClass = String.format("-Dtest=%s", getClass().getName());
|
||||||
|
private final String[] arguments = {"mvn", "test", TAG, testClass};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenChildProcessTestRunner_whenRunTheTest_thenAllSucceed()
|
||||||
|
throws IOException, InterruptedException {
|
||||||
|
ProcessBuilder processBuilder = new ProcessBuilder();
|
||||||
|
processBuilder.inheritIO();
|
||||||
|
|
||||||
|
Map<String, String> environment = processBuilder.environment();
|
||||||
|
environment.put(CHILD_PROCESS_CONDITION, CHILD_PROCESS_VALUE);
|
||||||
|
environment.put(ENVIRONMENT_VARIABLE_NAME, ENVIRONMENT_VARIABLE_VALUE);
|
||||||
|
Process process = processBuilder.command(arguments).start();
|
||||||
|
|
||||||
|
int errorCode = process.waitFor();
|
||||||
|
assertThat(errorCode).isZero();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@EnabledIfEnvironmentVariable(named = CHILD_PROCESS_CONDITION, matches = CHILD_PROCESS_VALUE)
|
||||||
|
@Tag(CHILD_PROCESS_TAG)
|
||||||
|
void givenChildProcess_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
|
||||||
|
String actual = System.getenv(ENVIRONMENT_VARIABLE_NAME);
|
||||||
|
assertThat(actual).isEqualTo(ENVIRONMENT_VARIABLE_VALUE);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
package com.baeldung.setenvironment;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||||
|
|
||||||
|
class SettingDockerEnvironmentVariableUnitTest {
|
||||||
|
|
||||||
|
public static final String ENV_VARIABLE_NAME = "CUSTOM_DOCKER_ENV_VARIABLE";
|
||||||
|
public static final String ENV_VARIABLE_VALUE = "TRUE";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@EnabledIfEnvironmentVariable(named = ENV_VARIABLE_NAME, matches = ENV_VARIABLE_VALUE)
|
||||||
|
void givenDockerEnvironment_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
|
||||||
|
String actual = System.getenv(ENV_VARIABLE_NAME);
|
||||||
|
assertEquals(ENV_VARIABLE_VALUE, actual);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,83 @@
|
||||||
|
package com.baeldung.setenvironment;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.lang.reflect.Field;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledForJreRange;
|
||||||
|
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||||
|
import org.junit.jupiter.api.condition.JRE;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
import org.junitpioneer.jupiter.SetEnvironmentVariable;
|
||||||
|
|
||||||
|
class SettingSameProcessEnvironmentVariableUnitTest {
|
||||||
|
|
||||||
|
private static final String PROCESS_ENVIRONMENT = "java.lang.ProcessEnvironment";
|
||||||
|
private static final String ENVIRONMENT = "theUnmodifiableEnvironment";
|
||||||
|
private static final String SOURCE_MAP = "m";
|
||||||
|
private static final Object STATIC_METHOD = null;
|
||||||
|
private static final Class<?> UMODIFIABLE_MAP_CLASS
|
||||||
|
= Collections.unmodifiableMap(Collections.emptyMap()).getClass();
|
||||||
|
private static final Class<?> MAP_CLASS = Map.class;
|
||||||
|
public static final String ENV_VARIABLE_NAME = "test";
|
||||||
|
public static final String ENV_VARIABLE_VALUE = "Hello World";
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@CsvSource({ENV_VARIABLE_VALUE + "," + ENV_VARIABLE_NAME})
|
||||||
|
@EnabledForJreRange(max = JRE.JAVA_16)
|
||||||
|
void givenReflexiveAccess_whenGetSourceMap_thenSuccessfullyModifyVariables(String environmentVariable, String value)
|
||||||
|
throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
|
||||||
|
Map<String, String> modifiableEnvironment = getModifiableEnvironment();
|
||||||
|
assertThat(modifiableEnvironment).isNotNull();
|
||||||
|
|
||||||
|
modifiableEnvironment.put(environmentVariable, value);
|
||||||
|
String actual = modifiableEnvironment.get(environmentVariable);
|
||||||
|
assertThat(actual).isEqualTo(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@EnabledIfEnvironmentVariable(named = "PATH", matches = ".*",
|
||||||
|
disabledReason = "The test relies on the presence of PATH variable")
|
||||||
|
void givenOS_whenGetPath_thenVariableIsPresent() {
|
||||||
|
String classPath = System.getenv("PATH");
|
||||||
|
assertThat(classPath).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenOS_whenGetEnv_thenVariablesArePresent() {
|
||||||
|
Map<String, String> environment = System.getenv();
|
||||||
|
assertThat(environment).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SetEnvironmentVariable(key = ENV_VARIABLE_NAME, value = ENV_VARIABLE_VALUE)
|
||||||
|
@EnabledForJreRange(max = JRE.JAVA_16)
|
||||||
|
void givenVariableSet_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
|
||||||
|
String actual = System.getenv(ENV_VARIABLE_NAME);
|
||||||
|
assertThat(actual).isEqualTo(ENV_VARIABLE_VALUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private static Map<String, String> getModifiableEnvironment()
|
||||||
|
throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
|
||||||
|
Class<?> environmentClass = Class.forName(PROCESS_ENVIRONMENT);
|
||||||
|
Field environmentField = environmentClass.getDeclaredField(ENVIRONMENT);
|
||||||
|
assertThat(environmentField).isNotNull();
|
||||||
|
environmentField.setAccessible(true);
|
||||||
|
|
||||||
|
Object unmodifiableEnvironmentMap = environmentField.get(STATIC_METHOD);
|
||||||
|
assertThat(unmodifiableEnvironmentMap).isNotNull();
|
||||||
|
assertThat(unmodifiableEnvironmentMap).isInstanceOf(UMODIFIABLE_MAP_CLASS);
|
||||||
|
|
||||||
|
Field underlyingMapField = unmodifiableEnvironmentMap.getClass().getDeclaredField(SOURCE_MAP);
|
||||||
|
underlyingMapField.setAccessible(true);
|
||||||
|
Object underlyingMap = underlyingMapField.get(unmodifiableEnvironmentMap);
|
||||||
|
assertThat(underlyingMap).isNotNull();
|
||||||
|
assertThat(underlyingMap).isInstanceOf(MAP_CLASS);
|
||||||
|
|
||||||
|
return (Map<String, String>) underlyingMap;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.setenvironment;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.testcontainers.containers.GenericContainer;
|
||||||
|
import org.testcontainers.images.builder.ImageFromDockerfile;
|
||||||
|
|
||||||
|
class SettingTestcontainerVariableUnitTest {
|
||||||
|
|
||||||
|
public static final String CONTAINER_REPORT_FILE = "/app/target/surefire-reports/TEST-com.baeldung.setenvironment.SettingDockerEnvironmentVariableUnitTest.xml";
|
||||||
|
public static final String HOST_REPORT_FILE = "./container-test-report.xml";
|
||||||
|
public static final String DOCKERFILE = "./Dockerfile";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@Disabled("Requires working Docker environment ")
|
||||||
|
void givenTestcontainerEnvironment_whenGetEnvironmentVariable_thenReturnsCorrectValue() {
|
||||||
|
Path dockerfilePath = Paths.get(DOCKERFILE);
|
||||||
|
GenericContainer container = new GenericContainer(
|
||||||
|
new ImageFromDockerfile().withDockerfile(dockerfilePath));
|
||||||
|
assertThat(container).isNotNull();
|
||||||
|
container.start();
|
||||||
|
while (container.isRunning()) {
|
||||||
|
// Busy spin
|
||||||
|
}
|
||||||
|
container.copyFileFromContainer(CONTAINER_REPORT_FILE, HOST_REPORT_FILE);
|
||||||
|
}
|
||||||
|
}
|
|
@ -13,4 +13,5 @@
|
||||||
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
|
||||||
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
|
- [Clamp Function in Java](https://www.baeldung.com/java-clamp-function)
|
||||||
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
|
- [Creating a Magic Square in Java](https://www.baeldung.com/java-magic-square)
|
||||||
|
- [Check if a Point Is Between Two Points Drawn on a Straight Line in Java](https://www.baeldung.com/java-check-point-straight-line)
|
||||||
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
|
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
|
||||||
|
|
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.math.rotatevertex;
|
||||||
|
|
||||||
|
import java.awt.geom.AffineTransform;
|
||||||
|
import java.awt.geom.Point2D;
|
||||||
|
|
||||||
|
public class VertexRotation {
|
||||||
|
public static Point2D.Double usingOriginAsRotationPoint(Point2D.Double vertex, Point2D.Double rotationPoint, double angle) {
|
||||||
|
double translatedToOriginX = vertex.x - rotationPoint.x;
|
||||||
|
double translatedToOriginY = vertex.y - rotationPoint.y;
|
||||||
|
|
||||||
|
double rotatedX = translatedToOriginX * Math.cos(angle) - translatedToOriginY * Math.sin(angle);
|
||||||
|
double rotatedY = translatedToOriginX * Math.sin(angle) + translatedToOriginY * Math.cos(angle);
|
||||||
|
|
||||||
|
double reverseTranslatedX = rotatedX + rotationPoint.x;
|
||||||
|
double reverseTranslatedY = rotatedY + rotationPoint.y;
|
||||||
|
|
||||||
|
return new Point2D.Double(reverseTranslatedX, reverseTranslatedY);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Point2D.Double usingAffineTransform(Point2D.Double vertex, Point2D.Double rotationPoint, double angle) {
|
||||||
|
AffineTransform affineTransform = AffineTransform.getRotateInstance(angle, rotationPoint.x, rotationPoint.y);
|
||||||
|
Point2D.Double rotatedVertex = new Point2D.Double();
|
||||||
|
affineTransform.transform(vertex, rotatedVertex);
|
||||||
|
return rotatedVertex;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
package com.baeldung.powerinsteadofmathpow;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class FindPowerInsteadOfUsingMathPowUnitTest {
|
||||||
|
double result = 1;
|
||||||
|
double base = 2;
|
||||||
|
int exponent = 3;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBaseAndExponentNumbers_whenUtilizingIterativeApproach_thenReturnThePower() {
|
||||||
|
|
||||||
|
for (int i = 0; i < exponent; i++) {
|
||||||
|
result *= base;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(8, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBaseAndExponentNumbers_whenUtilizingRecursionApproach_thenReturnThePower() {
|
||||||
|
|
||||||
|
result = calculatePowerRecursively(base, exponent);
|
||||||
|
|
||||||
|
assertEquals(8, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double calculatePowerRecursively(double base, int exponent) {
|
||||||
|
if (exponent == 0) {
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
return base * calculatePowerRecursively(base, exponent - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenBaseAndExponentNumbers_whenUtilizingFastApproach_thenReturnThePower() {
|
||||||
|
result = calculatePowerFast(base, exponent);
|
||||||
|
|
||||||
|
assertEquals(8, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
private double calculatePowerFast(double base, int exponent) {
|
||||||
|
if (exponent == 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
double halfPower = calculatePowerFast(base, exponent / 2);
|
||||||
|
if (exponent % 2 == 0) {
|
||||||
|
return halfPower * halfPower;
|
||||||
|
} else {
|
||||||
|
return base * halfPower * halfPower;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
package com.baeldung.math.rotatevertex;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
import java.awt.geom.Point2D;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class VertexRotationUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenRotationPoint_whenUseOrigin_thenRotateVertex() {
|
||||||
|
Point2D.Double vertex = new Point2D.Double(2.0, 2.0);
|
||||||
|
Point2D.Double rotationPoint = new Point2D.Double(0.0, 1.0);
|
||||||
|
double angle = Math.toRadians(45.0);
|
||||||
|
Point2D.Double rotatedVertex = VertexRotation.usingOriginAsRotationPoint(vertex, rotationPoint, angle);
|
||||||
|
|
||||||
|
assertEquals(0.707, rotatedVertex.getX(), 0.001);
|
||||||
|
assertEquals(3.121, rotatedVertex.getY(), 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenRotationPoint_whenUseAffineTransform_thenRotateVertex() {
|
||||||
|
Point2D.Double vertex = new Point2D.Double(2.0, 2.0);
|
||||||
|
Point2D.Double rotationPoint = new Point2D.Double(0.0, 1.0);
|
||||||
|
double angle = Math.toRadians(45.0);
|
||||||
|
Point2D.Double rotatedVertex = VertexRotation.usingAffineTransform(vertex, rotationPoint, angle);
|
||||||
|
|
||||||
|
assertEquals(0.707, rotatedVertex.getX(), 0.001);
|
||||||
|
assertEquals(3.121, rotatedVertex.getY(), 0.001);
|
||||||
|
}
|
||||||
|
}
|
|
@ -10,3 +10,4 @@ This module contains articles about generics in Java
|
||||||
- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion)
|
- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion)
|
||||||
- [Java Warning “Unchecked Cast”](https://www.baeldung.com/java-warning-unchecked-cast)
|
- [Java Warning “Unchecked Cast”](https://www.baeldung.com/java-warning-unchecked-cast)
|
||||||
- [What Does the Holder<T> Class Do in Java?](https://www.baeldung.com/java-holder-class)
|
- [What Does the Holder<T> Class Do in Java?](https://www.baeldung.com/java-holder-class)
|
||||||
|
- [Determine the Class of a Generic Type in Java](https://www.baeldung.com/java-generic-type-find-class-runtime)
|
||||||
|
|
|
@ -0,0 +1,50 @@
|
||||||
|
package com.baeldung.urlnormalization;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.apache.commons.validator.routines.UrlValidator;
|
||||||
|
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
|
||||||
|
public class URLNormalizationUnitTest {
|
||||||
|
String originalUrl = "https://www.example.com:8080/path/to/resource?param1=value1¶m2=value2#fragment";
|
||||||
|
String expectedNormalizedUrl = "https://www.example.com:8080/path/to/resource";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOriginalUrl_whenUsingApacheCommonsValidator_thenValidatedAndMaybeManuallyNormalized() {
|
||||||
|
UrlValidator urlValidator = new UrlValidator();
|
||||||
|
if (urlValidator.isValid(originalUrl)) {
|
||||||
|
String normalizedUri = originalUrl.split("\\?")[0];
|
||||||
|
assertEquals(expectedNormalizedUrl, normalizedUri);
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid URL: " + originalUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOriginalUrl_whenUsingJavaURIClass_thenNormalizedUrl() throws URISyntaxException {
|
||||||
|
URI uri = new URI(originalUrl);
|
||||||
|
URI normalizedUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null);
|
||||||
|
String normalizedUrl = normalizedUri.toString();
|
||||||
|
assertEquals(expectedNormalizedUrl, normalizedUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOriginalUrl_whenUsingRegularExpression_thenNormalizedUrl() throws URISyntaxException, UnsupportedEncodingException {
|
||||||
|
String regex = "^(https?://[^/]+/[^?#]+)";
|
||||||
|
Pattern pattern = Pattern.compile(regex);
|
||||||
|
Matcher matcher = pattern.matcher(originalUrl);
|
||||||
|
|
||||||
|
if (matcher.find()) {
|
||||||
|
String normalizedUrl = matcher.group(1);
|
||||||
|
assertEquals(expectedNormalizedUrl, normalizedUrl);
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid URL: " + originalUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,2 +1,3 @@
|
||||||
## Relevant Articles
|
## Relevant Articles
|
||||||
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)
|
- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer)
|
||||||
|
- [Print a Double Value Without Scientific Notation in Java](https://www.baeldung.com/java-print-double-number-no-scientific-notation)
|
||||||
|
|
|
@ -2,7 +2,9 @@
|
||||||
- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
|
- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
|
||||||
- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal)
|
- [Convert Long to BigDecimal in Java](https://www.baeldung.com/java-convert-long-bigdecimal)
|
||||||
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
- [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long)
|
||||||
- [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float)
|
- [How to Convert Double to Float in Java](https://www.baeldung.com/java-convert-double-float)
|
||||||
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
- [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal)
|
||||||
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
|
- [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer)
|
||||||
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)
|
- [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five)
|
||||||
|
- [Convert byte to int Type in Java](https://www.baeldung.com/java-byte-to-int-conversion)
|
||||||
|
- [Converting Integer to BigDecimal in Java](https://www.baeldung.com/java-integer-bigdecimal-conversion)
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.bytetoint;
|
||||||
|
|
||||||
|
public class ByteToIntConversion {
|
||||||
|
static int usingTypeCasting(byte b){
|
||||||
|
int i = b;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int usingIntegerValueOf(byte b){
|
||||||
|
return Integer.valueOf(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int usingByteIntValue(byte b){
|
||||||
|
Byte byteObj = new Byte(b);
|
||||||
|
return byteObj.intValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
static int usingMathToIntExact(byte b){
|
||||||
|
return Math.toIntExact(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
static int usingByteUnsignedInt(byte b){
|
||||||
|
return Byte.toUnsignedInt(b);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.bytetoint;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class ByteToIntConversionUnitTest {
|
||||||
|
@Test
|
||||||
|
public void givenByte_whenUsingTypeCasting_thenConvertToInt() {
|
||||||
|
byte b = -51;
|
||||||
|
int result = ByteToIntConversion.usingTypeCasting(b);
|
||||||
|
assertEquals(-51, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenByte_whenUsingIntegerValueOf_thenConvertToInt() {
|
||||||
|
byte b = -51;
|
||||||
|
int result = ByteToIntConversion.usingIntegerValueOf(b);
|
||||||
|
|
||||||
|
assertEquals(-51, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenByte_whenUsingByteIntValue_thenConvertToInt() {
|
||||||
|
byte b = -51;
|
||||||
|
int result = ByteToIntConversion.usingByteIntValue(b);
|
||||||
|
|
||||||
|
assertEquals(-51, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenByte_whenUsingMathToIntExact_thenConvertToInt() {
|
||||||
|
byte b = -51;
|
||||||
|
int result = ByteToIntConversion.usingMathToIntExact(b);
|
||||||
|
|
||||||
|
assertEquals(-51, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenByte_whenUsingByteUnsignedInt_thenConvertToInt() {
|
||||||
|
byte b = -51;
|
||||||
|
int result = ByteToIntConversion.usingByteUnsignedInt(b);
|
||||||
|
|
||||||
|
assertEquals(205, result);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,52 @@
|
||||||
|
package com.baeldung.oom;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
@Disabled
|
||||||
|
class OomCrashUnitTest {
|
||||||
|
|
||||||
|
public static final Runnable MEMORY_LEAK = () -> {
|
||||||
|
List<byte[]> list = new ArrayList<>();
|
||||||
|
while (true) {
|
||||||
|
list.add(tenMegabytes());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenMemoryLeakCode_whenRunInsideThread_thenMainAppDoestFail() throws InterruptedException {
|
||||||
|
Thread memoryLeakThread = new Thread(MEMORY_LEAK);
|
||||||
|
memoryLeakThread.start();
|
||||||
|
memoryLeakThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenMemoryLeakCode_whenRunSeveralTimesInsideThread_thenMainAppDoestFail() throws InterruptedException {
|
||||||
|
for (int i = 0; i < 5; i++) {
|
||||||
|
Thread memoryLeakThread = new Thread(MEMORY_LEAK);
|
||||||
|
memoryLeakThread.start();
|
||||||
|
memoryLeakThread.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenBadExample_whenUseItInProductionCode_thenQuestionedByEmployerAndProbablyFired()
|
||||||
|
throws InterruptedException {
|
||||||
|
Thread npeThread = new Thread(() -> {
|
||||||
|
String nullString = null;
|
||||||
|
try {
|
||||||
|
nullString.isEmpty();
|
||||||
|
} catch (NullPointerException e) {
|
||||||
|
throw new OutOfMemoryError(e.getMessage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
npeThread.start();
|
||||||
|
npeThread.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] tenMegabytes() {
|
||||||
|
return new byte[1024 * 1014 * 10];
|
||||||
|
}
|
||||||
|
}
|
|
@ -9,5 +9,5 @@
|
||||||
- [Regular Expression: \z vs \Z Anchors in Java](https://www.baeldung.com/java-regular-expression-z-vs-z-anchors)
|
- [Regular Expression: \z vs \Z Anchors in Java](https://www.baeldung.com/java-regular-expression-z-vs-z-anchors)
|
||||||
- [Extract Text Between Square Brackets](https://www.baeldung.com/java-get-content-between-square-brackets)
|
- [Extract Text Between Square Brackets](https://www.baeldung.com/java-get-content-between-square-brackets)
|
||||||
- [Get the Indexes of Regex Pattern Matches in Java](https://www.baeldung.com/java-indexes-regex-pattern-matches)
|
- [Get the Indexes of Regex Pattern Matches in Java](https://www.baeldung.com/java-indexes-regex-pattern-matches)
|
||||||
- [Check if a String is Strictly Alphanumeric With Java](https://www.baeldung.com/java-check-string-contains-only-letters-numbers)
|
- [Check if a String Is Strictly Alphanumeric With Java](https://www.baeldung.com/java-check-string-contains-only-letters-numbers)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
### Relevant Articles:
|
||||||
|
|
||||||
|
- More articles: [[<-- prev]](/core-java-modules/core-java-regex-2)
|
|
@ -0,0 +1,24 @@
|
||||||
|
<?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-regex-3</artifactId>
|
||||||
|
<name>core-java-regex-3</name>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>5.8.1</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-java-modules</groupId>
|
||||||
|
<artifactId>core-java-modules</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
</project>
|
|
@ -0,0 +1,53 @@
|
||||||
|
package com.baeldung.passwordvalidation;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class PasswordValidationUsingRegexUnitTest {
|
||||||
|
String password = "Baeldung20@";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringPassword_whenUsingDynamicPasswordValidationRules_thenCheckIfPasswordValid() {
|
||||||
|
boolean result = false;
|
||||||
|
try {
|
||||||
|
if (password != null) {
|
||||||
|
String MIN_LENGTH = "8";
|
||||||
|
String MAX_LENGTH = "20";
|
||||||
|
boolean SPECIAL_CHAR_NEEDED = false;
|
||||||
|
|
||||||
|
String ONE_DIGIT = "(?=.*[0-9])";
|
||||||
|
String LOWER_CASE = "(?=.*[a-z])";
|
||||||
|
String UPPER_CASE = "(?=.*[A-Z])";
|
||||||
|
String SPECIAL_CHAR = SPECIAL_CHAR_NEEDED ? "(?=.*[@#$%^&+=])" : "";
|
||||||
|
String NO_SPACE = "(?=\\S+$)";
|
||||||
|
|
||||||
|
String MIN_MAX_CHAR = ".{" + MIN_LENGTH + "," + MAX_LENGTH + "}";
|
||||||
|
String PATTERN = ONE_DIGIT + LOWER_CASE + UPPER_CASE + SPECIAL_CHAR + NO_SPACE + MIN_MAX_CHAR;
|
||||||
|
|
||||||
|
assertTrue(password.matches(PATTERN));
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception ex) {
|
||||||
|
ex.printStackTrace();
|
||||||
|
fail("Exception occurred: " + ex.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenStringPassword_whenUsingRegulaExpressions_thenCheckIfPasswordValid() {
|
||||||
|
|
||||||
|
|
||||||
|
String regExpn =
|
||||||
|
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";
|
||||||
|
|
||||||
|
Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
|
||||||
|
Matcher matcher = pattern.matcher(password);
|
||||||
|
|
||||||
|
assertTrue(matcher.matches());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -6,4 +6,5 @@ This module contains articles about core Java Security
|
||||||
- [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign)
|
- [Check if Certificate Is Self-Signed or CA-Signed With Java](https://www.baeldung.com/java-check-certificate-sign)
|
||||||
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
|
- [Extract CN From X509 Certificate in Java](https://www.baeldung.com/java-extract-common-name-x509-certificate)
|
||||||
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
|
- [Check Certificate Name and Alias in Keystore File](https://www.baeldung.com/java-keystore-check-certificate-name-alias)
|
||||||
|
- [Using a Custom TrustStore in Java](https://www.baeldung.com/java-custom-truststore)
|
||||||
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)
|
- More articles: [[<-- prev]](/core-java-modules/core-java-security-3)
|
||||||
|
|
|
@ -0,0 +1,32 @@
|
||||||
|
package com.baeldung.enablessldebug;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import javax.net.ssl.HttpsURLConnection;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class SSLDebugLogger {
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(SSLDebugLogger.class);
|
||||||
|
|
||||||
|
public static void enableSSLDebugUsingSystemProperties() {
|
||||||
|
System.setProperty("javax.net.debug", "ssl");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void makeHttpsRequest() throws Exception {
|
||||||
|
String url = "https://github.com/eugenp/tutorials";
|
||||||
|
URL httpsUrl = new URL(url);
|
||||||
|
HttpsURLConnection connection = (HttpsURLConnection) httpsUrl.openConnection();
|
||||||
|
|
||||||
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
|
||||||
|
String line;
|
||||||
|
logger.info("Response from " + url + ":");
|
||||||
|
while ((line = reader.readLine()) != null) {
|
||||||
|
logger.info(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,49 @@
|
||||||
|
package com.baeldung.enablessldebug;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.util.logging.ConsoleHandler;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.LogManager;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
public class SSLDebugLoggerUnitTest {
|
||||||
|
@Test
|
||||||
|
void givenSSLDebuggingEnabled_whenUsingSystemProperties_thenEnableSSLDebugLogging() throws Exception {
|
||||||
|
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
System.setErr(new PrintStream(outContent));
|
||||||
|
|
||||||
|
SSLDebugLogger.enableSSLDebugUsingSystemProperties();
|
||||||
|
assertEquals("ssl", System.getProperty("javax.net.debug"));
|
||||||
|
|
||||||
|
SSLDebugLogger.makeHttpsRequest();
|
||||||
|
assertTrue(outContent.toString().contains("javax.net.ssl|DEBUG|"));
|
||||||
|
outContent.reset();
|
||||||
|
|
||||||
|
System.clearProperty("javax.net.debug");
|
||||||
|
assertNull(System.getProperty("javax.net.debug"));
|
||||||
|
|
||||||
|
SSLDebugLogger.makeHttpsRequest();
|
||||||
|
assertEquals(outContent.toString(),"");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenSSLDebuggingEnabled_whenUsingConfigurationFile_thenEnableSSLDebugLogging() throws IOException {
|
||||||
|
InputStream configFile = SSLDebugLoggerUnitTest.class.getClassLoader().getResourceAsStream("logging.properties");
|
||||||
|
LogManager.getLogManager().readConfiguration(configFile);
|
||||||
|
|
||||||
|
Logger sslLogger = Logger.getLogger("javax.net.ssl");
|
||||||
|
ConsoleHandler consoleHandler = (ConsoleHandler) sslLogger.getHandlers()[0];
|
||||||
|
Level consoleHandlerLevel = consoleHandler.getLevel();
|
||||||
|
|
||||||
|
assertEquals(Level.ALL, consoleHandlerLevel, "SSL ConsoleHandler level should be ALL");
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
java.util.logging.ConsoleHandler.level=ALL
|
||||||
|
javax.net.ssl.handlers=java.util.logging.ConsoleHandler
|
||||||
|
javax.net.ssl.level=ALL
|
|
@ -4,3 +4,4 @@ This module contains articles about string-related algorithms.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Rotating a Java String By n Characters](https://www.baeldung.com/java-rotate-string-by-n-characters)
|
- [Rotating a Java String By n Characters](https://www.baeldung.com/java-rotate-string-by-n-characters)
|
||||||
|
- [Remove Characters From a String That Are in the Other String](https://www.baeldung.com/java-strings-character-difference)
|
||||||
|
|
|
@ -5,4 +5,4 @@
|
||||||
- [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map)
|
- [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map)
|
||||||
- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)
|
- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)
|
||||||
- [How to Convert an Object to String](https://www.baeldung.com/java-object-string-representation)
|
- [How to Convert an Object to String](https://www.baeldung.com/java-object-string-representation)
|
||||||
- [Convert String to long or Long in Java](https://www.baeldung.com/java-convert-string-to-long)
|
- [Convert String to long or Long in Java](https://www.baeldung.com/java-convert-string-long)
|
||||||
|
|
|
@ -3,7 +3,12 @@
|
||||||
- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)
|
- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output)
|
||||||
- [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word)
|
- [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word)
|
||||||
- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters)
|
- [Check if a String Contains Only Unicode Letters](https://www.baeldung.com/java-string-all-unicode-characters)
|
||||||
- [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string)
|
- [Create a “Mutable” String in Java](https://www.baeldung.com/java-mutable-string)
|
||||||
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
|
- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence)
|
||||||
- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank)
|
- [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank)
|
||||||
- [String’s Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length)
|
- [String’s Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length)
|
||||||
|
- [Java’s String.length() and String.getBytes().length](https://www.baeldung.com/java-string-length-vs-getbytes-length)
|
||||||
|
- [Replace Non-Printable Unicode Characters in Java](https://www.baeldung.com/java-replace-non-printable-unicode-characters)
|
||||||
|
- [Check If a Java StringBuilder Object Contains a Character](https://www.baeldung.com/java-check-stringbuilder-object-contains-character)
|
||||||
|
- [Comparing One String With Multiple Values in One Expression in Java](https://www.baeldung.com/java-compare-string-multiple-values-one-expression)
|
||||||
|
- [UTF-8 Validation in Java](https://www.baeldung.com/java-utf-8-validation)
|
||||||
|
|
|
@ -39,6 +39,11 @@
|
||||||
<artifactId>icu4j</artifactId>
|
<artifactId>icu4j</artifactId>
|
||||||
<version>${icu4j.version}</version>
|
<version>${icu4j.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-collections4</artifactId>
|
||||||
|
<version>${apache.commons.collection.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter</artifactId>
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
@ -75,6 +80,7 @@
|
||||||
<maven.compiler.source>11</maven.compiler.source>
|
<maven.compiler.source>11</maven.compiler.source>
|
||||||
<maven.compiler.target>11</maven.compiler.target>
|
<maven.compiler.target>11</maven.compiler.target>
|
||||||
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
|
<apache.commons.lang3.version>3.13.0</apache.commons.lang3.version>
|
||||||
|
<apache.commons.collection.version>4.4</apache.commons.collection.version>
|
||||||
<apache.tika.version>2.9.1</apache.tika.version>
|
<apache.tika.version>2.9.1</apache.tika.version>
|
||||||
<commons-text.version>1.10.0</commons-text.version>
|
<commons-text.version>1.10.0</commons-text.version>
|
||||||
<icu4j.version>74.1</icu4j.version>
|
<icu4j.version>74.1</icu4j.version>
|
||||||
|
|
|
@ -0,0 +1,103 @@
|
||||||
|
package com.baeldung.morse;
|
||||||
|
|
||||||
|
import org.apache.commons.collections4.BidiMap;
|
||||||
|
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
|
||||||
|
|
||||||
|
public class MorseTranslator {
|
||||||
|
|
||||||
|
private static final BidiMap<String, String> morseAlphabet = new DualHashBidiMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
morseAlphabet.put("A", ".-");
|
||||||
|
morseAlphabet.put("B", "-...");
|
||||||
|
morseAlphabet.put("C", "-.-.");
|
||||||
|
morseAlphabet.put("D", "-..");
|
||||||
|
morseAlphabet.put("E", ".");
|
||||||
|
morseAlphabet.put("F", "..-.");
|
||||||
|
morseAlphabet.put("G", "--.");
|
||||||
|
morseAlphabet.put("H", "....");
|
||||||
|
morseAlphabet.put("I", "..");
|
||||||
|
morseAlphabet.put("J", ".---");
|
||||||
|
morseAlphabet.put("K", "-.-");
|
||||||
|
morseAlphabet.put("L", ".-..");
|
||||||
|
morseAlphabet.put("M", "--");
|
||||||
|
morseAlphabet.put("N", "-.");
|
||||||
|
morseAlphabet.put("O", "---");
|
||||||
|
morseAlphabet.put("P", ".--.");
|
||||||
|
morseAlphabet.put("Q", "--.-");
|
||||||
|
morseAlphabet.put("R", ".-.");
|
||||||
|
morseAlphabet.put("S", "...");
|
||||||
|
morseAlphabet.put("T", "-");
|
||||||
|
morseAlphabet.put("U", "..-");
|
||||||
|
morseAlphabet.put("V", "...-");
|
||||||
|
morseAlphabet.put("W", ".--");
|
||||||
|
morseAlphabet.put("X", "-..-");
|
||||||
|
morseAlphabet.put("Y", "-.--");
|
||||||
|
morseAlphabet.put("Z", "--..");
|
||||||
|
morseAlphabet.put("0", "-----");
|
||||||
|
morseAlphabet.put("1", ".----");
|
||||||
|
morseAlphabet.put("2", "..---");
|
||||||
|
morseAlphabet.put("3", "...--");
|
||||||
|
morseAlphabet.put("4", "....-");
|
||||||
|
morseAlphabet.put("5", ".....");
|
||||||
|
morseAlphabet.put("6", "-....");
|
||||||
|
morseAlphabet.put("7", "--...");
|
||||||
|
morseAlphabet.put("8", "---..");
|
||||||
|
morseAlphabet.put("9", "----.");
|
||||||
|
morseAlphabet.put(".", ".-.-.-");
|
||||||
|
morseAlphabet.put(",", "--..--");
|
||||||
|
morseAlphabet.put("?", "..--..");
|
||||||
|
morseAlphabet.put("'", ".----.");
|
||||||
|
morseAlphabet.put("!", "-.-.-----.");
|
||||||
|
morseAlphabet.put("/", "-..-.");
|
||||||
|
morseAlphabet.put("(", "-.--.");
|
||||||
|
morseAlphabet.put(")", "-.--.-");
|
||||||
|
morseAlphabet.put("&", ".-...");
|
||||||
|
morseAlphabet.put(":", "---...");
|
||||||
|
morseAlphabet.put(";", "-.-.-.");
|
||||||
|
morseAlphabet.put("=", "-...-");
|
||||||
|
morseAlphabet.put("+", ".-.-.");
|
||||||
|
morseAlphabet.put("-", "-....-");
|
||||||
|
morseAlphabet.put("_", "..--.-");
|
||||||
|
morseAlphabet.put("\"", ".-..-.");
|
||||||
|
morseAlphabet.put("$", "...-..-");
|
||||||
|
morseAlphabet.put("@", ".--.-.");
|
||||||
|
morseAlphabet.put(" ", "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
static String englishToMorse(String english) {
|
||||||
|
if (english == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String upperCaseEnglish = english.toUpperCase();
|
||||||
|
String[] morse = new String[upperCaseEnglish.length()];
|
||||||
|
for (int index = 0; index < upperCaseEnglish.length(); index++) {
|
||||||
|
String morseCharacter = morseAlphabet.get(String.valueOf(upperCaseEnglish.charAt(index)));
|
||||||
|
if (morseCharacter == null) {
|
||||||
|
throw new IllegalArgumentException("Character " + upperCaseEnglish.charAt(index) + " can't be translated to morse");
|
||||||
|
}
|
||||||
|
morse[index] = morseCharacter;
|
||||||
|
}
|
||||||
|
return String.join(" ", morse);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String morseToEnglish(String morse) {
|
||||||
|
if (morse == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (morse.isEmpty()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String[] morseUnitCharacters = morse.split(" ");
|
||||||
|
StringBuilder stringBuilder = new StringBuilder();
|
||||||
|
for (int index = 0; index < morseUnitCharacters.length; index ++) {
|
||||||
|
String englishCharacter = morseAlphabet.getKey(morseUnitCharacters[index]);
|
||||||
|
if (englishCharacter == null) {
|
||||||
|
throw new IllegalArgumentException("Character " + morseUnitCharacters[index] + " is not a valid morse character");
|
||||||
|
}
|
||||||
|
stringBuilder.append(englishCharacter);
|
||||||
|
}
|
||||||
|
return stringBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,33 @@
|
||||||
|
package com.baeldung.checkifstringcontainsinvalidcharacters;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.charset.*;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
public class CheckIfStringContainsInvalidEncodedCharactersUnitTest {
|
||||||
|
|
||||||
|
public String input = "HÆllo, World!";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInputString_whenUsingRegexPattern_thenFindIfInvalidCharacters() {
|
||||||
|
String regexPattern = "[^\\x00-\\x7F]+";
|
||||||
|
Pattern pattern = Pattern.compile(regexPattern);
|
||||||
|
Matcher matcher = pattern.matcher(input);
|
||||||
|
assertTrue(matcher.find());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInputString_whenUsingStringEncoding_thenFindIfInvalidCharacters() {
|
||||||
|
byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
|
||||||
|
boolean found = false;
|
||||||
|
for (byte b : bytes) {
|
||||||
|
found = (b & 0xFF) > 127 ? true : found;
|
||||||
|
}
|
||||||
|
assertTrue(found);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
package com.baeldung.morse;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
|
import org.junit.jupiter.params.provider.ValueSource;
|
||||||
|
|
||||||
|
public class MorseTranslatorUnitTest {
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@ValueSource(strings = {"MORSE CODE!", "morse code!", "mOrSe cOdE!"})
|
||||||
|
void givenAValidEnglishWordWhateverTheCapitalization_whenEnglishToMorse_thenTranslatedToMorse(String english) {
|
||||||
|
assertEquals("-- --- .-. ... . / -.-. --- -.. . -.-.-----.", MorseTranslator.englishToMorse(english));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAnEnglishWordWithAnIllegalCharacter_whenEnglishToMorse_thenThrows() {
|
||||||
|
String english = "~This sentence starts with an illegal character";
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> MorseTranslator.englishToMorse(english));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNull_whenEnglishToMorse_thenNull() {
|
||||||
|
assertNull(MorseTranslator.englishToMorse(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenEmptyString_whenEnglishToMorse_thenEmptyArray() {
|
||||||
|
assertEquals("", MorseTranslator.englishToMorse(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAValidMorseWord_whenMorseToEnglish_thenTranslatedToUpperCaseEnglish() {
|
||||||
|
assertEquals("MORSE CODE!", MorseTranslator.morseToEnglish("-- --- .-. ... . / -.-. --- -.. . -.-.-----."));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenAMorseWordWithAnIllegalCharacter_whenMorseToEnglish_thenThrows() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> MorseTranslator.morseToEnglish(".!!!!!!!"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenNull_whenMorseToEnglish_thenNull() {
|
||||||
|
assertNull(MorseTranslator.morseToEnglish(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void givenEmptyArray_whenMorseToEnglish_thenEmptyString() {
|
||||||
|
assertEquals("", MorseTranslator.morseToEnglish(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -8,3 +8,4 @@ This module contains articles about the sun package
|
||||||
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
|
||||||
- [Why Is sun.misc.Unsafe.park Actually Unsafe?](https://www.baeldung.com/java-sun-misc-unsafe-park-reason)
|
- [Why Is sun.misc.Unsafe.park Actually Unsafe?](https://www.baeldung.com/java-sun-misc-unsafe-park-reason)
|
||||||
- [Sharing Memory Between JVMs](https://www.baeldung.com/java-sharing-memory-between-jvms)
|
- [Sharing Memory Between JVMs](https://www.baeldung.com/java-sharing-memory-between-jvms)
|
||||||
|
- [Parse Java Source Code and Extract Methods](https://www.baeldung.com/java-parse-code-extract-methods)
|
||||||
|
|
|
@ -3,8 +3,8 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>core-java-string-swing</artifactId>
|
<artifactId>core-java-swing</artifactId>
|
||||||
<name>core-java-string-swing</name>
|
<name>core-java-swing</name>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -7,3 +7,4 @@ This module contains articles about the measurement of time in Java.
|
||||||
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
|
||||||
- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time)
|
- [Overriding System Time for Testing in Java](https://www.baeldung.com/java-override-system-time)
|
||||||
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
|
||||||
|
- [Java System.currentTimeMillis() Vs. System.nanoTime()](https://www.baeldung.com/java-system-currenttimemillis-vs-system-nanotime)
|
||||||
|
|
|
@ -112,6 +112,7 @@
|
||||||
<module>core-java-datetime-string-2</module>
|
<module>core-java-datetime-string-2</module>
|
||||||
<module>core-java-date-operations-2</module>
|
<module>core-java-date-operations-2</module>
|
||||||
<module>core-java-date-operations-3</module>
|
<module>core-java-date-operations-3</module>
|
||||||
|
<module>core-java-date-operations-4</module>
|
||||||
<module>core-java-documentation</module>
|
<module>core-java-documentation</module>
|
||||||
<module>core-java-exceptions</module>
|
<module>core-java-exceptions</module>
|
||||||
<module>core-java-exceptions-2</module>
|
<module>core-java-exceptions-2</module>
|
||||||
|
@ -199,6 +200,7 @@
|
||||||
<module>core-java-string-operations-7</module>
|
<module>core-java-string-operations-7</module>
|
||||||
<module>core-java-regex</module>
|
<module>core-java-regex</module>
|
||||||
<module>core-java-regex-2</module>
|
<module>core-java-regex-2</module>
|
||||||
|
<module>core-java-regex-3</module>
|
||||||
<module>core-java-uuid</module>
|
<module>core-java-uuid</module>
|
||||||
<module>core-java-collections-maps-6</module>
|
<module>core-java-collections-maps-6</module>
|
||||||
<module>core-java-records</module>
|
<module>core-java-records</module>
|
||||||
|
@ -209,6 +211,7 @@
|
||||||
<module>core-java-collections-set</module>
|
<module>core-java-collections-set</module>
|
||||||
<module>core-java-date-operations-1</module>
|
<module>core-java-date-operations-1</module>
|
||||||
<module>core-java-datetime-conversion</module>
|
<module>core-java-datetime-conversion</module>
|
||||||
|
<module>core-java-datetime-conversion-2</module>
|
||||||
<module>core-java-httpclient</module>
|
<module>core-java-httpclient</module>
|
||||||
<module>java-native</module>
|
<module>java-native</module>
|
||||||
<module>java-rmi</module>
|
<module>java-rmi</module>
|
||||||
|
|
|
@ -25,7 +25,7 @@
|
||||||
</dependencyManagement>
|
</dependencyManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<guava.version>32.1.3-jre</guava.version>
|
<guava.version>33.0.0-jre</guava.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -49,7 +49,7 @@
|
||||||
<maven.compiler.source>8</maven.compiler.source>
|
<maven.compiler.source>8</maven.compiler.source>
|
||||||
<maven.compiler.target>8</maven.compiler.target>
|
<maven.compiler.target>8</maven.compiler.target>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<guava.version>32.1.3-jre</guava.version>
|
<guava.version>33.0.0-jre</guava.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
|
@ -7,6 +7,8 @@ ext.javaMainClass = "com.baeldung.cmd.MainClass"
|
||||||
application {
|
application {
|
||||||
mainClassName = javaMainClass
|
mainClassName = javaMainClass
|
||||||
}
|
}
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
task propertyTypes(){
|
task propertyTypes(){
|
||||||
doLast{
|
doLast{
|
||||||
|
|
|
@ -5,6 +5,9 @@ ext {
|
||||||
awsVersion = '2.20.83'
|
awsVersion = '2.20.83'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation platform("software.amazon.awssdk:bom:$awsVersion")
|
implementation platform("software.amazon.awssdk:bom:$awsVersion")
|
||||||
|
|
|
@ -13,6 +13,8 @@ jar {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
application {
|
application {
|
||||||
mainClassName = javaMainClass
|
mainClassName = javaMainClass
|
||||||
|
|
|
@ -3,6 +3,9 @@ apply plugin: "eclipse"
|
||||||
apply plugin: "java"
|
apply plugin: "java"
|
||||||
|
|
||||||
description = "Source Sets example"
|
description = "Source Sets example"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
|
|
||||||
task printSourceSetInformation(){
|
task printSourceSetInformation(){
|
||||||
description = "Print source set information"
|
description = "Print source set information"
|
||||||
|
|
|
@ -1,6 +1,9 @@
|
||||||
|
|
||||||
description = "Gradle Unused Dependencies example"
|
description = "Gradle Unused Dependencies example"
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation('com.google.guava:guava:29.0-jre')
|
implementation('com.google.guava:guava:29.0-jre')
|
||||||
implementation('org.apache.httpcomponents:httpclient:4.5.12')
|
implementation('org.apache.httpcomponents:httpclient:4.5.12')
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung"
|
group = "com.baeldung"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api("io.reactivex.rxjava2:rxjava:2.2.16")
|
api("io.reactivex.rxjava2:rxjava:2.2.16")
|
||||||
|
|
|
@ -2,6 +2,9 @@ plugins {
|
||||||
`java-library`
|
`java-library`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api(project(":fibonacci-spi"))
|
api(project(":fibonacci-spi"))
|
||||||
compileOnly("com.google.auto.service:auto-service-annotations:1.0-rc6")
|
compileOnly("com.google.auto.service:auto-service-annotations:1.0-rc6")
|
||||||
|
|
|
@ -3,6 +3,9 @@ plugins {
|
||||||
`java-test-fixtures`
|
`java-test-fixtures`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
testFixturesApi("org.junit.jupiter:junit-jupiter-api:5.5.2")
|
testFixturesApi("org.junit.jupiter:junit-jupiter-api:5.5.2")
|
||||||
testFixturesImplementation("org.junit.jupiter:junit-jupiter-engine:5.5.2")
|
testFixturesImplementation("org.junit.jupiter:junit-jupiter-engine:5.5.2")
|
||||||
|
|
|
@ -2,6 +2,9 @@ plugins {
|
||||||
`java-platform`
|
`java-platform`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
constraints {
|
constraints {
|
||||||
api("org.apache.httpcomponents:fluent-hc:4.5.10")
|
api("org.apache.httpcomponents:fluent-hc:4.5.10")
|
||||||
|
|
|
@ -3,6 +3,9 @@ plugins {
|
||||||
`maven-publish`
|
`maven-publish`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
publishing {
|
publishing {
|
||||||
publications {
|
publications {
|
||||||
register<MavenPublication>("mavenJava") {
|
register<MavenPublication>("mavenJava") {
|
||||||
|
|
|
@ -2,6 +2,9 @@ plugins {
|
||||||
`java-library`
|
`java-library`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api(platform(project(":httpclient-platform")))
|
api(platform(project(":httpclient-platform")))
|
||||||
implementation("org.apache.httpcomponents:fluent-hc")
|
implementation("org.apache.httpcomponents:fluent-hc")
|
||||||
|
|
|
@ -2,6 +2,9 @@ plugins {
|
||||||
`java-library`
|
`java-library`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
api(platform(project(":httpclient-platform")))
|
api(platform(project(":httpclient-platform")))
|
||||||
implementation("org.apache.httpcomponents:httpclient")
|
implementation("org.apache.httpcomponents:httpclient")
|
||||||
|
|
|
@ -6,6 +6,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "0.0.1-SNAPSHOT"
|
version = "0.0.1-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "0.0.1-SNAPSHOT"
|
version = "0.0.1-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "0.0.1-SNAPSHOT"
|
version = "0.0.1-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "0.0.1-SNAPSHOT"
|
version = "0.0.1-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "0.0.1-SNAPSHOT"
|
version = "0.0.1-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group 'org.example'
|
group 'org.example'
|
||||||
version '1.0-SNAPSHOT'
|
version '1.0-SNAPSHOT'
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
javadoc {
|
javadoc {
|
||||||
destinationDir = file("${buildDir}/docs/javadoc")
|
destinationDir = file("${buildDir}/docs/javadoc")
|
||||||
|
|
|
@ -4,6 +4,8 @@ plugins {
|
||||||
|
|
||||||
group = 'org.baeldung'
|
group = 'org.baeldung'
|
||||||
version = '1.0-SNAPSHOT'
|
version = '1.0-SNAPSHOT'
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|
|
@ -3,6 +3,9 @@ plugins {
|
||||||
id 'com.github.bjornvester.wsdl2java' version '2.0.2'
|
id 'com.github.bjornvester.wsdl2java' version '2.0.2'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,8 @@ plugins {
|
||||||
|
|
||||||
group = "com.baeldung.gradle"
|
group = "com.baeldung.gradle"
|
||||||
version = "1.0.0-SNAPSHOT"
|
version = "1.0.0-SNAPSHOT"
|
||||||
|
sourceCompatibility = "1.8"
|
||||||
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenLocal()
|
mavenLocal()
|
||||||
|
|
|
@ -6,8 +6,8 @@ plugins {
|
||||||
apply plugin: 'application'
|
apply plugin: 'application'
|
||||||
mainClassName = 'employee.EmployeeApp'
|
mainClassName = 'employee.EmployeeApp'
|
||||||
|
|
||||||
sourceCompatibility = JavaVersion.VERSION_1_8
|
sourceCompatibility = "1.8"
|
||||||
targetCompatibility = JavaVersion.VERSION_1_8
|
targetCompatibility = "1.8"
|
||||||
|
|
||||||
println 'This is executed during configuration phase'
|
println 'This is executed during configuration phase'
|
||||||
|
|
||||||
|
|
|
@ -13,6 +13,9 @@ plugins {
|
||||||
id 'java'
|
id 'java'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,8 @@ group = 'com.baeldung'
|
||||||
// by default, pom's artifactId is taken from the directory name
|
// by default, pom's artifactId is taken from the directory name
|
||||||
|
|
||||||
version = '0.0.1'
|
version = '0.0.1'
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation 'org.slf4j:slf4j-api:1.7.25'
|
implementation 'org.slf4j:slf4j-api:1.7.25'
|
||||||
|
|
|
@ -13,6 +13,9 @@ plugins {
|
||||||
id 'java'
|
id 'java'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
targetCompatibility = JavaVersion.VERSION_1_8
|
||||||
|
|
||||||
apply from: 'aplugin.gradle'
|
apply from: 'aplugin.gradle'
|
||||||
apply plugin: 'org.shipkit.bintray-release'
|
apply plugin: 'org.shipkit.bintray-release'
|
||||||
|
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue