This commit is contained in:
Loredana Crusoveanu 2022-01-10 19:31:07 +02:00
commit 872daf6a22
228 changed files with 3751 additions and 700 deletions

View File

@ -1,3 +1,4 @@
*.docx
temp.xls
temp.xlsx
number_test.xlsx

View File

@ -1,9 +1,12 @@
## Apache POI
This module contains articles about Apache POI
This module contains articles about Apache POI.
### Relevant Articles:
- [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)
- More articles: [[<-- prev]](/apache-poi)
- [Numeric Format Using POI](https://www.baeldung.com/apache-poi-numeric-format)
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- More articles: [[<-- prev]](../apache-poi)

View File

@ -5,7 +5,22 @@ import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.xslf.usermodel.SlideLayout;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFAutoShape;
import org.apache.poi.xslf.usermodel.XSLFHyperlink;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFSlideLayout;
import org.apache.poi.xslf.usermodel.XSLFSlideMaster;
import org.apache.poi.xslf.usermodel.XSLFTable;
import org.apache.poi.xslf.usermodel.XSLFTableCell;
import org.apache.poi.xslf.usermodel.XSLFTableRow;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import java.awt.*;
import java.io.FileInputStream;
@ -155,8 +170,8 @@ public class PowerPointHelper {
/**
* Retrieve the placeholder inside a slide
*
* @param slide
*
* @param slide
* The slide
* @return List of placeholder inside a slide
*/

View File

@ -1,7 +1,11 @@
package com.baeldung.poi.word;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileOutputStream;
import java.io.IOException;

View File

Before

Width:  |  Height:  |  Size: 782 B

After

Width:  |  Height:  |  Size: 782 B

View File

@ -1,8 +1,5 @@
package com.baeldung.poi.powerpoint;
import java.io.File;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
@ -13,12 +10,15 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.List;
public class PowerPointIntegrationTest {
private PowerPointHelper pph;
private String fileLocation;
private static final String FILE_NAME = "presentation.pptx";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();

View File

@ -1,19 +1,19 @@
package com.baeldung.poi.word;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.junit.BeforeClass;
import org.junit.Test;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class WordIntegrationTest {
static WordDocument wordDocument;

View File

@ -1,12 +1,10 @@
## Apache POI
This module contains articles about Apache POI
This module contains articles about Apache POI.
### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](https://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://www.baeldung.com/apache-poi-slideshow)
- [Merge Cells in Excel Using Apache POI](https://www.baeldung.com/java-apache-poi-merge-cells)
- [Get String Value of Excel Cell with Apache POI](https://www.baeldung.com/java-apache-poi-cell-string-value)
- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula)
@ -16,4 +14,4 @@ This module contains articles about Apache POI
- [Set Background Color of a Cell with Apache POI](https://www.baeldung.com/apache-poi-background-color)
- [Add Borders to Excel Cells With Apache POI](https://www.baeldung.com/apache-poi-add-borders)
- [Reading Values From Excel in Java](https://www.baeldung.com/java-read-dates-excel)
- More articles: [[next -->]](/apache-poi-2)
- More articles: [[next -->]](../apache-poi-2)

View File

@ -27,6 +27,13 @@
<compilerArgs>--enable-preview</compilerArgs>
<source>${maven.compiler.source.version}</source>
<target>${maven.compiler.target.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
@ -49,6 +56,20 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source.version>17</maven.compiler.source.version>
<maven.compiler.target.version>17</maven.compiler.target.version>

View File

@ -0,0 +1,115 @@
package com.baeldung.randomgenerators;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import java.util.concurrent.TimeUnit;
import java.util.random.RandomGenerator;
public class BenchmarkRunner {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL128X1024MixRandom() {
generateRandomNumbers(RandomGenerator.of("L128X1024MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL128X128MixRandom() {
generateRandomNumbers(RandomGenerator.of("L128X128MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL128X256MixRandom() {
generateRandomNumbers(RandomGenerator.of("L128X256MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL32X64MixRandom() {
generateRandomNumbers(RandomGenerator.of("L32X64MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL64X1024MixRandom() {
generateRandomNumbers(RandomGenerator.of("L64X1024MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL64X128MixRandom() {
generateRandomNumbers(RandomGenerator.of("L64X128MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL64X128StarStarRandom() {
generateRandomNumbers(RandomGenerator.of("L64X128StarStarRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testL64X256MixRandom() {
generateRandomNumbers(RandomGenerator.of("L64X256MixRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testRandom() {
generateRandomNumbers(RandomGenerator.of("Random"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testSecureRandom() {
generateRandomNumbers(RandomGenerator.of("SecureRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testSplittableRandom() {
generateRandomNumbers(RandomGenerator.of("SplittableRandom"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testXoroshiro128PlusPlus() {
generateRandomNumbers(RandomGenerator.of("Xoroshiro128PlusPlus"));
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public static void testXoshiro256PlusPlus() {
generateRandomNumbers(RandomGenerator.of("Xoshiro256PlusPlus"));
}
private static void generateRandomNumbers(RandomGenerator generator) {
generator.nextLong();
generator.nextInt();
generator.nextFloat();
generator.nextDouble();
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.randomgenerators;
import java.util.Comparator;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
public class GeneratorFactory {
public static void main(String[] args) {
System.out.println("Group\tName\tJumpable?\tSplittable?");
RandomGeneratorFactory.all()
.sorted(Comparator.comparing(RandomGeneratorFactory::name))
.forEach(factory -> System.out.println(String.format("%s\t%s\t%s\t%s",
factory.group(),
factory.name(),
factory.isJumpable(),
factory.isSplittable())));
}
public static int getRandomInt(RandomGenerator generator, int bound) {
return generator.nextInt(bound);
}
public static RandomGenerator getDefaultGenerator() {
return RandomGeneratorFactory.getDefault().create();
}
public static RandomGenerator getJumpableGenerator() {
return RandomGeneratorFactory.all()
.filter(RandomGeneratorFactory::isJumpable)
.findAny()
.map(RandomGeneratorFactory::create)
.orElseThrow(() -> new RuntimeException("Error creating a generator"));
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.randomgenerators;
import java.util.Random;
public class OldRandom {
public static int getRandomInt(int bound) {
Random random = new Random();
return random.nextInt(bound);
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.randomgenerators;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;
public class SplittableGeneratorMultiThread {
public static List<Integer> generateNumbersInMultipleThreads() {
List<Integer> numbers = Collections.synchronizedList(new ArrayList<>());
ExecutorService executorService = Executors.newCachedThreadPool();
RandomGenerator.SplittableGenerator sourceGenerator = RandomGeneratorFactory
.<RandomGenerator.SplittableGenerator>of("L128X256MixRandom")
.create();
sourceGenerator.splits(20).forEach((splitGenerator) -> {
executorService.submit(() -> {
numbers.add(splitGenerator.nextInt(10));
});
});
return numbers;
}
}

View File

@ -1,4 +1,7 @@
module core.java {
requires jdk.incubator.vector;
requires jdk.incubator.foreign;
requires jmh.core;
requires jdk.unsupported;
exports com.baeldung.randomgenerators.jmh_generated;
}

View File

@ -0,0 +1,21 @@
package com.baeldung.randomgenerators;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class GeneratorFactoryUnitTest {
@Test
void givenDefaultGenerator_whenGeneratingAnInt_thenIntInRangeIsGenerated() {
int number = GeneratorFactory.getRandomInt(GeneratorFactory.getDefaultGenerator(), 10);
assertThat(number).isNotNegative().isLessThan(10);
}
@Test
void givenJumpableGenerator_whenGeneratingAnInt_thenIntInRangeIsGenerated() {
int number = GeneratorFactory.getRandomInt(GeneratorFactory.getJumpableGenerator(), 10);
assertThat(number).isNotNegative().isLessThan(10);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.randomgenerators;
import org.junit.jupiter.api.Test;
import java.util.random.RandomGenerator;
import static org.assertj.core.api.Assertions.assertThat;
class GeneratorSelectionUnitTest {
@Test
void givenDefaultGenerator_whenGeneratingAnInt_thenIntInRangeIsGenerated() {
RandomGenerator generator = RandomGenerator.getDefault();
int number = generator.nextInt(10);
assertThat(number).isNotNegative().isLessThan(10);
}
@Test
void givenSpecificGenerator_whenGeneratingAnInt_thenIntInRangeIsGenerated() {
RandomGenerator generator = RandomGenerator.of("L128X256MixRandom");
int number = generator.nextInt(10);
assertThat(number).isNotNegative().isLessThan(10);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.randomgenerators;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class OldRandomUnitTest {
@Test
void givenOldRandomApi_whenGeneratingAnInt_thenIntInRangeIsGenerated() {
int number = OldRandom.getRandomInt(10);
assertThat(number).isNotNegative().isLessThan(10);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.randomgenerators;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class SplittableGeneratorMultiThreadUnitTest {
@Test
void givenSplittableGenerator_whenUsingMultipleThreads_thenListOfIntsIsGenerated() {
List<Integer> numbers = SplittableGeneratorMultiThread.generateNumbersInMultipleThreads();
assertThat(numbers).hasSize(20).allMatch(number -> number >= 0 && number <= 10);
}
}

View File

@ -5,7 +5,7 @@ This module contains articles about the Date and Time API introduced with Java 8
### Relevant Articles:
- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [Get the Current Date and Time in Java](https://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
- [ZoneOffset in Java](https://www.baeldung.com/java-zone-offset)
- [Differences Between ZonedDateTime and OffsetDateTime](https://www.baeldung.com/java-zoneddatetime-offsetdatetime)

View File

@ -3,3 +3,4 @@
- [Binary Semaphore vs Reentrant Lock](https://www.baeldung.com/java-binary-semaphore-vs-reentrant-lock)
- [Bad Practices With Synchronization](https://www.baeldung.com/java-synchronization-bad-practices)
- [Start Two Threads at the Exact Same Time in Java](https://www.baeldung.com/java-start-two-threads-at-same-time)
- [Volatile Variables and Thread Safety](https://www.baeldung.com/java-volatile-variables-thread-safety)

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

@ -14,4 +14,5 @@ This module contains articles about basic Java concurrency
- [How to Stop Execution After a Certain Time in Java](https://www.baeldung.com/java-stop-execution-after-certain-time)
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
- [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)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-basic)

View File

@ -9,3 +9,4 @@
- [Explanation of ClassCastException in Java](https://www.baeldung.com/java-classcastexception)
- [NoSuchFieldError in Java](https://www.baeldung.com/java-nosuchfielderror)
- [IllegalAccessError in Java](https://www.baeldung.com/java-illegalaccesserror)
- [Working with (Unknown Source) Stack Traces in Java](https://www.baeldung.com/java-unknown-source-stack-trace)

View File

@ -14,4 +14,4 @@ This module contains articles about core Java input and output (IO)
- [Find the Last Modified File in a Directory with Java](https://www.baeldung.com/java-last-modified-file)
- [Get a Filename Without the Extension in Java](https://www.baeldung.com/java-filename-without-extension)
- [Writing byte[] to a File in Java](https://www.baeldung.com/java-write-byte-array-file)
- [[<-- Prev]](/core-java-modules/core-java-io-2)
- [[<-- Prev]](/core-java-modules/core-java-io-2)[[More -->]](/core-java-modules/core-java-io-4)

View File

@ -31,7 +31,7 @@ public class InputSequenceUnitTest {
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(file1, file2);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, FILE1_AND_FILE2_CONTENT);
assertEquals(FILE1_AND_FILE2_CONTENT, stringValue);
}
@Test
@ -43,7 +43,7 @@ public class InputSequenceUnitTest {
InputSequenceHandler inputSequenceHandler = new InputSequenceHandler(filesList);
String stringValue = inputSequenceHandler.readAsString();
inputSequenceHandler.close();
assertEquals(stringValue, ALL_FILES_CONTENT);
assertEquals(ALL_FILES_CONTENT, stringValue);
}
@Test

View File

@ -10,4 +10,5 @@ This module contains articles about string conversions from/to another type.
- [Converting String to BigInteger in Java](https://www.baeldung.com/java-string-to-biginteger)
- [Convert a String to Camel Case](https://www.baeldung.com/java-string-to-camel-case)
- [Convert a ByteBuffer to String in Java](https://www.baeldung.com/java-bytebuffer-to-string)
- [Convert String to Float and Back in Java](https://www.baeldung.com/java-string-to-float)
- More articles: [[<-- prev]](/core-java-string-conversions)

View File

@ -3,4 +3,7 @@
- [Ignoring Commas in Quotes When Splitting a Comma-separated String](https://www.baeldung.com/java-split-string-commas)
- [Compare Strings While Ignoring Whitespace in Java](https://www.baeldung.com/java-compare-string-whitespace)
- [Concatenating Null Strings in Java](https://www.baeldung.com/java-concat-null-string)
- [Split a String Every n Characters in Java](https://www.baeldung.com/java-string-split-every-n-characters)
- [String equals() Vs contentEquals() in Java](https://www.baeldung.com/java-string-equals-vs-contentequals)
- [Check if a String Ends with a Certain Pattern in Java](https://www.baeldung.com/java-string-ends-pattern)

View File

@ -0,0 +1,45 @@
package com.baeldung.endswithpattern;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
public class StringEndsWithPattern {
public static boolean usingStringEndsWithMethod(String text, String suffix) {
if (text == null || suffix == null) {
return false;
}
return text.endsWith(suffix);
}
public static boolean usingStringMatchesMethod(String text, String suffix) {
if (text == null || suffix == null) {
return false;
}
String regex = ".*" + suffix + "$";
return text.matches(regex);
}
public static boolean usingStringRegionMatchesMethod(String text, String suffix) {
if (text == null || suffix == null) {
return false;
}
int toffset = text.length() - suffix.length();
return text.regionMatches(toffset, suffix, 0, suffix.length());
}
public static boolean usingPatternClass(String text, String suffix) {
if (text == null || suffix == null) {
return false;
}
Pattern pattern = Pattern.compile(".*" + suffix + "$");
return pattern.matcher(text)
.find();
}
public static boolean usingApacheCommonsLang(String text, String suffix) {
return StringUtils.endsWith(text, suffix);
}
}

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,42 @@
package com.baeldung.endswithpattern;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.Test;
public class StringEndsWithPatternUnitTest {
private static final String TEXT = "Welcome to baeldung.com";
private static final String SUFFIX = "com";
@Test
public void givenStringAndSuffix_whenUsingStringEndsWith_thenCheck() {
assertTrue(StringEndsWithPattern.usingStringEndsWithMethod(TEXT, SUFFIX));
}
@Test
public void givenStringAndSuffix_whenUsingStringMatches_thenCheck() {
assertTrue(StringEndsWithPattern.usingStringMatchesMethod(TEXT, SUFFIX));
}
@Test
public void givenStringAndSuffix_whenUsingStringRegionMatches_thenCheck() {
assertTrue(StringEndsWithPattern.usingStringRegionMatchesMethod(TEXT, SUFFIX));
}
@Test
public void givenStringAndSuffix_whenUsingPatternClass_thenCheck() {
assertTrue(StringEndsWithPattern.usingPatternClass(TEXT, SUFFIX));
}
@Test
public void givenStringAndSuffix_whenUsingApacheCommonsLang_thenCheck() {
assertTrue(StringEndsWithPattern.usingApacheCommonsLang(TEXT, SUFFIX));
}
}

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"));
}
}

3
jbang/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Guide to JBang](https://www.baeldung.com/jbang-guide)

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

@ -13,4 +13,4 @@ This module contains articles about JSON.
- [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration)
- [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping)
- [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size)
- More Articles: [[next -->]](/json-2)
- More Articles: [[next -->]](../json-2)

View File

@ -63,15 +63,22 @@
<version>${commons-collections4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit-assertj</artifactId>
<version>${json-unit-assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<everit.json.schema.version>1.4.1</everit.json.schema.version>
<jsonb-api.version>1.0</jsonb-api.version>
<yasson.version>1.0.1</yasson.version>
<json.version>20171018</json.version>
<json.version>20211205</json.version>
<gson.version>2.8.5</gson.version>
<javax.version>1.1.2</javax.version>
<json-unit-assertj.version>2.28.0</json-unit-assertj.version>
</properties>
</project>

View File

@ -1,36 +1,44 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.junit.Test;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
public class CDLIntegrationTest {
@Test
public void givenCommaDelimitedText_thenConvertToJSONArray() {
JSONArray ja = CDL.rowToJSONArray(new JSONTokener("England, USA, Canada"));
assertEquals("[\"England\",\"USA\",\"Canada\"]", ja.toString());
assertThatJson(ja)
.isEqualTo("[\"England\",\"USA\",\"Canada\"]");
}
@Test
public void givenJSONArray_thenConvertToCommaDelimitedText() {
JSONArray ja = new JSONArray("[\"England\",\"USA\",\"Canada\"]");
String cdt = CDL.rowToString(ja);
assertEquals("England,USA,Canada", cdt.toString().trim());
assertThat(cdt.trim()).isEqualTo("England,USA,Canada");
}
@Test
public void givenCommaDelimitedText_thenGetJSONArrayOfJSONObjects() {
String string =
String string =
"name, city, age \n" +
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(string);
assertEquals("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]", result.toString());
assertThatJson(result)
.isEqualTo("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]");
}
@Test
@ -39,14 +47,16 @@ public class CDLIntegrationTest {
ja.put("name");
ja.put("city");
ja.put("age");
String string =
String string =
"john, chicago, 22 \n" +
"gary, florida, 35 \n" +
"sal, vegas, 18";
JSONArray result = CDL.toJSONArray(ja, string);
assertEquals("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]", result.toString());
assertThatJson(result)
.isEqualTo("[{\"name\":\"john\",\"city\":\"chicago\",\"age\":\"22\"},{\"name\":\"gary\",\"city\":\"florida\",\"age\":\"35\"},{\"name\":\"sal\",\"city\":\"vegas\",\"age\":\"18\"}]");
}
}

View File

@ -1,20 +1,23 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
import org.json.Cookie;
import org.json.JSONObject;
import org.junit.Test;
public class CookieIntegrationTest {
@Test
public void givenCookieString_thenConvertToJSONObject() {
String cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
JSONObject cookieJO = Cookie.toJSONObject(cookie);
assertEquals("{\"path\":\"/\",\"expires\":\"Thu, 18 Dec 2013 12:00:00 UTC\",\"name\":\"username\",\"value\":\"John Doe\"}", cookieJO.toString());
assertThatJson(cookieJO)
.isEqualTo("{\"path\":\"/\",\"expires\":\"Thu, 18 Dec 2013 12:00:00 UTC\",\"name\":\"username\",\"value\":\"John Doe\"}");
}
@Test
public void givenJSONObject_thenConvertToCookieString() {
JSONObject cookieJO = new JSONObject();
@ -22,8 +25,10 @@ public class CookieIntegrationTest {
cookieJO.put("value", "John Doe");
cookieJO.put("expires", "Thu, 18 Dec 2013 12:00:00 UTC");
cookieJO.put("path", "/");
String cookie = Cookie.toString(cookieJO);
assertEquals("username=John Doe;expires=Thu, 18 Dec 2013 12:00:00 UTC;path=/", cookie.toString());
assertThat(cookie.split(";"))
.containsExactlyInAnyOrder("username=John Doe", "path=/", "expires=Thu, 18 Dec 2013 12:00:00 UTC");
}
}

View File

@ -1,10 +1,12 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.HTTP;
import org.json.JSONObject;
import org.junit.Test;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
public class HTTPIntegrationTest {
@Test
public void givenJSONObject_thenConvertToHTTPHeader() {
@ -12,14 +14,16 @@ public class HTTPIntegrationTest {
jo.put("Method", "POST");
jo.put("Request-URI", "http://www.example.com/");
jo.put("HTTP-Version", "HTTP/1.1");
assertEquals("POST \"http://www.example.com/\" HTTP/1.1"+HTTP.CRLF+HTTP.CRLF, HTTP.toString(jo));
assertThat(HTTP.toString(jo))
.isEqualTo("POST \"http://www.example.com/\" HTTP/1.1" + HTTP.CRLF + HTTP.CRLF);
}
@Test
public void givenHTTPHeader_thenConvertToJSONObject() {
JSONObject obj = HTTP.toJSONObject("POST \"http://www.example.com/\" HTTP/1.1");
assertEquals("{\"Request-URI\":\"http://www.example.com/\",\"Method\":\"POST\",\"HTTP-Version\":\"HTTP/1.1\"}", obj.toString());
assertThatJson(obj)
.isEqualTo("{\"Request-URI\":\"http://www.example.com/\",\"Method\":\"POST\",\"HTTP-Version\":\"HTTP/1.1\"}");
}
}

View File

@ -1,12 +1,10 @@
package com.baeldung.jsonjava;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class JSONArrayGetValueByKeyUnitTest {
@ -19,7 +17,8 @@ public class JSONArrayGetValueByKeyUnitTest {
List<String> actualValues = obj.getValuesByKeyInJSONArray(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
assertThat(actualValues)
.containsExactlyInAnyOrder("John", "Gary", "Selena");
}
@Test
@ -29,7 +28,8 @@ public class JSONArrayGetValueByKeyUnitTest {
List<String> actualValues = obj.getValuesByKeyInJSONArrayUsingJava8(jsonStr, "name");
assertThat(actualValues, equalTo(Arrays.asList("John", "Gary", "Selena")));
assertThat(actualValues)
.containsExactlyInAnyOrder("John", "Gary", "Selena");
}
}

View File

@ -1,36 +1,40 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
public class JSONArrayIntegrationTest {
@Test
public void givenJSONJava_thenCreateNewJSONArrayFromScratch() {
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
// We can also put a JSONObject in JSONArray
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
assertEquals("[true,\"lorem ipsum\",{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}]", ja.toString());
assertThatJson(ja)
.isEqualTo("[true,\"lorem ipsum\",{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}]");
}
@Test
public void givenJsonString_thenCreateNewJSONArray() {
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
assertEquals("[true,\"lorem ipsum\",215]", ja.toString());
assertThatJson(ja)
.isEqualTo("[true,\"lorem ipsum\",215]");
}
@Test
@ -40,8 +44,10 @@ public class JSONArrayIntegrationTest {
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
assertEquals("[\"California\",\"Texas\",\"Hawaii\",\"Alaska\"]", ja.toString());
assertThatJson(ja)
.isEqualTo("[\"California\",\"Texas\",\"Hawaii\",\"Alaska\"]");
}
}

View File

@ -1,23 +1,24 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
public class JSONObjectIntegrationTest {
@Test
public void givenJSONJava_thenCreateNewJSONObject() {
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
assertEquals("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}", jo.toString());
assertThatJson(jo)
.isEqualTo("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}");
}
@Test
@ -27,8 +28,9 @@ public class JSONObjectIntegrationTest {
map.put("age", "22");
map.put("city", "chicago");
JSONObject jo = new JSONObject(map);
assertEquals("{\"name\":\"jon doe\",\"city\":\"chicago\",\"age\":\"22\"}", jo.toString());
assertThatJson(jo)
.isEqualTo("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}");
}
@Test
@ -36,7 +38,8 @@ public class JSONObjectIntegrationTest {
JSONObject jo = new JSONObject(
"{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}"
);
assertEquals("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}", jo.toString());
assertThatJson(jo)
.isEqualTo("{\"city\":\"chicago\",\"name\":\"jon doe\",\"age\":\"22\"}");
}
}

View File

@ -1,21 +1,22 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.JSONTokener;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class JSONTokenerIntegrationTest {
@Test
public void givenString_convertItToJSONTokens() {
String str = "Sample String";
JSONTokener jt = new JSONTokener(str);
char[] expectedTokens = str.toCharArray();
int index = 0;
while(jt.more()) {
assertEquals(expectedTokens[index++], jt.next());
while (jt.more()) {
assertThat(jt.next()).isEqualTo(expectedTokens[index++]);
}
}
}

View File

@ -1,19 +1,22 @@
package com.baeldung.jsonjava;
import static org.junit.Assert.assertEquals;
import org.json.JSONObject;
import org.junit.Test;
import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
public class ObjectToFromJSONIntegrationTest {
@Test
public void givenDemoBean_thenCreateJSONObject() {
DemoBean demo = new DemoBean();
demo.setId(1);
demo.setName("lorem ipsum");
demo.setActive(true);
JSONObject jo = new JSONObject(demo);
assertEquals("{\"name\":\"lorem ipsum\",\"active\":true,\"id\":1}", jo.toString());
assertThatJson(jo)
.isEqualTo("{\"name\":\"lorem ipsum\",\"active\":true,\"id\":1}");
}
}

View File

@ -21,7 +21,7 @@ public class ZipSingleFile {
if (!fileToAdd.exists()) {
fileToAdd.createNewFile();
}
zipFile.addFile(fileToAdd);
zipFile.addFile(fileToAdd, zipParameters);
zipFile.close();
}
}

View File

@ -16,3 +16,4 @@ This module contains articles about Project Lombok.
- [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)
- [Lombok Configuration System](https://www.baeldung.com/lombok-configuration-system)

View File

@ -8,3 +8,4 @@ This module contains articles about metrics.
- [Introduction to Netflix Servo](https://www.baeldung.com/netflix-servo)
- [Quick Guide to Micrometer](https://www.baeldung.com/micrometer)
- [@Timed Annotation Using Metrics and AspectJ](https://www.baeldung.com/timed-metrics-aspectj)
- [Guide to Netflix Spectator](https://www.baeldung.com/java-netflix-spectator)

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,18 +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.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
@ -24,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")
@ -61,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();
}
@ -98,20 +83,17 @@ 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);
}
@Ignore("Fixing after Spring Boot 2.6.1 upgrade")
@Test
public final void whenFooBarsModified_thenFooBarsAudited() {

View File

@ -556,7 +556,6 @@
<module>atomikos</module>
<module>reactive-systems</module>
<module>slack</module>
<module>spring-webflux-threads</module>
</modules>
</profile>
@ -613,16 +612,19 @@
<module>spring-5-data-reactive</module>
<module>spring-5-reactive</module>
<module>spring-5-reactive-2</module>
<module>spring-5-reactive-3</module>
<module>spring-5-reactive-client</module>
<module>spring-5-reactive-oauth</module>
<module>spring-5-reactive-security</module>
<module>spring-5-webflux</module>
<module>spring-5-webflux-2</module>
<module>spring-reactive</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-amqp</module>
<module>spring-aop</module>
<module>spring-aop-2</module>
<module>spring-apache-camel</module>
<module>spring-batch</module>
@ -1035,7 +1037,6 @@
<module>atomikos</module>
<module>reactive-systems</module>
<module>slack</module>
<module>spring-webflux-threads</module>
</modules>
</profile>
@ -1084,15 +1085,18 @@
<module>spring-5-data-reactive</module>
<module>spring-5-reactive</module>
<module>spring-5-reactive-2</module>
<module>spring-5-reactive-3</module>
<module>spring-5-reactive-client</module>
<module>spring-5-reactive-oauth</module>
<module>spring-5-reactive-security</module>
<module>spring-5-webflux</module>
<module>spring-reactive</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-amqp</module>
<module>spring-aop</module>
<module>spring-aop-2</module>
<module>spring-apache-camel</module>
<module>spring-batch</module>

View File

@ -4,7 +4,6 @@ This module contains articles about Reactor Core.
### Relevant articles
- [Intro To Reactor Core](https://www.baeldung.com/reactor-core)
- [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams)
- [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor)
- [How to Extract a Monos Content in Java](https://www.baeldung.com/java-string-from-mono)

View File

@ -1,13 +1,10 @@
## Spring 5 Reactive Project
This module contains articles about reactive Spring 5
This module contains articles about reactive Spring 5.
- [Spring WebClient vs. RestTemplate](https://www.baeldung.com/spring-webclient-resttemplate)
- [Validation for Functional Endpoints in Spring 5](https://www.baeldung.com/spring-functional-endpoints-validation)
- [Logging a Reactive Sequence](https://www.baeldung.com/spring-reactive-sequence-logging)
- [Testing Reactive Streams Using StepVerifier and TestPublisher](https://www.baeldung.com/reactive-streams-step-verifier-test-publisher)
- [Debugging Reactive Streams in Java](https://www.baeldung.com/spring-debugging-reactive-streams)
- [Static Content in Spring WebFlux](https://www.baeldung.com/spring-webflux-static-content)
- [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events)
- [Backpressure Mechanism in Spring WebFlux](https://www.baeldung.com/spring-webflux-backpressure)
- More articles: [[<-- prev]](/spring-5-reactive)
- More articles: [[<-- prev]](../spring-5-reactive) [[next -->]](../spring-5-reactive-3)

12
spring-5-reactive-3/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
#folders#
.idea
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,6 @@
## Spring 5 Reactive Project
This module contains articles about reactive Spring 5.
- [Logging a Reactive Sequence](https://www.baeldung.com/spring-reactive-sequence-logging)
- More articles: [[<-- prev]](../spring-5-reactive-2)

View File

@ -0,0 +1,44 @@
<?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>spring-5-reactive-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-5-reactive-3</name>
<packaging>jar</packaging>
<description>spring 5 sample project about new features</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectreactor</groupId>
<artifactId>reactor-spring</artifactId>
<version>${reactor-spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
</properties>
</project>

View File

@ -0,0 +1 @@
# application properties

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -8,8 +8,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles
- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators)
- [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive)
- [Guide to Spring 5 WebFlux](https://www.baeldung.com/spring-webflux)
- [Introduction to the Functional Web Framework in Spring 5](https://www.baeldung.com/spring-5-functional-web)
- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver)
- [Spring Webflux and CORS](https://www.baeldung.com/spring-webflux-cors)

View File

@ -110,7 +110,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.baeldung.webflux.EmployeeSpringApplication</mainClass>
<mainClass>com.baeldung.reactive.actuator.Spring5ReactiveApplication</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>

View File

@ -1,64 +0,0 @@
package com.baeldung.webflux;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Repository
public class EmployeeRepository {
static Map<String,Employee> employeeData;
static Map<String,String> employeeAccessData;
static
{
employeeData = new HashMap<>();
employeeData.put("1",new Employee("1","Employee 1"));
employeeData.put("2",new Employee("2","Employee 2"));
employeeData.put("3",new Employee("3","Employee 3"));
employeeData.put("4",new Employee("4","Employee 4"));
employeeData.put("5",new Employee("5","Employee 5"));
employeeData.put("6",new Employee("6","Employee 6"));
employeeData.put("7",new Employee("7","Employee 7"));
employeeData.put("8",new Employee("8","Employee 8"));
employeeData.put("9",new Employee("9","Employee 9"));
employeeData.put("10",new Employee("10","Employee 10"));
employeeAccessData=new HashMap<>();
employeeAccessData.put("1", "Employee 1 Access Key");
employeeAccessData.put("2", "Employee 2 Access Key");
employeeAccessData.put("3", "Employee 3 Access Key");
employeeAccessData.put("4", "Employee 4 Access Key");
employeeAccessData.put("5", "Employee 5 Access Key");
employeeAccessData.put("6", "Employee 6 Access Key");
employeeAccessData.put("7", "Employee 7 Access Key");
employeeAccessData.put("8", "Employee 8 Access Key");
employeeAccessData.put("9", "Employee 9 Access Key");
employeeAccessData.put("10", "Employee 10 Access Key");
}
public Mono<Employee> findEmployeeById(String id)
{
return Mono.just(employeeData.get(id));
}
public Flux<Employee> findAllEmployees()
{
return Flux.fromIterable(employeeData.values());
}
public Mono<Employee> updateEmployee(Employee employee)
{
Employee existingEmployee=employeeData.get(employee.getId());
if(existingEmployee!=null)
{
existingEmployee.setName(employee.getName());
}
return Mono.just(existingEmployee);
}
}

View File

@ -1,14 +1,13 @@
package com.baeldung;
import com.baeldung.reactive.actuator.Spring5ReactiveApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.reactive.security.SpringSecurity5Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringSecurity5Application.class)
@SpringBootTest(classes = Spring5ReactiveApplication.class)
public class SpringContextTest {
@Test

View File

@ -7,11 +7,9 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring
### Relevant Articles
- [Spring 5 WebClient](https://www.baeldung.com/spring-5-webclient)
- [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching)
- [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets)
- [Spring Webflux Filters](https://www.baeldung.com/spring-webflux-filters)
- [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header)
- [Handling Errors in Spring WebFlux](https://www.baeldung.com/spring-webflux-errors)
- [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive)
- More articles: [[next -->]](/spring-5-reactive-2)

View File

@ -1,28 +0,0 @@
package com.baeldung.web.reactive;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Task {
private final String name;
private final int id;
public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
return "Task{" + "name='" + name + '\'' + ", id=" + id + '}';
}
}

View File

@ -6,9 +6,7 @@ This module contains articles about Spring 5 WebFlux
- [Spring Boot Reactor Netty Configuration](https://www.baeldung.com/spring-boot-reactor-netty)
- [How to Return 404 with Spring WebFlux](https://www.baeldung.com/spring-webflux-404)
- [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters)
- [RSocket Using Spring Boot](https://www.baeldung.com/spring-boot-rsocket)
- [Spring MVC Async vs Spring WebFlux](https://www.baeldung.com/spring-mvc-async-vs-webflux)
- [Set a Timeout in Spring 5 Webflux WebClient](https://www.baeldung.com/spring-webflux-timeout)
- [Guide to Retry in Spring WebFlux](https://www.baeldung.com/spring-webflux-retry)
- [Spring Webflux and @Cacheable Annotation](https://www.baeldung.com/spring-webflux-cacheable)

10
spring-aop-2/README.md Normal file
View File

@ -0,0 +1,10 @@
## Spring AOP
This module contains articles about Spring aspect oriented programming (AOP)
### Relevant articles
- [Spring Performance Logging](https://www.baeldung.com/spring-performance-logging)
- [When Does Java Throw UndeclaredThrowableException?](https://www.baeldung.com/java-undeclaredthrowableexception)
- [Get Advised Method Info in Spring AOP](https://www.baeldung.com/spring-aop-get-advised-method-info)
- More articles: [[<-- prev]](/spring-aop)

46
spring-aop-2/pom.xml Normal file
View File

@ -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>spring-aop-2</artifactId>
<name>spring-aop-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<aspectj-plugin.version>1.11</aspectj-plugin.version>
</properties>
</project>

View File

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

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<logger name="com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor" level="INFO" />
<logger name="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" level="TRACE" />
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,15 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -6,11 +6,9 @@ This module contains articles about Spring aspect oriented programming (AOP)
- [Implementing a Custom Spring AOP Annotation](https://www.baeldung.com/spring-aop-annotation)
- [Intro to AspectJ](https://www.baeldung.com/aspectj)
- [Spring Performance Logging](https://www.baeldung.com/spring-performance-logging)
- [Introduction to Spring AOP](https://www.baeldung.com/spring-aop)
- [Introduction to Pointcut Expressions in Spring](https://www.baeldung.com/spring-aop-pointcut-tutorial)
- [Introduction to Advice Types in Spring](https://www.baeldung.com/spring-aop-advice-tutorial)
- [When Does Java Throw UndeclaredThrowableException?](https://www.baeldung.com/java-undeclaredthrowableexception)
- [Get Advised Method Info in Spring AOP](https://www.baeldung.com/spring-aop-get-advised-method-info)
- [Advise Methods on Annotated Classes With AspectJ](https://www.baeldung.com/aspectj-advise-methods)
- [Joinpoint vs. ProceedingJoinPoint in AspectJ](https://www.baeldung.com/aspectj-joinpoint-proceedingjoinpoint)
- More articles: [[next -->]](/spring-aop-2)

View File

@ -13,10 +13,6 @@
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<logger name="com.baeldung.performancemonitor.MyPerformanceMonitorInterceptor" level="INFO" />
<logger name="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" level="TRACE" />
<logger name="com.baeldung.aspectj.classmethodadvice" level="TRACE" />
<root level="TRACE">

View File

@ -70,6 +70,7 @@
<module>spring-boot-springdoc</module>
<module>spring-boot-swagger</module>
<module>spring-boot-swagger-jwt</module>
<module>spring-boot-swagger-keycloak</module>
<module>spring-boot-testing</module>
<module>spring-boot-testing-2</module>
<module>spring-boot-vue</module>
@ -97,4 +98,4 @@
</dependencies>
</dependencyManagement>
</project>
</project>

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