Merge branch 'master' of https://github.com/eugenp/tutorials into JAVA-3060

This commit is contained in:
chaos2418 2022-01-03 17:49:11 +05:30
commit e1b05f08c0
340 changed files with 4434 additions and 800 deletions

View File

@ -6,4 +6,5 @@ This module contains articles about Apache POI
- [Adding a Column to an Excel Sheet Using Apache POI](https://www.baeldung.com/java-excel-add-column)
- [Add an Image to a Cell in an Excel File With Java](https://www.baeldung.com/java-add-image-excel)
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
- More articles: [[<-- prev]](/apache-poi)

View File

@ -0,0 +1,19 @@
package com.baeldung.poi.excel.newcolumn.numeric;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelNumericFormat {
public static void applyNumericFormat(Workbook outWorkbook, Row row, Cell cell, Double value, String styleFormat) {
CellStyle style = outWorkbook.createCellStyle();
DataFormat format = outWorkbook.createDataFormat();
style.setDataFormat(format.getFormat(styleFormat));
cell.setCellValue(value);
cell.setCellStyle(style);
}
}

View File

@ -0,0 +1,105 @@
package com.baeldung.poi.excel.newcolumn.numeric;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
public class NumberCellValueUnitTest {
@Test
public void decimalDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalRoundedDisplay_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251123, "#,##0.0000");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251123, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalDisplayInXLS_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xls");
try (Workbook outWorkbook = new HSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, 10.251, "0.00");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new HSSFWorkbook(new FileInputStream(file))) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.251, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
@Test
public void decimalValue_whenAddedDouble_thenNumericCellCreated() throws IOException {
File file = new File("number_test.xlsx");
try (Workbook outWorkbook = new XSSFWorkbook()) {
Sheet sheet = outWorkbook.createSheet("Numeric Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
DecimalFormat df = new DecimalFormat("#,###.##");
ExcelNumericFormat.applyNumericFormat(outWorkbook, row, cell, Double.valueOf(df.format(10.251)), "#,###.##");
FileOutputStream fileOut = new FileOutputStream(file);
outWorkbook.write(fileOut);
fileOut.close();
}
try (Workbook inWorkbook = new XSSFWorkbook("number_test.xlsx")) {
Sheet sheet = inWorkbook.cloneSheet(0);
Row row = sheet.getRow(0);
Assertions.assertEquals(10.25, row.getCell(0)
.getNumericCellValue());
file.delete();
}
}
}

View File

@ -2,7 +2,6 @@ package com.baeldung.poi.excel.multilinetext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
public class MultilineText {
public void formatMultilineText(Cell cell, int cellNumber) {

View File

@ -111,7 +111,7 @@
<feign-core.version>11.2</feign-core.version>
<guice.version>5.0.1</guice.version>
<system-stubs-junit4.version>1.2.0</system-stubs-junit4.version>
<mockito-core.version>3.3.0</mockito-core.version>
<mockito-core.version>4.1.0</mockito-core.version>
<assertj-core.version>3.19.0</assertj-core.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
</properties>

View File

@ -20,12 +20,6 @@
<artifactId>aws-java-sdk</artifactId>
<version>${aws-java-sdk.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
@ -111,7 +105,6 @@
<aws-lambda-java-core.version>1.1.0</aws-lambda-java-core.version>
<gson.version>2.8.0</gson.version>
<aws-java-sdk.version>1.11.290</aws-java-sdk.version>
<mockito-core.version>2.21.0</mockito-core.version>
<dynamodblocal.version>1.11.86</dynamodblocal.version>
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
<commons-codec-version>1.10.L001</commons-codec-version>

View File

@ -9,3 +9,4 @@ This module contains articles about Java 11 core features
- [New Features in Java 11](https://www.baeldung.com/java-11-new-features)
- [Getting the Java Version at Runtime](https://www.baeldung.com/get-java-version-runtime)
- [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service)
- [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication)

View File

@ -2,12 +2,21 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.*;
import java.lang.module.ModuleDescriptor.Builder;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.lang.module.ModuleDescriptor.Provides;
import java.lang.module.ModuleDescriptor.Requires;
import java.sql.Date;
import java.sql.Driver;
import java.util.HashMap;
@ -16,7 +25,7 @@ import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
public class ModuleAPIUnitTest {
@ -28,14 +37,9 @@ public class ModuleAPIUnitTest {
@Before
public void setUp() {
Class<HashMap> hashMapClass = HashMap.class;
javaBaseModule = hashMapClass.getModule();
Class<Date> dateClass = Date.class;
javaSqlModule = dateClass.getModule();
Class<Person> personClass = Person.class;
module = personClass.getModule();
javaBaseModule = HashMap.class.getModule();
javaSqlModule = Date.class.getModule();
module = Person.class.getModule();
}
@Test
@ -111,7 +115,6 @@ public class ModuleAPIUnitTest {
}
@Test
@Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679
public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() {
Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides();
Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides();
@ -120,7 +123,7 @@ public class ModuleAPIUnitTest {
.map(Provides::service)
.collect(Collectors.toSet());
assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider"));
assertThat(javaBaseProvidesService, hasItem("java.nio.file.spi.FileSystemProvider"));
assertThat(javaSqlProvides, empty());
}
@ -132,15 +135,14 @@ public class ModuleAPIUnitTest {
.map(Exports::source)
.collect(Collectors.toSet());
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
assertThat(javaSqlExportsSource, hasItems("java.sql", "javax.sql"));
}
@Test
public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaSqlUses, contains("java.sql.Driver"));
assertThat(javaSqlUses, hasItem("java.sql.Driver"));
}
@Test

View File

@ -17,22 +17,45 @@ public class MapIteration {
System.out.println("Iterating Keys of Map Using KeySet");
mapIteration.iterateKeys(map);
System.out.println("Iterating Values of Map Using values()");
mapIteration.iterateValues(map);
System.out.println("Iterating Map Using Entry Set");
mapIteration.iterateUsingEntrySet(map);
System.out.println("Iterating Using Iterator and Map Entry");
mapIteration.iterateUsingIteratorAndEntry(map);
System.out.println("Iterating Using Iterator and KeySet");
mapIteration.iterateUsingIteratorAndKeySet(map);
System.out.println("Iterating values Using Iterator and values()");
mapIteration.iterateUsingIteratorAndValues(map);
System.out.println("Iterating Using KeySet and For Each");
mapIteration.iterateUsingKeySetAndForeach(map);
System.out.println("Iterating Map Using Lambda Expression");
mapIteration.iterateUsingLambda(map);
System.out.println("Iterating Map By Keys Using Lambda Expression");
mapIteration.iterateByKeysUsingLambda(map);
System.out.println("Iterating values Using Lambda Expression");
mapIteration.iterateValuesUsingLambda(map);
System.out.println("Iterating Using Stream API");
mapIteration.iterateUsingStreamAPI(map);
}
public void iterateUsingIteratorAndValues(Map<String, Integer> map) {
Iterator<Integer> iterator = map.values().iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println("value :" + value);
}
}
public void iterateUsingEntrySet(Map<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
@ -43,6 +66,14 @@ public class MapIteration {
map.forEach((k, v) -> System.out.println((k + ":" + v)));
}
public void iterateByKeysUsingLambda(Map<String, Integer> map) {
map.keySet().forEach(k -> System.out.println((k + ":" + map.get(k))));
}
public void iterateValuesUsingLambda(Map<String, Integer> map) {
map.values().forEach(v -> System.out.println(("value: " + v)));
}
public void iterateUsingIteratorAndEntry(Map<String, Integer> map) {
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet()
.iterator();
@ -52,6 +83,14 @@ public class MapIteration {
}
}
public void iterateUsingIteratorAndKeySet(Map<String, Integer> map) {
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + ":" + map.get(key));
}
}
public void iterateUsingKeySetAndForeach(Map<String, Integer> map) {
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
@ -68,7 +107,12 @@ public class MapIteration {
for (String key : map.keySet()) {
System.out.println(key);
}
}
public void iterateValues(Map<String, Integer> map) {
for (Integer value : map.values()) {
System.out.println(value);
}
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
public class VolatileVarNotThreadSafe {
private static final Logger LOG = LoggerFactory.getLogger(VolatileVarNotThreadSafe.class);
private static volatile int count = 0;
private static final int MAX_LIMIT = 1000;
public static void increment() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int index=0; index<MAX_LIMIT; index++) {
increment();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
LOG.info("value of counter variable: "+count);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.volatilekeywordthreadsafety;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class VolatileVarNotThreadSafeUnitTest {
@Test
public void whenCalledMainMethod_thenIncrementCount() throws InterruptedException {
VolatileVarNotThreadSafe.main(null);
Assertions.assertTrue(VolatileVarNotThreadSafe.getCount() > 0);
}
}

View File

@ -24,6 +24,22 @@
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<!-- Comment the arg below to print complete stack trace information -->
<!-- <arg>-g:none</arg>-->
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<h2.version>1.4.191</h2.version>
</properties>

View File

@ -0,0 +1,25 @@
package com.baeldung.unknownsourcestacktrace;
import com.baeldung.unknownsourcestacktrace.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final int SHORT_NAME_LIMIT = 10;
public static void main(String[] args) {
User user = new User();
user.setName("Tom");
logger.info(getGreetingMessage(user.getName()));
}
private static String getGreetingMessage(String name) {
return "Welcome " + getShortenedName(name) + "!";
}
private static String getShortenedName(String name) {
return name.substring(0, SHORT_NAME_LIMIT);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.unknownsourcestacktrace.dto;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -5,4 +5,5 @@ This module contains articles about core Java input and output (IO)
### Relevant Articles:
- [Java File Separator vs File Path Separator](https://www.baeldung.com/java-file-vs-file-path-separator)
- [Simulate touch Command in Java](https://www.baeldung.com/java-simulate-touch-command)
- [[<-- Prev]](/core-java-modules/core-java-io-3)

View File

@ -0,0 +1,45 @@
package com.baeldung.iostreams;
import java.io.*;
import java.util.List;
import java.util.Vector;
public class InputSequenceHandler {
private SequenceInputStream sequenceInputStream;
public InputSequenceHandler(Vector<InputStream> inputStreams) {
sequenceInputStream = new SequenceInputStream(inputStreams.elements());
}
public InputSequenceHandler(String file1, String file2) throws FileNotFoundException {
sequenceInputStream = new SequenceInputStream(new FileInputStream(file1), new FileInputStream(file2));
}
public InputSequenceHandler(List<String> fileNames) throws FileNotFoundException {
Vector<InputStream> inputStreams = new Vector<>();
for (String fileName: fileNames) {
inputStreams.add(new FileInputStream(fileName));
}
sequenceInputStream = new SequenceInputStream(inputStreams.elements());
}
public int read() throws IOException {
return sequenceInputStream.read();
}
public String readAsString() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
int readByte;
while ((readByte = sequenceInputStream.read()) != -1) {
stringBuilder.append((char) readByte);
}
return stringBuilder.toString();
}
public void close() throws IOException {
sequenceInputStream.close();
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.iostreams;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InputSequenceUnitTest {
private static final String FILE1 = "iostreams/File1.txt";
private static final String FILE2 = "iostreams/File2.txt";
private static final String FILE3 = "iostreams/File3.txt";
private static final String FILE1_AND_FILE2_CONTENT = "InputSequenceUnitTest";
private static final String ALL_FILES_CONTENT = "InputSequenceUnitTest is Success";
@Test
public void givenTwoFiles_readAsString() throws URISyntaxException, IOException {
String file1 = Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString();
String file2 = Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString();
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(file1, file2);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, FILE1_AND_FILE2_CONTENT);
}
@Test
public void givenFileList_readAsString() throws URISyntaxException, IOException {
List<String> filesList = new ArrayList<>();
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE1).toURI()).toString());
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE2).toURI()).toString());
filesList.add(Paths.get(ClassLoader.getSystemResource(FILE3).toURI()).toString());
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(filesList);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, ALL_FILES_CONTENT);
}
@Test
public void givenVectorOfInputStreams_readAsString() throws IOException {
String[] strings = {"Testing", "Leads", "to", "failure",
"and", "failure", "leads", "to", "understanding"};
Vector<InputStream> inputStreamVector = new Vector<>();
StringBuilder stringBuilder = new StringBuilder();
for (String string: strings) {
inputStreamVector.add(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
stringBuilder.append(string);
}
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(inputStreamVector);
String combinedString = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringBuilder.toString(), combinedString);
}
@Test
public void givenTwoStrings_readCombinedValue() throws IOException {
InputStream first = new ByteArrayInputStream("One".getBytes());
InputStream second = new ByteArrayInputStream("Magic".getBytes());
SequenceInputStream sequenceInputStream = new SequenceInputStream(first, second);
StringBuilder stringBuilder = new StringBuilder();
int byteValue;
while ((byteValue = sequenceInputStream.read()) != -1) {
stringBuilder.append((char) byteValue);
}
assertEquals("OneMagic", stringBuilder.toString());
}
}

View File

@ -0,0 +1 @@
InputSequence

View File

@ -0,0 +1 @@
UnitTest

View File

@ -0,0 +1 @@
is Success

View File

@ -9,3 +9,4 @@ This module contains article about constructors in Java
- [Private Constructors in Java](https://www.baeldung.com/java-private-constructors)
- [Throwing Exceptions in Constructors](https://www.baeldung.com/java-constructors-exceptions)
- [Constructors in Java Abstract Classes](https://www.baeldung.com/java-abstract-classes-constructors)
- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error)

View File

@ -5,4 +5,4 @@ This module contains articles about types in Java
### Relevant Articles:
- [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-find-enum-by-criteria)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)

View File

@ -15,6 +15,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>

View File

@ -0,0 +1,78 @@
package com.baeldung.getbit;
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class GetABitFromIntegralValueUnitTest {
@Test
public void givenAByte_whenUsingAHardCodedMask_thenGetBitValue() {
byte val1 = 0b0110_0100;
byte val2 = 0b0110_0010;
byte mask = 0b0000_0100;
boolean isSet1 = (val1 & mask) > 0;
boolean isSet2 = (val2 & mask) > 0;
assertTrue(isSet1);
assertFalse(isSet2);
}
@Test
public void givenAnIntValue_whenUsingACalculatedMask_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
int mask = 1 << pos;
boolean isSet = (val & mask) > 0;
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue1_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << (31 - pos)) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue2_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << (~pos & 31)) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingALeftShiftedValue3_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val << ~pos) < 0);
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingARightShiftedValue_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = ((val >> pos) & 1) == 1;
assertTrue(isSet);
}
@Test
public void givenAnIntValue_whenUsingBigInteger_thenGetBitValue() {
int val = 0b0110_0100;
int pos = 2;
boolean isSet = BigInteger.valueOf(val).testBit(pos);
assertTrue(isSet);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.serialization;
import java.io.Serializable;
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private volatile String name;
private Address address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@ -29,7 +29,7 @@ public class MySerializationUtils {
public static boolean isSerializable(Class<?> it) {
boolean serializable = it.isPrimitive() || it.isInterface() || Serializable.class.isAssignableFrom(it);
if (!serializable) {
return serializable;
return false;
}
Field[] declaredFields = it.getDeclaredFields();
for (Field field : declaredFields) {
@ -37,8 +37,10 @@ public class MySerializationUtils {
continue;
}
Class<?> fieldType = field.getType();
return isSerializable(fieldType);
if (!isSerializable(fieldType)) {
return false;
}
}
return serializable;
return true;
}
}

View File

@ -107,5 +107,7 @@ public class SerializationUnitTest {
assertFalse(MySerializationUtils.isSerializable(Address.class));
assertTrue(MySerializationUtils.isSerializable(Person.class));
assertTrue(MySerializationUtils.isSerializable(Integer.class));
assertFalse(MySerializationUtils.isSerializable(Customer.class));
assertTrue(MySerializationUtils.isSerializable(Employee.class));
}
}

View File

@ -0,0 +1,187 @@
package com.baeldung.stringtofloat;
import org.junit.jupiter.api.Test;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class StringToFloatConversionUnitTest {
@Test
public void givenFloat_whenStringConcatenation_thenReturnString() {
Float givenFloat = 1.25f;
String result = givenFloat + "";
assertEquals("1.25", result);
}
@Test
public void givenFloatPrimitive_whenStringConcatenation_thenReturnString() {
float givenFloat = 1.25f;
String result = givenFloat + "";
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenStringConcatenation_thenReturnNullString() {
Float givenFloat = null;
String result = givenFloat + "";
assertEquals("null", result);
}
@Test
public void givenFloat_whenToString_thenReturnString() {
Float givenFloat = 1.25f;
String result = Float.toString(givenFloat);
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenToString_thenThrowNullPointerException() {
Float givenFloat = null;
assertThrows(NullPointerException.class, () -> Float.toString(givenFloat));
}
@Test
public void givenFloat_whenValueOf_thenReturnString() {
Float givenFloat = 1.25f;
String result = String.valueOf(givenFloat);
assertEquals("1.25", result);
}
@Test
public void givenNullFloat_whenValueOf_thenReturnNullString() {
Float givenFloat = null;
String result = String.valueOf(givenFloat);
assertEquals("null", result);
}
@Test
public void givenFloat_whenDecimalFormat_thenReturnString() {
Float givenFloat = 1.25f;
String result = new DecimalFormat("#.0000").format(givenFloat);
assertEquals("1.2500", result);
}
@Test
public void givenFloat_whenDecimalFormat_thenReturnWholeNumberString() {
Float givenFloat = 1.0025f;
String result = new DecimalFormat("#.##").format(givenFloat);
assertEquals("1", result);
}
@Test
public void givenNullFloat_whenDecimalFormat_thenThrowIllegalArgumentException() {
Float givenFloat = null;
assertThrows(IllegalArgumentException.class, () -> new DecimalFormat("#.000").format(givenFloat));
}
@Test
public void givenFloat_whenStringFormat_thenReturnString() {
Float givenFloat = 1.25f;
String result = String.format("%f", givenFloat);
assertEquals("1.250000", result);
}
@Test
public void givenFloat_whenStringFormatWithDecimalLimit_thenReturnRoundedString() {
Float givenFloat = 1.256f;
String result = String.format("%.2f", givenFloat);
assertEquals("1.26", result);
}
@Test
public void givenNullFloat_whenStringFormatWithDecimalLimit_thenReturnNullString() {
Float givenFloat = null;
String result = String.format("%f", givenFloat);
assertEquals("null", result);
}
@Test
public void givenString_whenParseFloat_thenReturnFloat() {
String givenString = "1.25";
float result = Float.parseFloat(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenNullString_whenParseFloat_thenThrowNullPointerException() {
String givenString = null;
assertThrows(NullPointerException.class, () -> Float.parseFloat(givenString));
}
@Test
public void givenNonParsableString_whenParseFloat_thenThrowNumberFormatException() {
String givenString = "1.23x";
assertThrows(NumberFormatException.class, () -> Float.parseFloat(givenString));
}
@Test
public void givenString_whenValueOf_thenReturnFloat() {
String givenString = "1.25";
Float result = Float.valueOf(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenNonParsableString_whenValueOf_thenThrowNumberFormatException() {
String givenString = "1.25x";
assertThrows(NumberFormatException.class, () -> Float.valueOf(givenString));
}
@Test
public void givenString_whenConstructor_thenReturnFloat() {
String givenString = "1.25";
Float result = new Float(givenString);
assertEquals(1.25f, result);
}
@Test
public void givenString_whenDecimalFormat_thenReturnFloat() throws ParseException {
String givenString = "1,250";
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
DecimalFormat decimalFormat = new DecimalFormat("#.000");
decimalFormat.setDecimalFormatSymbols(symbols);
Float result = decimalFormat.parse(givenString).floatValue();
assertEquals(1.25f, result);
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.split;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
public class SplitStringEveryNthChar {
public static List<String> usingSplitMethod(String text, int n) {
String[] results = text.split("(?<=\\G.{" + n + "})");
return Arrays.asList(results);
}
public static List<String> usingSubstringMethod(String text, int n) {
List<String> results = new ArrayList<>();
int length = text.length();
for (int i = 0; i < length; i += n) {
results.add(text.substring(i, Math.min(length, i + n)));
}
return results;
}
public static List<String> usingPattern(String text, int n) {
List<String> results = new ArrayList<>();
Pattern pattern = Pattern.compile(".{1," + n + "}");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String match = text.substring(matcher.start(), matcher.end());
results.add(match);
}
return results;
}
public static List<String> usingGuava(String text, int n) {
Iterable<String> parts = Splitter.fixedLength(n)
.split(text);
return ImmutableList.copyOf(parts);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.equalsvscontentequals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class StringEqualsVsContentEqualsUnitTest {
String actualString = "baeldung";
String identicalString = "baeldung";
CharSequence identicalStringInstance = "baeldung";
CharSequence identicalStringBufferInstance = new StringBuffer("baeldung");
@Test
public void whenIdenticalTestString_thenBothTrue() {
assertTrue(actualString.equals(identicalString));
assertTrue(actualString.contentEquals(identicalString));
}
@Test
public void whenSameContentButDifferentType_thenEqualsIsFalseAndContentEqualsIsTrue() {
assertTrue(actualString.equals(identicalStringInstance));
assertTrue(actualString.contentEquals(identicalStringInstance));
assertFalse(actualString.equals(identicalStringBufferInstance));
assertTrue(actualString.contentEquals(identicalStringBufferInstance));
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.split;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import java.util.List;
import org.junit.jupiter.api.Test;
public class SplitStringEveryNthCharUnitTest {
public static final String TEXT = "abcdefgh123456";
@Test
public void givenString_whenUsingSplit_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingSplitMethod(TEXT, 3);
assertThat(results, contains("abc", "def", "gh1", "234", "56"));
}
@Test
public void givenString_whenUsingSubstring_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingSubstringMethod(TEXT, 4);
assertThat(results, contains("abcd", "efgh", "1234", "56"));
}
@Test
public void givenString_whenUsingPattern_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingPattern(TEXT, 5);
assertThat(results, contains("abcde", "fgh12", "3456"));
}
@Test
public void givenString_whenUsingGuava_thenSplit() {
List<String> results = SplitStringEveryNthChar.usingGuava(TEXT, 6);
assertThat(results, contains("abcdef", "gh1234", "56"));
}
}

View File

@ -43,12 +43,6 @@
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito-inline.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
@ -85,7 +79,7 @@
<lombok.version>1.18.22</lombok.version>
<asspectj.version>1.8.9</asspectj.version>
<jmockit.version>1.44</jmockit.version>
<mockito-inline.version>4.0.0</mockito-inline.version>
<mockito-inline.version>4.1.0</mockito-inline.version>
</properties>
</project>

View File

@ -0,0 +1,154 @@
package com.baeldung.javadoc;
public class CodeSnippetFormatting {
/**
* This is an example to show default behavior of code snippet formatting in Javadocs
*
* public class Application(){
*
* }
*
*/
public void showCodeSnippetFormatting() {
// do nothing
}
/**
* This is an example to show usage of HTML pre tag while code snippet formatting in Javadocs
*
* <pre>
* public class Application(){
* List<Integer> nums = new ArrayList<>();
* }
*
* </pre>
*/
public void showCodeSnippetFormattingUsingPRETag() {
// do nothing
}
/**
* This is an example to show usage of HTML character entities while code snippet formatting in Javadocs
*
* <pre>
* public class Application(){
* List&lt;Integer&gt; nums = new ArrayList<>();
* }
*
* </pre>
*/
public void showCodeSnippetFormattingUsingCharacterEntities() {
// do nothing
}
/**
* This is an example to show usage of javadoc code tag while code snippet formatting in Javadocs
*
* <pre>
*
* public class Application(){
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetFormattingUsingCodeTag() {
// do nothing
}
/**
* This is an example to show issue faced while using annotations in Javadocs
*
* <pre>
*
* public class Application(){
* @Getter
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetFormattingIssueUsingCodeTag() {
// do nothing
}
/**
* This is an example to show usage of javadoc code tag for handling '@' character
*
* <pre>
*
* public class Application(){
* {@code @Getter}
* {@code List<Integer> nums = new ArrayList<>(); }
* }
*
* </pre>
*/
public void showCodeSnippetAnnotationFormattingUsingCodeTag() {
// do nothing
}
/**
* This is an example to show difference in javadoc literal and code tag
*
* <p>
*
* {@literal @Getter}
* {@literal List<Integer> nums = new ArrayList<>(); }
*
* <br />
* {@code @Getter}
* {@code List<Integer> nums = new ArrayList<>(); }
* </p>
*/
public void showCodeSnippetCommentsFormattingUsingCodeAndLiteralTag() {
// do nothing
}
/**
* This is an example to illustrate a basic jQuery code snippet embedded in documentation comments
* <pre>
* {@code <script>}
* $document.ready(function(){
* console.log("Hello World!);
* })
* {@code </script>}
* </pre>
*/
public void showJSCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>{@code
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>}
* </pre>
*
*/
public void showHTMLCodeSnippetUsingJavadoc() {
// do nothing
}
/**
* This is an example to illustrate an HTML code snippet embedded in documentation comments
* <pre>
* <html>
* <body>
* <h1>Hello World!</h1>
* </body>
* </html>
* </pre>
*
*/
public void showHTMLCodeSnippetIssueUsingJavadoc() {
// do nothing
}
}

View File

@ -86,11 +86,6 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>

View File

@ -191,7 +191,6 @@
<ethereumj-core.version>1.5.0-RELEASE</ethereumj-core.version>
<web3j.core.version>3.3.1</web3j.core.version>
<spring.boot.version>1.5.6.RELEASE</spring.boot.version>
<mockito.version>2.21.0</mockito.version>
<jsonpath.version>2.4.0</jsonpath.version>
<spring-boot-maven-plugin.version>2.0.4.RELEASE</spring-boot-maven-plugin.version>
<compiler.plugin.version>3.1</compiler.plugin.version>

11
jbang/hello.java Executable file
View File

@ -0,0 +1,11 @@
///usr/bin/env jbang "$0" "$@" ; exit $?
// //DEPS <dependency1> <dependency2>
import static java.lang.System.*;
public class hello {
public static void main(String... args) {
out.println("Hello World");
}
}

27
jbang/hellocli.java Executable file
View File

@ -0,0 +1,27 @@
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.5.0
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Parameters;
import java.util.concurrent.Callable;
@Command(name = "hellocli", mixinStandardHelpOptions = true, version = "hellocli 0.1",
description = "hellocli made with jbang")
class hellocli implements Callable<Integer> {
@Parameters(index = "0", description = "The greeting to print", defaultValue = "World!")
private String greeting;
public static void main(String... args) {
int exitCode = new CommandLine(new hellocli()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception { // your business logic goes here...
System.out.println("Hello " + greeting);
return 0;
}
}

18
jbang/index.html Normal file
View File

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JBang meets Quarkus</title>
</head>
<body>
<a href="/hello">Go Say Hello!</a>
<p>
Powered by:
<a href="https://jbang.dev"><img src="https://www.jbang.dev/assets/images/logo.png"/></a>
</p>
</body>
</html>

15
jbang/jbang-catalog.json Normal file
View File

@ -0,0 +1,15 @@
{
"catalogs": {},
"aliases": {
"hello": {
"script-ref": "hello.java"
},
"hellocli": {
"script-ref": "hellocli.java"
},
"jbangquarkus": {
"script-ref": "jbangquarkus.java"
}
},
"templates": {}
}

21
jbang/jbangquarkus.java Executable file
View File

@ -0,0 +1,21 @@
///usr/bin/env jbang "$0" "$@" ; exit $?
// Update the Quarkus version to what you want here or run jbang with
// `-Dquarkus.version=<version>` to override it.
//DEPS io.quarkus:quarkus-bom:${quarkus.version:2.4.0.Final}@pom
//DEPS io.quarkus:quarkus-resteasy
//JAVAC_OPTIONS -parameters
//FILES META-INF/resources/index.html=index.html
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("/hello")
@ApplicationScoped
public class jbangquarkus {
@GET
public String sayHello() {
return "Hello from Quarkus with jbang.dev";
}
}

View File

@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -64,7 +64,7 @@ public class AccountResourceIntegrationTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(anyObject());
doNothing().when(mockMailService).sendActivationEmail(any());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService);

View File

@ -26,7 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyObject;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ -64,7 +64,7 @@ public class AccountResourceIntegrationTest {
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(anyObject());
doNothing().when(mockMailService).sendActivationEmail(any());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService);

View File

@ -11,7 +11,7 @@ import static io.jsonwebtoken.SignatureAlgorithm.HS256;
public class JWTDecoderUtil {
public static String decodeJWTToken(String token) {
Base64.Decoder decoder = Base64.getDecoder();
Base64.Decoder decoder = Base64.getUrlDecoder();
String[] chunks = token.split("\\.");
@ -22,7 +22,7 @@ public class JWTDecoderUtil {
}
public static String decodeJWTToken(String token, String secretKey) throws Exception {
Base64.Decoder decoder = Base64.getDecoder();
Base64.Decoder decoder = Base64.getUrlDecoder();
String[] chunks = token.split("\\.");

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [How to Use Command Line Arguments in a Bash Script](https://www.baeldung.com/linux/use-command-line-arguments-in-bash-script)
- [Concatenate Two Strings to Build a Complete Path in Linux](https://www.baeldung.com/linux/concatenate-strings-to-build-path)

View File

@ -15,3 +15,4 @@ This module contains articles about Project Lombok.
- [Using Lomboks @Accessors Annotation](https://www.baeldung.com/lombok-accessors)
- [Omitting Getter or Setter in Lombok](https://www.baeldung.com/lombok-omit-getter-setter)
- [Declaring Val and Var Variables in Lombok](https://www.baeldung.com/java-lombok-val-var)
- [Lombok Using @With Annotations](https://www.baeldung.com/lombok-with-annotations)

8
lombok/lombok.config Normal file
View File

@ -0,0 +1,8 @@
import lombok_feature.config
config.stopBubbling = true
lombok.anyconstructor.addconstructorproperties=false
lombok.addLombokGeneratedAnnotation = true
lombok.addSuppressWarnings = false

View File

@ -0,0 +1 @@
lombok.experimental.flagUsage = warning

View File

@ -26,6 +26,11 @@
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>${hibernate-jpa-2.1-api.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>23.0.0</version>
</dependency>
</dependencies>
<build>
@ -70,7 +75,7 @@
<!-- various -->
<hibernate-jpa-2.1-api.version>1.0.0.Final</hibernate-jpa-2.1-api.version>
<!-- delombok maven plugin -->
<delombok-maven-plugin.version>1.18.10.0</delombok-maven-plugin.version>
<delombok-maven-plugin.version>1.18.20.0</delombok-maven-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,40 @@
package com.baeldung.lombok.configexamples;
import lombok.*;
import lombok.extern.java.Log;
import java.util.logging.Level;
import static java.lang.Math.abs;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Log
public class Account {
@NonNull
private Double balance = 0.;
@NonNull
private String accountHolder = "";
public Account addBalance(double amount) {
if (amount < 0) {
throw new IllegalArgumentException("Can not add negative amount");
}
this.balance += amount;
return this;
}
public Account withdraw(double amount) {
if (this.balance - abs(amount) < 0) {
domainLog.log(Level.INFO, String.format("Transaction denied for account holder: %s", this.accountHolder));
throw new IllegalArgumentException(String.format("Not enough balance, you have %.2f", this.balance));
}
this.balance -= abs(amount);
return this;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.lombok.configexamples;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;
@AllArgsConstructor
@Getter
@Accessors(prefix = {"op"})
public class TransactionLog {
double amount;
String description;
}

View File

@ -0,0 +1,6 @@
clear lombok.experimental.flagUsage
lombok.anyconstructor.addconstructorproperties=true
lombok.addNullAnnotations = jetbrains
lombok.accessors.chain = true
lombok.log.fieldName = domainLog

View File

@ -0,0 +1,50 @@
package com.baeldung.lombok.configexamples;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AccountUnitTest {
@Test
void should_initialize_account() {
Account myAccount = new Account()
.setBalance(2000.00)
.setAccountHolder("John Snow");
assertEquals(2000.00, myAccount.getBalance());
assertEquals("John Snow", myAccount.getAccountHolder());
}
@Test
void should_throw_error_when_balance_becomes_negative() {
Account myAccount = new Account()
.setBalance(20.00)
.setAccountHolder("John Snow");
assertThrows(IllegalArgumentException.class, () -> myAccount.withdraw(100.00));
}
@Test
void should_throw_no_error_when_balance_becomes_zero() {
Account myAccount = new Account()
.setBalance(20.00)
.setAccountHolder("John Snow");
myAccount.withdraw(20.00);
assertEquals(0.00, myAccount.getBalance());
}
@Test
void should_update_balance_properly() {
Account myAccount = new Account()
.setBalance(20.00)
.setAccountHolder("John Snow");
myAccount.withdraw(5.00).withdraw(10.00);
assertEquals(5.00, myAccount.getBalance());
}
}

View File

@ -78,7 +78,7 @@
<dependency>
<groupId>com.netflix.spectator</groupId>
<artifactId>spectator-api</artifactId>
<version>0.132.0</version>
<version>1.0.11</version>
</dependency>
</dependencies>
@ -92,4 +92,4 @@
<metrics-aspectj.version>1.1.0</metrics-aspectj.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,221 @@
package com.baeldung.metrics.spectator;
import com.netflix.spectator.api.*;
import com.netflix.spectator.api.patterns.LongTaskTimer;
import com.netflix.spectator.api.patterns.PolledMeter;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SpectatorMetersUnitTest {
@Test
public void spectatorCounterTest(){
class MyListProcessor {
private final Counter insertCounter;
private final Counter removeCounter;
List<String> requestList = new ArrayList();
private MyListProcessor(Registry registry){
insertCounter = registry.counter("list.insert.count");
removeCounter = registry.counter("list.remove.count");
}
private void addToList(String element){
requestList.add(element);
insertCounter.increment();
}
private void removeFromList(){
requestList.remove(0);
removeCounter.increment();
}
}
MyListProcessor myListProcessor = new MyListProcessor(new DefaultRegistry());
myListProcessor.addToList("element1");
myListProcessor.addToList("element2");
myListProcessor.addToList("element3");
myListProcessor.removeFromList();
assertEquals(3, myListProcessor.insertCounter.count());
assertEquals(1, myListProcessor.removeCounter.count());
}
@Test
public void spectatorTimerTest() throws Exception {
class MyRequestProcessor {
private final Timer requestLatency;
private MyRequestProcessor(Registry registry) {
requestLatency = registry.timer("app.request.latency");
}
private String processRequest(int input) throws Exception {
return requestLatency.record(() -> handleRequest(input));
}
private String handleRequest(int input) throws InterruptedException {
try {
Thread.sleep(input);
return "Done";
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
}
}
}
MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry());
myRequestProcessor.processRequest(3000);
assertEquals(1, myRequestProcessor.requestLatency.count());
assertThat(myRequestProcessor.requestLatency.totalTime()).isBetween(3000000000L, 4000000000L);
}
@Test
public void spectatorLongTaskTimerTest() throws Exception {
class MyRequestProcessor {
private final LongTaskTimer refreshDuration;
private long duration;
private MyRequestProcessor(Registry registry) {
refreshDuration = LongTaskTimer.get(registry, registry.createId("metadata.refreshDuration"));
}
private String processRequest(int input) throws Exception {
final long taskId = refreshDuration.start();
try {
Thread.sleep(input);
return "Done";
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
} finally {
refreshDuration.stop(taskId);
}
}
}
MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry());
myRequestProcessor.processRequest(3000);
System.out.println(myRequestProcessor.refreshDuration.measure());
System.out.println(myRequestProcessor.duration);
System.out.println(myRequestProcessor.refreshDuration.duration());
}
@Test
public void spectatorGauges_polledMeter_Test(){
class MyList {
private List<String> list = new ArrayList();;
private AtomicInteger listSize = new AtomicInteger(0);
private MyList(Registry registry) {
PolledMeter.using(registry)
.withName("list.size")
.monitorValue(listSize);
}
private void addToList(String element){
list.add(element);
listSize.incrementAndGet();
}
private void removeFromList(){
list.remove(0);
listSize.decrementAndGet();
}
private int size(){
return list.size();
}
}
MyList myList = new MyList(new DefaultRegistry());
myList.addToList("element1");
myList.addToList("element2");
myList.addToList("element3");
myList.addToList("element4");
myList.removeFromList();
assertEquals(myList.size(), myList.listSize.get());
}
@Test
public void spectatorGauges_ActiveGauges_Test(){
class MyList {
private List<String> list = new ArrayList();;
private AtomicInteger listSize = new AtomicInteger(0);
private Gauge gauge;
private MyList(Registry registry) {
gauge = registry.gauge("list.size");
}
private void addToList(String element){
list.add(element);
listSize.incrementAndGet();
gauge.set(listSize.get());
}
private void removeFromList(){
list.remove(0);
listSize.decrementAndGet();
gauge.set(listSize.get());
}
private int size(){
return list.size();
}
}
MyList myList = new MyList(new DefaultRegistry());
myList.addToList("element1");
myList.addToList("element2");
myList.addToList("element3");
myList.addToList("element4");
myList.removeFromList();
assertEquals(3.0, myList.gauge.value());
}
@Test
public void spectatorDistributionSummaryTest() throws Exception {
class MyRequestProcessor {
private final DistributionSummary distributionSummary;
private MyRequestProcessor(Registry registry) {
distributionSummary = registry.distributionSummary("app.request.size");
}
private void processRequest(String input) throws Exception {
distributionSummary.record((long) input.length());
handleRequest();
}
private void handleRequest() throws InterruptedException {
try {
Thread.sleep(3000);
return;
} catch (InterruptedException e) {
e.printStackTrace();
throw e;
}
}
}
MyRequestProcessor myRequestProcessor = new MyRequestProcessor(new DefaultRegistry());
myRequestProcessor.processRequest("This is my sample input.");
assertEquals(1, myRequestProcessor.distributionSummary.count());
assertEquals("This is my sample input.".length(), (int) myRequestProcessor.distributionSummary.totalAmount());
}
}

View File

@ -4,3 +4,4 @@ This module contains articles about Micronaut.
### Relevant Articles:
- [Introduction to Micronaut Framework](https://www.baeldung.com/micronaut)
- [Micronaut vs. Spring Boot](https://www.baeldung.com/micronaut-vs-spring-boot)

View File

@ -4,6 +4,6 @@ import io.micronaut.runtime.Micronaut;
public class CompareApplication {
public static void main(String[] args) {
Micronaut.run(CompareApplication.class);
Micronaut.run(CompareApplication.class);
}
}

View File

@ -6,18 +6,18 @@ import io.micronaut.http.client.annotation.Client;
@Client("/math")
public interface ArithmeticClient {
@Get("/sum/{number1}/{number2}")
String sum(float number1, float number2);
@Get("/subtract/{number1}/{number2}")
String subtract(float number1, float number2);
@Get("/multiply/{number1}/{number2}")
String multiply(float number1, float number2);
@Get("/divide/{number1}/{number2}")
String divide(float number1, float number2);
@Get("/memory")
String memory();
@Get("/sum/{number1}/{number2}")
String sum(float number1, float number2);
@Get("/subtract/{number1}/{number2}")
String subtract(float number1, float number2);
@Get("/multiply/{number1}/{number2}")
String multiply(float number1, float number2);
@Get("/divide/{number1}/{number2}")
String divide(float number1, float number2);
@Get("/memory")
String memory();
}

View File

@ -8,34 +8,39 @@ import io.micronaut.http.client.annotation.Client;
@Singleton
public class ArithmeticClientImpl {
private RxHttpClient httpClient;
private RxHttpClient httpClient;
public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) {
this.httpClient = httpClient;
public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) {
this.httpClient = httpClient;
}
public String sum(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
HttpRequest<String> req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2);
return httpClient.retrieve(req)
.blockingFirst();
}
public String subtract(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
HttpRequest<String> req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2);
return httpClient.retrieve(req)
.blockingFirst();
}
public String multiply(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
HttpRequest<String> req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2);
return httpClient.retrieve(req)
.blockingFirst();
}
public String divide(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
HttpRequest<String> req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2);
return httpClient.retrieve(req)
.blockingFirst();
}
public String memory() {
HttpRequest<String> req = HttpRequest.GET("/math/memory");
return httpClient.retrieve(req).blockingFirst();
}
HttpRequest<String> req = HttpRequest.GET("/math/memory");
return httpClient.retrieve(req)
.blockingFirst();
}
}

View File

@ -14,45 +14,45 @@ import io.micronaut.http.annotation.Get;
public class ArithmeticController {
@Inject
private ArithmeticService arithmeticService;
@Get("/sum/{number1}/{number2}")
public float getSum(float number1, float number2) {
return arithmeticService.add(number1, number2);
return arithmeticService.add(number1, number2);
}
@Get("/subtract/{number1}/{number2}")
public float getDifference(float number1, float number2) {
return arithmeticService.subtract(number1, number2);
return arithmeticService.subtract(number1, number2);
}
@Get("/multiply/{number1}/{number2}")
public float getMultiplication(float number1, float number2) {
return arithmeticService.multiply(number1, number2);
return arithmeticService.multiply(number1, number2);
}
@Get("/divide/{number1}/{number2}")
public float getDivision(float number1, float number2) {
return arithmeticService.divide(number1, number2);
return arithmeticService.divide(number1, number2);
}
@Get("/memory")
public String getMemoryStatus() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
String memoryStats = "";
String init = String.format("Initial: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getInit() /1073741824);
String usedHeap = String.format("Used: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824);
String maxHeap = String.format("Max: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getMax() /1073741824);
String committed = String.format("Committed: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getCommitted() /1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
String memoryStats = "";
String init = String.format("Initial: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getInit() / 1073741824);
String usedHeap = String.format("Used: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getUsed() / 1073741824);
String maxHeap = String.format("Max: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getMax() / 1073741824);
String committed = String.format("Committed: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getCommitted() / 1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
}
}

View File

@ -5,21 +5,21 @@ import javax.inject.Singleton;
@Singleton
public class ArithmeticService {
public float add(float number1, float number2) {
return number1 + number2;
return number1 + number2;
}
public float subtract(float number1, float number2) {
return number1 - number2;
return number1 - number2;
}
public float multiply(float number1, float number2) {
return number1 * number2;
return number1 * number2;
}
public float divide(float number1, float number2) {
if (number2 == 0) {
throw new IllegalArgumentException("'number2' cannot be zero");
}
return number1 / number2;
if (number2 == 0) {
throw new IllegalArgumentException("'number2' cannot be zero");
}
return number1 / number2;
}
}

View File

@ -13,49 +13,49 @@ import org.junit.Test;
import com.baeldung.micronaut.vs.springboot.client.ArithmeticClientImpl;
public class ArithmeticClientUnitTest {
private EmbeddedServer server;
private EmbeddedServer server;
private ArithmeticClientImpl client;
@Before
public void setup() {
server = ApplicationContext.run(EmbeddedServer.class);
client = server.getApplicationContext().getBean(ArithmeticClientImpl.class);
client = server.getApplicationContext()
.getBean(ArithmeticClientImpl.class);
}
@After
public void cleanup() {
server.stop();
}
@Test
public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() {
String expected = Float.valueOf(10 + 20).toString();
assertEquals(expected, client.sum(10, 20));
String expected = Float.valueOf(10 + 20).toString();
assertEquals(expected, client.sum(10, 20));
}
@Test
public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() {
String expected = Float.valueOf(20 - 10).toString();
assertEquals(expected, client.subtract(20, 10));
String expected = Float.valueOf(20 - 10).toString();
assertEquals(expected, client.subtract(20, 10));
}
@Test
public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() {
String expected = Float.valueOf(10 * 20).toString();
assertEquals(expected, client.multiply(10, 20));
String expected = Float.valueOf(10 * 20).toString();
assertEquals(expected, client.multiply(10, 20));
}
@Test
public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() {
String expected = Float.valueOf(30 / 10).toString();
assertEquals(expected, client.divide(30, 10));
String expected = Float.valueOf(30 / 10).toString();
assertEquals(expected, client.divide(30, 10));
}
@Test
public void whenMemory_thenCorrectAnswerReturned() {
String expected = "Initial:";
assertThat(client.memory(), containsString(expected));
String expected = "Initial:";
assertThat(client.memory(), containsString(expected));
}
}

View File

@ -88,10 +88,8 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.5.4</spring-boot.version>
<spring-boot.version>2.6.1</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
<!-- this property can be removed once we update Mockito version in the main pom.xml -->
<mockito.version>3.4.0</mockito.version>
</properties>
</project>

View File

@ -40,11 +40,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-engine</artifactId>

View File

@ -36,11 +36,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -4,3 +4,4 @@
- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider)
- [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception)
- [Hibernates “Object References an Unsaved Transient Instance” Error](https://www.baeldung.com/hibernate-unsaved-transient-instance-error)
- [EntityNotFoundException in Hibernate](https://www.baeldung.com/hibernate-entitynotfoundexception)

View File

@ -29,6 +29,11 @@
<artifactId>jaxb-api</artifactId>
<version>${jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="com.baeldung.hibernate.entitynotfoundexception.h2_persistence_unit">
<description>EntityManager EntityNotFoundException persistence unit</description>
<class>com.baeldung.hibernate.entitynotfoundexception.Category</class>
<class>com.baeldung.hibernate.entitynotfoundexception.Item</class>
<class>com.baeldung.hibernate.entitynotfoundexception.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.generate_statistics" value="false"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db3;DB_CLOSE_DELAY=-1"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>

View File

@ -13,5 +13,4 @@ This module contains articles specific to use of Hibernate as a JPA implementati
- [Enabling Transaction Locks in Spring Data JPA](https://www.baeldung.com/java-jpa-transaction-locks)
- [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context)
- [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference)
- [JPA Entities and the Serializable Interface](https://www.baeldung.com/jpa-entities-serializable)
- [EntityNotFoundException in Hibernate](https://www.baeldung.com/hibernate-entitynotfoundexception)
- [JPA Entities and the Serializable Interface](https://www.baeldung.com/jpa-entities-serializable)

View File

@ -120,21 +120,4 @@
</properties>
</persistence-unit>
<persistence-unit name="com.baeldung.hibernate.entitynotfoundexception.h2_persistence_unit">
<description>EntityManager EntityNotFoundException persistence unit</description>
<class>com.baeldung.hibernate.entitynotfoundexception.Category</class>
<class>com.baeldung.hibernate.entitynotfoundexception.Item</class>
<class>com.baeldung.hibernate.entitynotfoundexception.User</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.generate_statistics" value="false"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db3;DB_CLOSE_DELAY=-1"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1 @@
spring.mongodb.embedded.version=3.5.5

View File

@ -37,11 +37,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

View File

@ -3,7 +3,7 @@ package com.baeldung.boot.ddd.event;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.verifyNoInteractions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@ -51,7 +51,7 @@ class AggregateEventsIntegrationTest {
.domainOperation();
// then
verifyZeroInteractions(eventHandler);
verifyNoInteractions(eventHandler);
}
@BeforeEach

View File

@ -30,10 +30,6 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
@ -56,12 +52,10 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
@ -84,8 +78,6 @@
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<guava.version>21.0</guava.version>
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
</properties>
</project>

View File

@ -1,8 +1,14 @@
package com.baeldung.persistence.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
import com.google.common.collect.Sets;
import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited;
import org.jboss.logging.Logger;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.CascadeType;
import javax.persistence.Column;
@ -17,17 +23,9 @@ import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited;
import org.jboss.logging.Logger;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.google.common.collect.Sets;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Entity
@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b")
@ -35,11 +33,11 @@ import com.google.common.collect.Sets;
@EntityListeners(AuditingEntityListener.class)
public class Bar implements Serializable {
private static Logger logger = Logger.getLogger(Bar.class);
private static final Logger LOGGER = Logger.getLogger(Bar.class);
public enum OPERATION {
INSERT, UPDATE, DELETE;
private String value;
private final String value;
OPERATION() {
value = toString();
@ -70,7 +68,7 @@ public class Bar implements Serializable {
private String name;
@OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@OrderBy(clause = "NAME DESC")
@OrderBy(clause = "name DESC")
// @NotAudited
private Set<Foo> fooSet = Sets.newHashSet();
@ -102,7 +100,6 @@ public class Bar implements Serializable {
public Bar(final String name) {
super();
this.name = name;
}
@ -202,35 +199,31 @@ public class Bar implements Serializable {
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
return other.name == null;
} else
return name.equals(other.name);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
return "Bar [name=" + name + "]";
}
@PrePersist
public void onPrePersist() {
logger.info("@PrePersist");
LOGGER.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
logger.info("@PreUpdate");
LOGGER.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
logger.info("@PreRemove");
LOGGER.info("@PreRemove");
audit(OPERATION.DELETE);
}

View File

@ -16,7 +16,10 @@ import javax.persistence.NamedNativeQuery;
import org.hibernate.envers.Audited;
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
@NamedNativeQueries({
@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class),
@NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)
})
@Entity
@Audited
// @Proxy(lazy = false)
@ -89,17 +92,13 @@ public class Foo implements Serializable {
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
return other.name == null;
} else
return name.equals(other.name);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
return "Foo [name=" + name + "]";
}
}

View File

@ -1,17 +1,14 @@
package com.baeldung.persistence.audit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.service.IBarAuditableService;
import com.baeldung.persistence.service.IFooAuditableService;
import com.baeldung.spring.config.PersistenceTestConfig;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
@ -23,28 +20,17 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.persistence.model.Bar;
import com.baeldung.persistence.model.Foo;
import com.baeldung.persistence.service.IBarAuditableService;
import com.baeldung.persistence.service.IFooAuditableService;
import com.baeldung.spring.config.PersistenceTestConfig;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceTestConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class EnversFooBarAuditIntegrationTest {
private static Logger logger = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class);
@BeforeClass
public static void setUpBeforeClass() throws Exception {
logger.info("setUpBeforeClass()");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
logger.info("tearDownAfterClass()");
}
private static final Logger LOGGER = LoggerFactory.getLogger(EnversFooBarAuditIntegrationTest.class);
@Autowired
@Qualifier("fooHibernateAuditableService")
@ -60,15 +46,15 @@ public class EnversFooBarAuditIntegrationTest {
private Session session;
@Before
public void setUp() throws Exception {
logger.info("setUp()");
public void setUp() {
LOGGER.info("setUp()");
makeRevisions();
session = sessionFactory.openSession();
}
@After
public void tearDown() throws Exception {
logger.info("tearDown()");
public void tearDown() {
LOGGER.info("tearDown()");
session.close();
}
@ -97,14 +83,12 @@ public class EnversFooBarAuditIntegrationTest {
// REV #3: update BAR
private void rev3(final Bar bar) {
bar.setName("BAR1");
barService.update(bar);
}
// REV #4: insert FOO3 & update BAR
private void rev4(final Bar bar) {
final Foo foo3 = new Foo("FOO3");
foo3.setBar(bar);
fooService.create(foo3);

View File

@ -3,4 +3,5 @@
### Relevant Articles:
- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Performance Difference Between save() and saveAll() in Spring Data](https://www.baeldung.com/spring-data-save-saveall)
- More articles: [[<-- prev]](/spring-data-jpa-repo/)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
- More articles: [[<-- prev]](../spring-data-jpa-repo)

View File

@ -14,7 +14,10 @@
</parent>
<dependencies>
<!-- Persistence -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
@ -31,7 +34,7 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<!-- Utilities -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>

View File

@ -1,4 +1,4 @@
package com.baeldung.like;
package com.baeldung.spring.data.persistence.like;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -1,4 +1,4 @@
package com.baeldung.like.model;
package com.baeldung.spring.data.persistence.like.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;

View File

@ -1,17 +1,16 @@
package com.baeldung.like.repository;
import java.util.List;
package com.baeldung.spring.data.persistence.like.repository;
import com.baeldung.spring.data.persistence.like.model.Movie;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.baeldung.like.model.Movie;
import java.util.List;
public interface MovieRepository extends CrudRepository<Movie, Long> {
List<Movie> findByTitleContaining(String title);
List<Movie> findByTitleLike(String title);
List<Movie> findByTitleContains(String title);
@ -23,17 +22,17 @@ public interface MovieRepository extends CrudRepository<Movie, Long> {
List<Movie> findByDirectorEndsWith(String director);
List<Movie> findByTitleContainingIgnoreCase(String title);
List<Movie> findByRatingNotContaining(String rating);
List<Movie> findByDirectorNotLike(String director);
@Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%")
List<Movie> searchByTitleLike(@Param("title") String title);
@Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
List<Movie> searchByRatingStartsWith(String rating);
//Escaping works in SpringBoot >= 2.4.1
//@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
@Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}")

View File

@ -2,7 +2,7 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
jdbc.pass=
jdbc.pass=sa
# hibernate.X
hibernate.hbm2ddl.auto=create-drop

View File

@ -1,7 +1,7 @@
package com.baeldung.like;
package com.baeldung.spring.data.persistence.like;
import com.baeldung.like.model.Movie;
import com.baeldung.like.repository.MovieRepository;
import com.baeldung.spring.data.persistence.like.model.Movie;
import com.baeldung.spring.data.persistence.like.repository.MovieRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -9,6 +9,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.util.List;
import static org.junit.Assert.assertEquals;
@ -22,11 +23,14 @@ public class MovieRepositoryIntegrationTest {
@Autowired
private MovieRepository movieRepository;
@Autowired
private DataSource dataSource;
@Test
public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByTitleContaining("in");
assertEquals(3, results.size());
results = movieRepository.findByTitleLike("%in%");
assertEquals(3, results.size());
@ -60,25 +64,25 @@ public class MovieRepositoryIntegrationTest {
List<Movie> results = movieRepository.searchByTitleLike("in");
assertEquals(3, results.size());
}
@Test
public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByRatingStartsWith("PG");
assertEquals(6, results.size());
}
@Test
public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.searchByDirectorEndsWith("Burton");
assertEquals(1, results.size());
}
@Test
public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByRatingNotContaining("PG");
assertEquals(1, results.size());
}
@Test
public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() {
List<Movie> results = movieRepository.findByDirectorNotLike("An%");

View File

@ -7,6 +7,8 @@ import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = PersistenceConfig.class)
public class FooServiceIntegrationTest {
@ -14,6 +16,9 @@ public class FooServiceIntegrationTest {
@Autowired
private IFooService service;
@Autowired
private DataSource dataSource;
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo());

View File

@ -5,13 +5,12 @@ This module contains articles about repositories in Spring Data JPA
### Relevant Articles:
- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries)
- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries)
- [Spring Data CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save)
- [Spring Data JPA Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories)
- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures)
- More articles: [[--> next]](/spring-data-jpa-repo-2/)
- More articles: [[--> next]](../spring-data-jpa-repo-2)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:

View File

@ -123,7 +123,7 @@
</build>
<properties>
<spring-tx.version>5.2.2.RELEASE</spring-tx.version>
<spring-tx.version>5.3.13</spring-tx.version>
<httpclient.version>4.5.2</httpclient.version>
<reactor-core.version>3.3.1.RELEASE</reactor-core.version>
</properties>

View File

@ -0,0 +1 @@
spring.mongodb.embedded.version=3.5.5

View File

@ -78,11 +78,11 @@
<properties>
<!-- Spring -->
<org.springframework.version>5.3.8</org.springframework.version>
<org.springframework.version>5.3.13</org.springframework.version>
<!-- persistence -->
<spring-mybatis.version>2.0.2</spring-mybatis.version>
<spring-mybatis.version>2.0.6</spring-mybatis.version>
<mybatis.version>3.5.2</mybatis.version>
<mybatis-spring-boot-starter.version>2.1.0</mybatis-spring-boot-starter.version>
<mybatis-spring-boot-starter.version>2.2.0</mybatis-spring-boot-starter.version>
<h2.version>1.4.197</h2.version>
</properties>

View File

@ -76,12 +76,6 @@
<scope>test</scope>
<version>${spring-boot-starter.version}</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
@ -94,8 +88,6 @@
<spring-data-jpa.version>2.2.7.RELEASE</spring-data-jpa.version>
<!-- simple-jndi -->
<simple-jndi.version>0.23.0</simple-jndi.version>
<!-- test scoped -->
<mockito.version>3.3.3</mockito.version>
</properties>
</project>

View File

@ -652,6 +652,7 @@
<module>spring-data-rest-querydsl</module>
<module>spring-di</module>
<module>spring-di-2</module>
<module>spring-di-3</module>
<module>spring-drools</module>
<module>spring-ejb</module>
@ -1416,7 +1417,7 @@
<assertj.version>3.21.0</assertj.version>
<hamcrest.version>2.2</hamcrest.version>
<hamcrest-all.version>1.3</hamcrest-all.version>
<mockito.version>3.3.0</mockito.version>
<mockito.version>4.1.0</mockito.version>
<byte-buddy.version>1.11.20</byte-buddy.version>
<!-- logging -->

View File

@ -37,6 +37,12 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
@ -94,6 +100,11 @@
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -172,6 +183,7 @@
<properties>
<quarkus.version>1.7.0.Final</quarkus.version>
<lombok.version>1.18.6</lombok.version>
<mockito.version>3.3.0</mockito.version>
</properties>
</project>

View File

@ -94,7 +94,7 @@
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-standalone</artifactId>
<version>2.26.0</version>
<version>${wiremock-standalone.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -110,13 +110,13 @@
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.23.0</version>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.2.10.RELEASE</version>
<version>${reactor-test.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -192,5 +192,7 @@
<geronimo-json_1.1_spec.version>1.0</geronimo-json_1.1_spec.version>
<jetty-reactive-httpclient.version>1.1.6</jetty-reactive-httpclient.version>
<okhttp.version>4.0.1</okhttp.version>
<reactor-test.version>3.2.10.RELEASE</reactor-test.version>
<wiremock-standalone.version>2.26.0</wiremock-standalone.version>
</properties>
</project>

View File

@ -32,11 +32,6 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

View File

@ -19,6 +19,7 @@
<modules>
<module>spring-boot</module>
<module>spring-boot-1</module>
<module>spring-boot-2</module>
<module>spring-boot-admin</module>
<module>spring-boot-angular</module>
<module>spring-boot-annotations</module>
@ -70,6 +71,7 @@
<module>spring-boot-swagger</module>
<module>spring-boot-swagger-jwt</module>
<module>spring-boot-testing</module>
<module>spring-boot-testing-2</module>
<module>spring-boot-vue</module>
<module>spring-boot-actuator</module>
<module>spring-boot-data-2</module>

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