Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8824
This commit is contained in:
commit
6369641f8f
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.algorithms.distancebetweenpoints;
|
||||
|
||||
import java.awt.geom.Point2D;
|
||||
|
||||
public class DistanceBetweenPointsService {
|
||||
|
||||
public double calculateDistanceBetweenPoints(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
|
||||
}
|
||||
|
||||
public double calculateDistanceBetweenPointsWithHypot(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
double ac = Math.abs(y2 - y1);
|
||||
double cb = Math.abs(x2 - x1);
|
||||
|
||||
return Math.hypot(ac, cb);
|
||||
}
|
||||
|
||||
public double calculateDistanceBetweenPointsWithPoint2D(
|
||||
double x1,
|
||||
double y1,
|
||||
double x2,
|
||||
double y2) {
|
||||
|
||||
return Point2D.distance(x1, y1, x2, y2);
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
public class LinesIntersectionService {
|
||||
|
||||
public Optional<Point> calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
|
||||
|
||||
if (m1 == m2) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
double x = (b2 - b1) / (m1 - m2);
|
||||
double y = m1 * x + b1;
|
||||
|
||||
Point point = new Point();
|
||||
point.setLocation(x, y);
|
||||
return Optional.of(point);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.algorithms.distancebetweenpoints;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DistanceBetweenPointsServiceUnitTest {
|
||||
|
||||
private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
|
||||
|
||||
double x1 = 3;
|
||||
double y1 = 4;
|
||||
double x2 = 7;
|
||||
double y2 = 1;
|
||||
|
||||
double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
|
||||
|
||||
assertEquals(distance, 5, 0.001);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.algorithms.linesintersection;
|
||||
|
||||
import java.awt.Point;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class LinesIntersectionServiceUnitTest {
|
||||
private LinesIntersectionService service = new LinesIntersectionService();
|
||||
|
||||
@Test
|
||||
public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
|
||||
|
||||
double m1 = 0;
|
||||
double b1 = 0;
|
||||
double m2 = 1;
|
||||
double b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertTrue(point.isPresent());
|
||||
assertEquals(point.get().getX(), 1, 0.001);
|
||||
assertEquals(point.get().getY(), 0, 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParallelLines_whenCalculatePoint_thenEmpty() {
|
||||
double m1 = 1;
|
||||
double b1 = 0;
|
||||
double m2 = 1;
|
||||
double b2 = -1;
|
||||
|
||||
Optional<Point> point = service.calculateIntersectionPoint(m1, b1, m2, b2);
|
||||
|
||||
assertFalse(point.isPresent());
|
||||
}
|
||||
}
|
|
@ -20,7 +20,7 @@
|
|||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>${artifactId}</finalName>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
|
|
|
@ -1,70 +1,91 @@
|
|||
package com.baeldung.test.dependencyinjection;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import org.jboss.weld.environment.se.Weld;
|
||||
import org.jboss.weld.environment.se.WeldContainer;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
|
||||
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
|
||||
import com.baeldung.dependencyinjection.loggers.TimeLogger;
|
||||
|
||||
public class ImageProcessorUnitTest {
|
||||
|
||||
|
||||
private static ImageFileProcessor imageFileProcessor;
|
||||
private static SimpleDateFormat dateFormat;
|
||||
private static Calendar calendar;
|
||||
|
||||
|
||||
|
||||
@BeforeClass
|
||||
public static void setImageProcessorInstance() {
|
||||
Weld weld = new Weld();
|
||||
WeldContainer container = weld.initialize();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class).get();
|
||||
imageFileProcessor = container.select(ImageFileProcessor.class)
|
||||
.get();
|
||||
container.shutdown();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setSimpleDateFormatInstance() {
|
||||
dateFormat = new SimpleDateFormat("HH:mm");
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void setCalendarInstance() {
|
||||
calendar = Calendar.getInstance();
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
|
||||
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
|
||||
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String openFileLog = imageFileProcessor.openFile("file1.png");
|
||||
assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(openFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String editFileLog = imageFileProcessor.editFile("file1.png");
|
||||
assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(editFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String writeFileLog = imageFileProcessor.writeFile("file1.png");
|
||||
assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(writeFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
|
||||
String currentTime = dateFormat.format(calendar.getTime());
|
||||
assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
|
||||
public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
String saveFileLog = imageFileProcessor.saveFile("file1.png");
|
||||
assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
|
||||
|
||||
LocalTime loggedTime = getLoggedTime(saveFileLog);
|
||||
assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
|
||||
}
|
||||
|
||||
private LocalTime getLoggedTime(String log) throws ParseException {
|
||||
String logTimeString = log.split("at: ")[1];
|
||||
|
||||
int hour = Integer.valueOf(logTimeString.split(":")[0]);
|
||||
int minutes = Integer.valueOf(logTimeString.split(":")[1]);
|
||||
|
||||
LocalTime loggedTime = LocalTime.of(hour, minutes);
|
||||
return loggedTime;
|
||||
}
|
||||
}
|
|
@ -15,24 +15,17 @@
|
|||
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
|
||||
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
|
||||
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
|
||||
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
|
||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
|
||||
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
|
||||
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
|
||||
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
|
||||
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
|
||||
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package com.baeldung.optional;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
}
|
|
@ -5,25 +5,22 @@
|
|||
*/
|
||||
package com.baeldung.nullsafecollectionstreams;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author Kwaje Anthony <kwajeanthony@gmail.com>
|
||||
*/
|
||||
public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
|
||||
new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
|
||||
|
||||
@Test
|
||||
public void whenCollectionIsNull_thenExpectAnEmptyStream() {
|
||||
|
@ -49,5 +46,5 @@ public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
|
|||
assertEquals(iter1.next(), iter2.next());
|
||||
assert !iter1.hasNext() && !iter2.hasNext();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
package com.baeldung.throwsexception;
|
||||
package com.baeldung.optional;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
public class PersonRepositoryUnitTest {
|
||||
|
@ -40,14 +40,4 @@ public class PersonRepositoryUnitTest {
|
|||
assertEquals("NAME", name);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIdIsNonNull_thenShouldReturnNameUpperCase() throws Exception {
|
||||
String name = Optional
|
||||
.ofNullable(personRepository.findNameById("id"))
|
||||
.map(String::toUpperCase)
|
||||
.orElseThrow(Exception::new);
|
||||
|
||||
assertEquals("NAME", name);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,97 +0,0 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
import org.openjdk.jmh.runner.options.TimeValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
|
||||
public class BenchmarkUnitTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
Options opt = new OptionsBuilder()
|
||||
// Specify which benchmarks to run.
|
||||
// You can be more specific if you'd like to run only one benchmark per test.
|
||||
.include(this.getClass().getName() + ".*")
|
||||
// Set the following options as needed
|
||||
.mode (Mode.AverageTime)
|
||||
.timeUnit(TimeUnit.MICROSECONDS)
|
||||
.warmupTime(TimeValue.seconds(1))
|
||||
.warmupIterations(2)
|
||||
.measurementTime(TimeValue.seconds(1))
|
||||
.measurementIterations(2)
|
||||
.threads(2)
|
||||
.forks(1)
|
||||
.shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
//.jvmArgs("-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining")
|
||||
//.addProfiler(WinPerfAsmProfiler.class)
|
||||
.build();
|
||||
|
||||
new Runner(opt).run();
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1, 100_000_000).parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamFiltered_showOpsPerMS(){
|
||||
IntStream.range(1,100_000_000).unordered().parallel().filter(i -> i % 10 == 0).toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenUnorderedStreamInput_whenStreamDistinct_showOpsPerMS(){
|
||||
IntStream.range(1, 1_000_000).unordered().parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void givenOrderedStreamInput_whenStreamDistinct_showOpsPerMS() {
|
||||
//section 5.1.
|
||||
IntStream.range(1, 1_000_000).parallel().distinct().toArray();
|
||||
}
|
||||
|
||||
|
||||
// The JMH samples are the best documentation for how to use it
|
||||
// http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
|
||||
@State(Scope.Thread)
|
||||
public static class BenchmarkState
|
||||
{
|
||||
List<Integer> list;
|
||||
|
||||
@Setup(Level.Trial) public void
|
||||
initialize() {
|
||||
|
||||
Random rand = new Random();
|
||||
|
||||
list = new ArrayList<>();
|
||||
for (int i = 0; i < 1000; i++)
|
||||
list.add (rand.nextInt());
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark public void
|
||||
benchmark1 (BenchmarkState state, Blackhole bh) {
|
||||
|
||||
List<Integer> list = state.list;
|
||||
|
||||
for (int i = 0; i < 1000; i++)
|
||||
bh.consume (list.get (i));
|
||||
}
|
||||
}
|
|
@ -1,149 +0,0 @@
|
|||
package com.baeldung.streamordering;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class StreamsOrderingUnitTest {
|
||||
|
||||
Logger logger = Logger.getLogger( StreamsOrderingUnitTest.class.getName());
|
||||
|
||||
@Before
|
||||
public void setUp() throws Exception {
|
||||
logger.setLevel(Level.ALL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamed_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] setOutput = set.stream().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoCollections_whenStreamedInParallel_thenCheckOutputDifferent(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
Set<String> set = new TreeSet<>(Arrays.asList("B", "A", "C", "D", "F"));
|
||||
|
||||
Object[] listOutput = list.stream().parallel().toArray();
|
||||
Object[] setOutput = set.stream().parallel().toArray();
|
||||
|
||||
assertEquals("[B, A, C, D, F]", Arrays.toString(listOutput));
|
||||
assertEquals("[A, B, C, D, F]", Arrays.toString(setOutput));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void givenOrderedInput_whenUnorderedAndOrderedCompared_thenCheckUnorderedOutputChanges(){
|
||||
Set<Integer> set = new TreeSet<>(
|
||||
Arrays.asList(-9, -5, -4, -2, 1, 2, 4, 5, 7, 9, 12, 13, 16, 29, 23, 34, 57, 68, 90, 102, 230));
|
||||
|
||||
Object[] orderedArray = set.stream()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
Object[] unorderedArray = set.stream()
|
||||
.unordered()
|
||||
.parallel()
|
||||
.limit(5)
|
||||
.toArray();
|
||||
|
||||
logger.info(Arrays.toString(orderedArray));
|
||||
logger.info(Arrays.toString(unorderedArray));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamSorted_thenCheckOrderChanged(){
|
||||
|
||||
List<Integer> list = Arrays.asList(-3,10,-4,1,3);
|
||||
|
||||
Object[] listOutput = list.stream().toArray();
|
||||
Object[] listOutputSorted = list.stream().sorted().toArray();
|
||||
|
||||
assertEquals("[-3, 10, -4, 1, 3]", Arrays.toString(listOutput));
|
||||
assertEquals("[-4, -3, 1, 3, 10]", Arrays.toString(listOutputSorted));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnsortedStreamInput_whenStreamDistinct_thenShowTimeTaken(){
|
||||
long start, end;
|
||||
start = System.currentTimeMillis();
|
||||
IntStream.range(1,1_000_000).unordered().parallel().distinct().toArray();
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println(String.format("Time taken when unordered: %d ms", (end - start)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamTerminated_thenCheckEachVsEachOrdered(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
list.stream().parallel().forEach(e -> logger.log(Level.INFO, e));
|
||||
list.stream().parallel().forEachOrdered(e -> logger.log(Level.INFO, e));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSameCollection_whenStreamCollected_thenCheckOutput(){
|
||||
|
||||
List<String> list = Arrays.asList("B", "A", "C", "D", "F");
|
||||
|
||||
List<String> collectionList = list.stream().parallel().collect(Collectors.toList());
|
||||
Set<String> collectionSet = list.stream().parallel().collect(Collectors.toCollection(TreeSet::new));
|
||||
|
||||
assertEquals("[B, A, C, D, F]", collectionList.toString());
|
||||
assertEquals("[A, B, C, D, F]", collectionSet.toString());
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListIterationOrder_whenStreamCollectedToMap_thenCeckOrderChanged() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC");
|
||||
|
||||
Map<String, Integer> hashMap = list.stream().collect(Collectors.toMap(Function.identity(), String::length));
|
||||
|
||||
Object[] keySet = hashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[BB, A, CCC]", Arrays.toString(keySet));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListIteration_whenStreamCollectedtoHashMap_thenCheckOrderMaintained() {
|
||||
List<String> list = Arrays.asList("A", "BB", "CCC", "CCC");
|
||||
|
||||
Map<String, Integer> linkedHashMap = list.stream().collect(Collectors.toMap(
|
||||
Function.identity(),
|
||||
String::length,
|
||||
(u, v) -> u,
|
||||
LinkedHashMap::new
|
||||
));
|
||||
|
||||
Object[] keySet = linkedHashMap.keySet().toArray();
|
||||
|
||||
assertEquals("[A, BB, CCC]", Arrays.toString(keySet));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
package com.baeldung.util;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
@ -10,8 +9,6 @@ import java.time.LocalTime;
|
|||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoField;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CurrentDateTimeUnitTest {
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ChildProcess {
|
||||
|
||||
public static void main(String[] args) {
|
||||
@SuppressWarnings("resource")
|
||||
Scanner input = new Scanner(System.in);
|
||||
Logger log = Logger.getLogger(ChildProcess.class.getName());
|
||||
log.log(Level.INFO, input.nextLine());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class OutputStreamExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Logger log = Logger.getLogger(OutputStreamExample.class.getName());
|
||||
log.log(Level.INFO, Integer.toString(sum(1,2)));
|
||||
}
|
||||
|
||||
public static int sum(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
public class ProcessCompilationError {
|
||||
//This method has been written to generate error to display
|
||||
//how process errorStream() can consume error
|
||||
public static void();
|
||||
}
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class ProcessUnderstanding {
|
||||
|
||||
public static int compileAndRunJavaProgram() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String getErrorStreamExample() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
return errorString;
|
||||
}
|
||||
|
||||
public static void creatingNewProcess() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
}
|
||||
|
||||
public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
|
||||
return (int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyingProcessCreatedByDifferentProcess() {
|
||||
// find out the process id of current running task by checking
|
||||
// task manager in windows and enter the integer value
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
}
|
||||
|
||||
public static int waitForExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
return process.waitFor();
|
||||
}
|
||||
|
||||
public static int exitValueExample() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
process.destroy();
|
||||
return process.exitValue();
|
||||
}
|
||||
|
||||
public static void destroyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
}
|
||||
|
||||
public static void destroyForciblyExample() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
public static void outputStreamDemo() throws IOException, InterruptedException {
|
||||
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
|
||||
Process pr = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
|
||||
final Process process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
|
||||
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
|
||||
w.write("send to child\n");
|
||||
}
|
||||
new Thread(() -> {
|
||||
try {
|
||||
int c;
|
||||
while ((c = process.getInputStream()
|
||||
.read()) != -1)
|
||||
System.out.write((byte) c);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
// send to child
|
||||
log.log(Level.INFO, "rc=" + process.waitFor());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,121 @@
|
|||
package com.baeldung.java9.process;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.lang.String;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.lang.Integer;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProcessUnderstandingTest {
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
|
||||
process = Runtime.getRuntime()
|
||||
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
|
||||
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
|
||||
int value = Integer.parseInt(output.readLine());
|
||||
assertEquals(3, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
|
||||
Process process = Runtime.getRuntime()
|
||||
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
|
||||
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
|
||||
String errorString = error.readLine();
|
||||
assertNotNull(errorString);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
assertTrue(builder.start().isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
if (process.isAlive()) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
Thread.sleep(10000);
|
||||
process.destroy();
|
||||
assertFalse(process.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
|
||||
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
|
||||
ProcessHandle processHandle = optionalProcessHandle.get();
|
||||
processHandle.destroy();
|
||||
assertFalse(processHandle.isAlive());
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.waitFor() >= 0);
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
//@Test - windows specific
|
||||
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
|
||||
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
|
||||
Process process = builder.start();
|
||||
assertThat(process.exitValue() >= 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
|
||||
assertThat(((int) ProcessHandle.allProcesses()
|
||||
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
|
||||
.count()) > 0);
|
||||
}
|
||||
}
|
|
@ -37,3 +37,9 @@
|
|||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
|
||||
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
|
||||
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
|
||||
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
|
||||
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
|
@ -0,0 +1,77 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class ArrayListBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
List<Employee> employeeList = new ArrayList<>();
|
||||
//LinkedList<Employee> employeeList = new LinkedList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(ArrayListBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(ArrayListBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
// @Benchmark
|
||||
// public void testAdd(ArrayListBenchmark.MyState state) {
|
||||
// state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
// }
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(ArrayListBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class CopyOnWriteBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>();
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeList.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
employeeList.add(employee);
|
||||
|
||||
employeeIndex = employeeList.indexOf(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAdd(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add(new Employee(state.iterations + 1, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public void testAddAt(CopyOnWriteBenchmark.MyState state) {
|
||||
state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John"));
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testContains(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public int testIndexOf(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.indexOf(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.get(state.employeeIndex);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(CopyOnWriteBenchmark.MyState state) {
|
||||
return state.employeeList.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -10,6 +10,22 @@ public class Employee {
|
|||
this.id = id;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
|
|
|
@ -0,0 +1,73 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class HashMapBenchmark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
Map<Long, Employee> employeeMap = new HashMap<>();
|
||||
//LinkedHashMap<Long, Employee> employeeMap = new LinkedHashMap<>();
|
||||
//IdentityHashMap<Long, Employee> employeeMap = new IdentityHashMap<>();
|
||||
//WeakHashMap<Long, Employee> employeeMap = new WeakHashMap<>();
|
||||
//ConcurrentHashMap<Long, Employee> employeeMap = new ConcurrentHashMap<>();
|
||||
//ConcurrentSkipListMap<Long, Employee> employeeMap = new ConcurrentSkipListMap <>();
|
||||
|
||||
// TreeMap
|
||||
|
||||
long iterations = 100000;
|
||||
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
int employeeIndex = -1;
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeMap.put(i, new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeMap.put(iterations, employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testGet(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.get(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testRemove(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.remove(state.iterations);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Employee testPut(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.put(state.employee.getId(), state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContainsKey(HashMapBenchmark.MyState state) {
|
||||
return state.employeeMap.containsKey(state.employee.getId());
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(HashMapBenchmark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
package com.baeldung.performance;
|
||||
|
||||
import org.openjdk.jmh.annotations.*;
|
||||
import org.openjdk.jmh.runner.Runner;
|
||||
import org.openjdk.jmh.runner.options.Options;
|
||||
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.concurrent.ConcurrentSkipListSet;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||
@Warmup(iterations = 10)
|
||||
public class SetBenchMark {
|
||||
|
||||
@State(Scope.Thread)
|
||||
public static class MyState {
|
||||
|
||||
//Set<Employee> employeeSet = new HashSet<>();
|
||||
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
|
||||
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
|
||||
|
||||
// TreeSet
|
||||
|
||||
long iterations = 1000;
|
||||
Employee employee = new Employee(100L, "Harry");
|
||||
|
||||
@Setup(Level.Trial)
|
||||
public void setUp() {
|
||||
for (long i = 0; i < iterations; i++) {
|
||||
employeeSet.add(new Employee(i, "John"));
|
||||
}
|
||||
|
||||
//employeeSet.add(employee);
|
||||
}
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testAdd(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.add(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public Boolean testContains(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.contains(state.employee);
|
||||
}
|
||||
|
||||
@Benchmark
|
||||
public boolean testRemove(SetBenchMark.MyState state) {
|
||||
return state.employeeSet.remove(state.employee);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Options options = new OptionsBuilder()
|
||||
.include(SetBenchMark.class.getSimpleName()).threads(1)
|
||||
.forks(1).shouldFailOnError(true)
|
||||
.shouldDoGC(true)
|
||||
.jvmArgs("-server").build();
|
||||
new Runner(options).run();
|
||||
}
|
||||
}
|
|
@ -1,13 +1,17 @@
|
|||
package com.baeldung.list;
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CopyListServiceUnitTest {
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionX {
|
||||
|
||||
public String addCharUsingCharArray(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
int len = str.length();
|
||||
char[] updatedArr = new char[len + 1];
|
||||
str.getChars(0, position, updatedArr, 0);
|
||||
updatedArr[position] = ch;
|
||||
str.getChars(position, len, updatedArr, position + 1);
|
||||
return new String(updatedArr);
|
||||
}
|
||||
|
||||
public String addCharUsingSubstring(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
return str.substring(0, position) + ch + str.substring(position);
|
||||
}
|
||||
|
||||
public String addCharUsingStringBuilder(String str, char ch, int position) {
|
||||
validate(str, position);
|
||||
StringBuilder sb = new StringBuilder(str);
|
||||
sb.insert(position, ch);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void validate(String str, int position) {
|
||||
if (str == null) {
|
||||
throw new IllegalArgumentException("Str should not be null");
|
||||
}
|
||||
int len = str.length();
|
||||
if (position < 0 || position > len) {
|
||||
throw new IllegalArgumentException("position[" + position + "] should be "
|
||||
+ "in the range 0.." + len + " for string " + str);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.synthetic;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic bridge method.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class BridgeMethodDemo implements Comparator<Integer> {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
|
||||
*/
|
||||
@Override
|
||||
public int compare(Integer o1, Integer o2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains a synthetic constructor.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticConstructorDemo {
|
||||
|
||||
/**
|
||||
* We need to instantiate the {@link NestedClass} using a private
|
||||
* constructor from the enclosing instance in order to generate a synthetic
|
||||
* constructor.
|
||||
*/
|
||||
private NestedClass nestedClass = new NestedClass();
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic constructor.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
/**
|
||||
* In order to generate a synthetic constructor, this class must have a
|
||||
* private constructor.
|
||||
*/
|
||||
private NestedClass() {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains a synthetic field reference to the outer
|
||||
* class.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticFieldDemo {
|
||||
|
||||
/**
|
||||
* Class which contains a synthetic field reference to the outer class.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.synthetic;
|
||||
|
||||
/**
|
||||
* Wrapper for a class which contains two synthetic methods accessors to a
|
||||
* private field.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticMethodDemo {
|
||||
|
||||
/**
|
||||
* Class which contains two synthetic methods accessors to a private field.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
class NestedClass {
|
||||
|
||||
/**
|
||||
* Field for which will be generated synthetic methods accessors. It's
|
||||
* important that this field is private for this purpose.
|
||||
*/
|
||||
private String nestedField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the private nested field. We need to read the nested field in order
|
||||
* to generate the synthetic getter.
|
||||
*
|
||||
* @return the {@link NestedClass#nestedField}
|
||||
*/
|
||||
public String getNestedField() {
|
||||
return new NestedClass().nestedField;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the private nested field. We need to write the nested field in order
|
||||
* to generate the synthetic setter.
|
||||
*
|
||||
* @param nestedField
|
||||
* the {@link NestedClass#nestedField}
|
||||
*/
|
||||
public void setNestedField(String nestedField) {
|
||||
new NestedClass().nestedField = nestedField;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,16 +1,10 @@
|
|||
package com.baeldung.throwsexception;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
public class PersonRepository {
|
||||
|
||||
@Nullable
|
||||
public String findNameById(String id) {
|
||||
return id == null ? null : "Name";
|
||||
}
|
||||
|
||||
public List<String> findAll() throws SQLException {
|
||||
throw new SQLException();
|
||||
}
|
||||
|
|
|
@ -0,0 +1,110 @@
|
|||
/**
|
||||
*
|
||||
*/
|
||||
package com.baeldung.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* @author swpraman
|
||||
*
|
||||
*/
|
||||
public class AppendCharAtPositionXUnitTest {
|
||||
|
||||
private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
|
||||
private String word = "Titanc";
|
||||
private char letter = 'i';
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
|
||||
assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
|
||||
assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
|
||||
assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
@Test(expected=IllegalArgumentException.class)
|
||||
public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
|
||||
appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package com.baeldung.synthetic;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
|
||||
* {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
|
||||
*
|
||||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class SyntheticUnitTest {
|
||||
|
||||
/**
|
||||
* Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
|
||||
* methods.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
|
||||
// Checks that the nested class contains exactly two synthetic methods.
|
||||
Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
|
||||
Assert.assertEquals("This class should contain only two methods", 2, methods.length);
|
||||
|
||||
for (Method m : methods) {
|
||||
System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
|
||||
Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
|
||||
* constructor.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
|
||||
// Checks that the nested class contains exactly a synthetic
|
||||
// constructor.
|
||||
int syntheticConstructors = 0;
|
||||
Constructor<?>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
|
||||
Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
|
||||
|
||||
for (Constructor<?> c : constructors) {
|
||||
System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
|
||||
|
||||
// Counts the synthetic constructors.
|
||||
if (c.isSynthetic()) {
|
||||
syntheticConstructors++;
|
||||
}
|
||||
}
|
||||
|
||||
// Checks that there's exactly one synthetic constructor.
|
||||
Assert.assertEquals(1, syntheticConstructors);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
|
||||
*/
|
||||
@Test
|
||||
public void givenSyntheticField_whenIsSinthetic_thenTrue() {
|
||||
// This class should contain exactly one synthetic field.
|
||||
Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
|
||||
Assert.assertEquals("This class should contain only one field", 1, fields.length);
|
||||
|
||||
for (Field f : fields) {
|
||||
System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
|
||||
Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
|
||||
*/
|
||||
@Test
|
||||
public void givenBridgeMethod_whenIsBridge_thenTrue() {
|
||||
// This class should contain exactly one synthetic bridge method.
|
||||
int syntheticMethods = 0;
|
||||
Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
|
||||
for (Method m : methods) {
|
||||
System.out.println(
|
||||
"Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
|
||||
|
||||
// Counts the synthetic methods and checks that they are also bridge
|
||||
// methods.
|
||||
if (m.isSynthetic()) {
|
||||
syntheticMethods++;
|
||||
Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
|
||||
}
|
||||
}
|
||||
|
||||
// Checks that there's exactly one synthetic bridge method.
|
||||
Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
|
||||
}
|
||||
|
||||
}
|
|
@ -16,7 +16,6 @@
|
|||
<groupId>org.wildfly</groupId>
|
||||
<artifactId>wildfly-ejb-client-bom</artifactId>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.ejb</groupId>
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
<modules>
|
||||
<module>ejb-remote</module>
|
||||
<module>ejb-client</module>
|
||||
<module>ejb-session-beans</module>
|
||||
</modules>
|
||||
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jackson</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>jackson</name>
|
||||
|
@ -119,17 +118,16 @@
|
|||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.9.4</jackson.version>
|
||||
<jackson.version>2.9.6</jackson.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
<joda-time.version>2.9.6</joda-time.version>
|
||||
<gson.version>2.8.0</gson.version>
|
||||
<commons-collections4.version>4.1</commons-collections4.version>
|
||||
<commons-lang3.version>3.8</commons-lang3.version>
|
||||
<joda-time.version>2.10</joda-time.version>
|
||||
<gson.version>2.8.5</gson.version>
|
||||
<commons-collections4.version>4.2</commons-collections4.version>
|
||||
|
||||
<!-- testing -->
|
||||
<rest-assured.version>3.0.1</rest-assured.version>
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<rest-assured.version>3.1.1</rest-assured.version>
|
||||
<assertj.version>3.11.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
<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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-streams</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
@ -15,17 +14,17 @@
|
|||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<scope>provided</scope>
|
||||
<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-core</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjdk.jmh</groupId>
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>${jmh.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
|
|
|
@ -1,15 +1,14 @@
|
|||
package com.baeldung.stream;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import org.junit.Test;
|
||||
|
||||
public class PrimitiveStreamsUnitTest {
|
||||
|
||||
|
@ -17,7 +16,7 @@ public class PrimitiveStreamsUnitTest {
|
|||
|
||||
@Test
|
||||
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||
int[] integers = new int[] {20, 98, 12, 7, 35};
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
int min = streams.min(integers); // returns 7
|
||||
|
||||
assertEquals(7, min);
|
||||
|
@ -66,19 +65,14 @@ public class PrimitiveStreamsUnitTest {
|
|||
@Test
|
||||
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||
|
||||
int sum = Stream.of(33,45)
|
||||
.mapToInt(i -> i)
|
||||
.sum();
|
||||
int sum = Stream.of(33, 45).mapToInt(i -> i).sum();
|
||||
|
||||
assertEquals(78, sum);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||
.filter(i -> i % 2 == 0)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
List<Integer> evenInts = IntStream.rangeClosed(1, 10).filter(i -> i % 2 == 0).boxed().collect(Collectors.toList());
|
||||
|
||||
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||
|
||||
|
|
|
@ -18,7 +18,6 @@ import java.util.stream.IntStream;
|
|||
public class BenchmarkUnitTest
|
||||
{
|
||||
|
||||
@Test
|
||||
public void
|
||||
launchBenchmark() throws Exception {
|
||||
|
||||
|
|
|
@ -52,6 +52,13 @@
|
|||
<artifactId>icu4j</artifactId>
|
||||
<version>${icu4j.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.vdurmont</groupId>
|
||||
<artifactId>emoji-java</artifactId>
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.string.sorting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AnagramValidator {
|
||||
|
||||
public static boolean isValid(String text, String anagram) {
|
||||
text = prepare(text);
|
||||
anagram = prepare(anagram);
|
||||
|
||||
String sortedText = sort(text);
|
||||
String sortedAnagram = sort(anagram);
|
||||
|
||||
return sortedText.equals(sortedAnagram);
|
||||
}
|
||||
|
||||
private static String sort(String text) {
|
||||
char[] chars = prepare(text).toCharArray();
|
||||
|
||||
Arrays.sort(chars);
|
||||
return new String(chars);
|
||||
}
|
||||
|
||||
private static String prepare(String text) {
|
||||
return text.toLowerCase()
|
||||
.trim()
|
||||
.replaceAll("\\s+", "");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,78 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.vdurmont.emoji.EmojiParser;
|
||||
|
||||
public class RemovingEmojiFromStringUnitTest {
|
||||
String text = "la conférence, commencera à 10 heures 😅 ✿";
|
||||
String regex = "[^\\p{L}\\p{N}\\p{P}\\p{Z}]";
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingLibrary_thenSuccess() {
|
||||
String result = EmojiParser.removeAllEmojis(text);
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceEmojiUsingLibrary_thenSuccess() {
|
||||
String result = EmojiParser.parseToAliases(text);
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("sweat_smile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingRegex_thenSuccess() {
|
||||
String result = text.replaceAll(regex, "");
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingMatcher_thenSuccess() {
|
||||
Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
String result = matcher.replaceAll("");
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingCodepoints_thenSuccess() {
|
||||
String result = text.replaceAll("[\\x{0001f300}-\\x{0001f64f}]|[\\x{0001f680}-\\x{0001f6ff}]", "");
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemoveEmojiUsingUnicode_thenSuccess() {
|
||||
String result = text.replaceAll("[\ud83c\udf00-\ud83d\ude4f]|[\ud83d\ude80-\ud83d\udeff]", "");
|
||||
System.out.println(result);
|
||||
assertThat(result, not(containsString("😅")));
|
||||
assertThat(result, containsString("à"));
|
||||
assertThat(result, containsString("la"));
|
||||
assertThat(result, containsString("10"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package com.baeldung.string.formatter;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class DateToStringFormatterUnitTest {
|
||||
|
||||
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
|
||||
private static final String EXPECTED_STRING_DATE = "Aug 1, 2018 12:00 PM";
|
||||
private static Date date;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone("CET"));
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(2018, Calendar.AUGUST, 1, 12, 0);
|
||||
date = calendar.getTime();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingSimpleDateFormatToString_thenCorrect() {
|
||||
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
|
||||
String formattedDate = formatter.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateFormatToString_thenCorrect() {
|
||||
String formattedDate = DateFormat
|
||||
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
|
||||
.format(date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingFormatterToString_thenCorrect() {
|
||||
String formattedDate = String.format("%1$tb %1$te, %1$tY %1$tI:%1$tM %1$Tp", date);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDateConvertedUsingDateTimeApiToString_thenCorrect() {
|
||||
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(DATE_FORMAT);
|
||||
Instant instant = date.toInstant();
|
||||
LocalDateTime ldt = instant
|
||||
.atZone(ZoneId.of("CET"))
|
||||
.toLocalDateTime();
|
||||
String formattedDate = ldt.format(fmt);
|
||||
|
||||
assertEquals(EXPECTED_STRING_DATE, formattedDate);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.string.sorting;
|
||||
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.baeldung.string.sorting.AnagramValidator;
|
||||
|
||||
class AnagramValidatorUnitTest {
|
||||
|
||||
@Test
|
||||
void givenValidAnagrams_whenSorted_thenEqual() {
|
||||
boolean isValidAnagram = AnagramValidator.isValid("Avida Dollars", "Salvador Dali");
|
||||
|
||||
assertTrue(isValidAnagram);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNotValidAnagrams_whenSorted_thenNotEqual() {
|
||||
boolean isValidAnagram = AnagramValidator.isValid("abc", "def");
|
||||
|
||||
assertFalse(isValidAnagram);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.baeldung.string.sorting;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class SortStringUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenSort_thenSorted() {
|
||||
String abcd = "bdca";
|
||||
char[] chars = abcd.toCharArray();
|
||||
|
||||
Arrays.sort(chars);
|
||||
String sorted = new String(chars);
|
||||
|
||||
assertThat(sorted).isEqualTo("abcd");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenSortJava8_thenSorted() {
|
||||
String sorted = "bdca".chars()
|
||||
.sorted()
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
|
||||
assertThat(sorted).isEqualTo("abcd");
|
||||
}
|
||||
}
|
|
@ -384,10 +384,6 @@
|
|||
</profile>
|
||||
</profiles>
|
||||
|
||||
<prerequisites>
|
||||
<maven>${maven.min.version}</maven>
|
||||
</prerequisites>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>bintray-mvc-spec-maven</id>
|
||||
|
|
|
@ -1,67 +0,0 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung.samples</groupId>
|
||||
<artifactId>jersey-client-rx</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.inject</groupId>
|
||||
<artifactId>jersey-hk2</artifactId>
|
||||
<version>2.27</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.core</groupId>
|
||||
<artifactId>jersey-client</artifactId>
|
||||
<version>2.27</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.ext.rx</groupId>
|
||||
<artifactId>jersey-rx-client-rxjava</artifactId>
|
||||
<version>2.27</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.ext.rx</groupId>
|
||||
<artifactId>jersey-rx-client-rxjava2</artifactId>
|
||||
<version>2.27</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.tomakehurst</groupId>
|
||||
<artifactId>wiremock</artifactId>
|
||||
<version>1.58</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>5.2.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-jackson</artifactId>
|
||||
<version>2.25</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.jaxrs</groupId>
|
||||
<artifactId>jackson-jaxrs-json-provider</artifactId>
|
||||
<version>2.4.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-jdk14</artifactId>
|
||||
<version>1.7.25</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.10.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
</properties>
|
||||
</project>
|
|
@ -1,3 +0,0 @@
|
|||
# Fluent, Reactive Jersey Client Orchestration #
|
||||
|
||||
### Sample code demonstrating the options for asynchronous, reactive RESTful service consumption with JAX-RS ###
|
|
@ -0,0 +1,102 @@
|
|||
package com.baeldung.jersey.server;
|
||||
|
||||
import com.baeldung.jersey.server.model.Person;
|
||||
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@Path("/response")
|
||||
public class Responder {
|
||||
|
||||
@GET
|
||||
@Path("/ok")
|
||||
public Response getOkResponse() {
|
||||
|
||||
String message = "This is a text response";
|
||||
|
||||
return Response
|
||||
.status(Response.Status.OK)
|
||||
.entity(message)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/not_ok")
|
||||
public Response getNOkTextResponse() {
|
||||
|
||||
String message = "There was an internal server error";
|
||||
|
||||
return Response
|
||||
.status(Response.Status.INTERNAL_SERVER_ERROR)
|
||||
.entity(message)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/text_plain")
|
||||
public Response getTextResponseTypeDefined() {
|
||||
|
||||
String message = "This is a plain text response";
|
||||
|
||||
return Response
|
||||
.status(Response.Status.OK)
|
||||
.entity(message)
|
||||
.type(MediaType.TEXT_PLAIN)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/text_plain_annotation")
|
||||
@Produces({ MediaType.TEXT_PLAIN })
|
||||
public Response getTextResponseTypeAnnotated() {
|
||||
|
||||
String message = "This is a plain text response via annotation";
|
||||
|
||||
return Response
|
||||
.status(Response.Status.OK)
|
||||
.entity(message)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/pojo")
|
||||
public Response getPojoResponse() {
|
||||
|
||||
Person person = new Person("Abh", "Nepal");
|
||||
|
||||
return Response
|
||||
.status(Response.Status.OK)
|
||||
.entity(person)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/json")
|
||||
public Response getJsonResponse() {
|
||||
|
||||
String message = "{\"hello\": \"This is a JSON response\"}";
|
||||
|
||||
return Response
|
||||
.status(Response.Status.OK)
|
||||
.entity(message)
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/xml")
|
||||
@Produces(MediaType.TEXT_XML)
|
||||
public String sayXMLHello() {
|
||||
return "<?xml version=\"1.0\"?>" + "<hello> This is a xml response </hello>";
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/html")
|
||||
@Produces(MediaType.TEXT_HTML)
|
||||
public String sayHtmlHello() {
|
||||
return "<html> " + "<title>" + " This is a html title </title>" + "<body><h1>" + " This is a html response body " + "</body></h1>" + "</html> ";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.jersey.server.model;
|
||||
|
||||
public class Person {
|
||||
String name;
|
||||
String address;
|
||||
|
||||
public Person(String name, String address) {
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Person [name: " + getName() + " address: " + getAddress() + "]";
|
||||
}
|
||||
}
|
|
@ -1,9 +1,7 @@
|
|||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jhipster-monolithic</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<description>JHipster Monolithic Application</description>
|
||||
|
||||
|
@ -89,8 +87,7 @@
|
|||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-annotation</artifactId>
|
||||
<version>${dropwizard-metrics.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
|
@ -98,18 +95,15 @@
|
|||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-json</artifactId>
|
||||
<version>${dropwizard-metrics.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-jvm</artifactId>
|
||||
<version>${dropwizard-metrics.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-servlet</artifactId>
|
||||
<version>${dropwizard-metrics.version}</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-servlets</artifactId>
|
||||
|
@ -418,6 +412,7 @@
|
|||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-eclipse-plugin</artifactId>
|
||||
<version>${maven-eclipse-plugin.version}</version>
|
||||
<configuration>
|
||||
<downloadSources>true</downloadSources>
|
||||
<downloadJavadocs>true</downloadJavadocs>
|
||||
|
@ -493,17 +488,6 @@
|
|||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<!-- Force alphabetical order to have a reproducible build -->
|
||||
<runOrder>alphabetical</runOrder>
|
||||
<excludes>
|
||||
<exclude>**/*IntTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
|
@ -536,7 +520,7 @@
|
|||
<plugin>
|
||||
<groupId>org.liquibase</groupId>
|
||||
<artifactId>liquibase-maven-plugin</artifactId>
|
||||
<version>${liquibase.version}</version>
|
||||
<version>${liquibase-maven-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
|
@ -896,10 +880,6 @@
|
|||
</profile>
|
||||
</profiles>
|
||||
|
||||
<prerequisites>
|
||||
<maven>${maven.version}</maven>
|
||||
</prerequisites>
|
||||
|
||||
<properties>
|
||||
<argLine>-Djava.security.egd=file:/dev/./urandom -Xmx256m</argLine>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
|
@ -920,11 +900,13 @@
|
|||
<jzlib.version>1.1.3</jzlib.version>
|
||||
<liquibase-hibernate5.version>3.6</liquibase-hibernate5.version>
|
||||
<liquibase-slf4j.version>2.0.0</liquibase-slf4j.version>
|
||||
<liquibase-maven-plugin.version>3.6.2</liquibase-maven-plugin.version>
|
||||
<logstash-logback-encoder.version>4.8</logstash-logback-encoder.version>
|
||||
<m2e.apt.activation>jdt_apt</m2e.apt.activation>
|
||||
<mapstruct.version>1.1.0.Final</mapstruct.version>
|
||||
<maven-enforcer-plugin.version>1.4.1</maven-enforcer-plugin.version>
|
||||
<maven-resources-plugin.version>3.0.1</maven-resources-plugin.version>
|
||||
<maven-eclipse-plugin.version>2.10</maven-eclipse-plugin.version>
|
||||
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
|
||||
<maven.version>3.0.0</maven.version>
|
||||
<metrics-spring.version>3.1.3</metrics-spring.version>
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
</properties>
|
||||
|
||||
<build>
|
||||
<finalName>${artifactId}</finalName>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>net.wasdev.wlp.maven.plugins</groupId>
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
### Relevant Articles:
|
||||
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
|
|
@ -1,65 +0,0 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>jpa-storedprocedure</artifactId>
|
||||
<version>1.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<!-- core library -->
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-api</artifactId>
|
||||
<version>${jee.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<!-- MySql JDBC -->
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>${mysql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>JpaStoredProcedure</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<!--archive> <manifest> <mainClass>fully.qualified.MainClass</mainClass> </manifest> </archive -->
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jee.version>7.0</jee.version>
|
||||
<hibernate.version>5.2.5.Final</hibernate.version>
|
||||
<mysql.version>6.0.5</mysql.version>
|
||||
<commons-io.version>2.5</commons-io.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -1,20 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
|
||||
version="2.1">
|
||||
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung" />
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung" />
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
|
||||
<property name="hibernate.show_sql" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
|
@ -1,13 +0,0 @@
|
|||
<?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>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
|
@ -36,11 +36,6 @@
|
|||
<version>${jstl.version}</version>
|
||||
</dependency>
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
|
|
23
jws/pom.xml
23
jws/pom.xml
|
@ -13,20 +13,23 @@
|
|||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>OpenNMS Repository</id>
|
||||
<url>http://repo.opennms.org/maven2/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>javax.jnlp</groupId>
|
||||
<groupId>javax.samples.jnlp</groupId>
|
||||
<artifactId>jnlp-servlet</artifactId>
|
||||
<version>${jnlp-servlet.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${project.basedir}/java-core-samples-lib/jnlp-servlet.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.jnlp</groupId>
|
||||
<artifactId>jardiff</artifactId>
|
||||
<version>${jardiff.version}</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${project.basedir}/java-core-samples-lib/jardiff.jar</systemPath>
|
||||
<groupId>javax.samples.jnlp</groupId>
|
||||
<artifactId>jnlp-jardiff</artifactId>
|
||||
<version>${jnlp-jardiff.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
@ -81,8 +84,8 @@
|
|||
<properties>
|
||||
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
|
||||
<maven-war-plugin.version>3.0.0</maven-war-plugin.version>
|
||||
<jardiff.version>7.0</jardiff.version>
|
||||
<jnlp-servlet.version>7.0</jnlp-servlet.version>
|
||||
<jnlp-jardiff.version>1.6.0</jnlp-jardiff.version>
|
||||
<jnlp-servlet.version>1.6.0</jnlp-servlet.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Embedded Jetty Server in Java](http://www.baeldung.com/jetty-embedded)
|
||||
- [Introduction to Netty](http://www.baeldung.com/netty)
|
||||
- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
|
||||
- [Programatically Create, Configure, and Run a Tomcat Server](http://www.baeldung.com/tomcat-programmatic-setup)
|
||||
- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
|
||||
- [Testing Netty with EmbeddedChannel](http://www.baeldung.com/testing-netty-embedded-channel)
|
||||
|
|
@ -14,6 +14,73 @@
|
|||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>1.2.0</version>
|
||||
</dependency>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-server</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-servlet</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.jetty</groupId>
|
||||
<artifactId>jetty-webapp</artifactId>
|
||||
<version>${jetty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>${httpclient.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
<groupId>commons-logging</groupId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons.io.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.netty</groupId>
|
||||
<artifactId>netty-all</artifactId>
|
||||
<version>${netty.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- tomcat -->
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-catalina</artifactId>
|
||||
<version>${tomcat.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<httpclient.version>4.5.3</httpclient.version>
|
||||
<commons.io.version>2.5</commons.io.version>
|
||||
<jetty.version>9.4.8.v20171121</jetty.version>
|
||||
<netty.version>4.1.20.Final</netty.version>
|
||||
<commons.collections.version>4.1</commons.collections.version>
|
||||
<junit.version>4.12</junit.version>
|
||||
<tomcat.version>8.5.24</tomcat.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue