Merge pull request #1 from eugenp/master

Merging base into fork
This commit is contained in:
Neeraj Yadav 2018-06-20 15:09:24 +05:30 committed by GitHub
commit 98ac1d4374
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
455 changed files with 7590 additions and 1508 deletions

View File

@ -40,5 +40,3 @@ This tutorials project is being built **[>> HERE](https://rest-security.ci.cloud
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure) - [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
- [Apache Maven Tutorial](http://www.baeldung.com/maven) - [Apache Maven Tutorial](http://www.baeldung.com/maven)
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library) - [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
- [Java Service Provider Interface](http://www.baeldung.com/java-spi)
- [Java Streams vs Vavr Streams](http://www.baeldung.com/vavr-java-streams)

View File

@ -148,7 +148,7 @@ public class Board {
System.out.println("Game Draw"); System.out.println("Game Draw");
break; break;
case IN_PROGRESS: case IN_PROGRESS:
System.out.println("Game In rogress"); System.out.println("Game In Progress");
break; break;
} }
} }

View File

@ -1,12 +1,21 @@
package com.baeldung.linkedlist; package com.baeldung.algorithms.middleelementlookup;
import com.baeldung.linkedlist.LinkedList.Node; import java.util.LinkedList;
import java.util.Optional;
public class MiddleElementLookup { public class MiddleElementLookup {
public static String findMiddleElement(Node head) { public static Optional<String> findMiddleElementLinkedList(LinkedList<String> linkedList) {
if (linkedList == null || linkedList.isEmpty()) {
return Optional.empty();
}
return Optional.ofNullable(linkedList.get((linkedList.size() - 1) / 2));
}
public static Optional<String> findMiddleElementFromHead(Node head) {
if (head == null) { if (head == null) {
return null; return Optional.empty();
} }
// calculate the size of the list // calculate the size of the list
@ -23,17 +32,17 @@ public class MiddleElementLookup {
current = current.next(); current = current.next();
} }
return current.data(); return Optional.ofNullable(current.data());
} }
public static String findMiddleElement1PassRecursively(Node head) { public static Optional<String> findMiddleElementFromHead1PassRecursively(Node head) {
if (head == null) { if (head == null) {
return null; return Optional.empty();
} }
MiddleAuxRecursion middleAux = new MiddleAuxRecursion(); MiddleAuxRecursion middleAux = new MiddleAuxRecursion();
findMiddleRecursively(head, middleAux); findMiddleRecursively(head, middleAux);
return middleAux.middle.data(); return Optional.ofNullable(middleAux.middle.data());
} }
private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) { private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
@ -53,9 +62,9 @@ public class MiddleElementLookup {
middleAux.length--; middleAux.length--;
} }
public static String findMiddleElement1PassIteratively(Node head) { public static Optional<String> findMiddleElementFromHead1PassIteratively(Node head) {
if (head == null) { if (head == null) {
return null; return Optional.empty();
} }
Node slowPointer = head; Node slowPointer = head;
@ -68,7 +77,7 @@ public class MiddleElementLookup {
slowPointer = slowPointer.next(); slowPointer = slowPointer.next();
} }
return slowPointer.data(); return Optional.ofNullable(slowPointer.data());
} }
private static class MiddleAuxRecursion { private static class MiddleAuxRecursion {

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.middleelementlookup;
public class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return this.data;
}
}

View File

@ -0,0 +1,118 @@
package algorithms;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;
import org.junit.Test;
import java.util.LinkedList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class MiddleElementLookupUnitTest {
@Test
public void whenFindingMiddleLinkedList_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementLinkedList(createLinkedList(4))
.get());
}
@Test
public void whenFindingMiddleFromHead_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead(createNodesList(4))
.get());
}
@Test
public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(createNodesList(4))
.get());
}
@Test
public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() {
assertEquals("3", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(5))
.get());
assertEquals("2", MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(createNodesList(4))
.get());
}
@Test
public void whenListEmptyOrNull_thenMiddleNotFound() {
// null list
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(null)
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(null)
.isPresent());
// empty LinkedList
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(new LinkedList<>())
.isPresent());
// LinkedList with nulls
LinkedList<String> nullsList = new LinkedList<>();
nullsList.add(null);
nullsList.add(null);
assertFalse(MiddleElementLookup
.findMiddleElementLinkedList(nullsList)
.isPresent());
// nodes with null values
assertFalse(MiddleElementLookup
.findMiddleElementFromHead(new Node(null))
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassIteratively(new Node(null))
.isPresent());
assertFalse(MiddleElementLookup
.findMiddleElementFromHead1PassRecursively(new Node(null))
.isPresent());
}
private static LinkedList<String> createLinkedList(int n) {
LinkedList<String> list = new LinkedList<>();
for (int i = 1; i <= n; i++) {
list.add(String.valueOf(i));
}
return list;
}
private static Node createNodesList(int n) {
Node head = new Node("1");
Node current = head;
for (int i = 2; i <= n; i++) {
Node newNode = new Node(String.valueOf(i));
current.setNext(newNode);
current = newNode;
}
return head;
}
}

View File

@ -0,0 +1,139 @@
package com.baeldung.algorithms.analysis;
import org.junit.Test;
public class AnalysisRunnerLiveTest {
int n = 10;
int total = 0;
@Test
public void whenConstantComplexity_thenConstantRuntime() {
System.out.println("**** n = " + n + " ****");
System.out.println();
// Constant Time
System.out.println("**** Constant time ****");
System.out.println("Hey - your input is: " + n);
System.out.println("Running time not dependent on input size!");
System.out.println();
}
@Test
public void whenLogarithmicComplexity_thenLogarithmicRuntime() {
// Logarithmic Time
System.out.println("**** Logarithmic Time ****");
for (int i = 1; i < n; i = i * 2) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenLinearComplexity_thenLinearRuntime() {
// Linear Time
System.out.println("**** Linear Time ****");
for (int i = 0; i < n; i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenNLogNComplexity_thenNLogNRuntime() {
// N Log N Time
System.out.println("**** nlogn Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j < n; j = j * 2) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
total++;
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenQuadraticComplexity_thenQuadraticRuntime() {
// Quadratic Time
System.out.println("**** Quadratic Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j);
total++;
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenCubicComplexity_thenCubicRuntime() {
// Cubic Time
System.out.println("**** Cubic Time ****");
total = 0;
for (
int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
// System.out.println("Hey - I'm busy looking at: " + i + " and " + j + " and " + k);
total++;
}
}
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenExponentialComplexity_thenExponentialRuntime() {
// Exponential Time
System.out.println("**** Exponential Time ****");
total = 0;
for (
int i = 1; i <= Math.pow(2, n); i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
System.out.println();
}
@Test
public void whenFactorialComplexity_thenFactorialRuntime() {
// Factorial Time
System.out.println("**** Factorial Time ****");
total = 0;
for (
int i = 1; i <=
factorial(n); i++) {
// System.out.println("Hey - I'm busy looking at: " + i);
total++;
}
System.out.println("Total amount of times run: " + total);
}
static int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
}

View File

@ -5,7 +5,7 @@
<artifactId>animal-sniffer-mvn-plugin</artifactId> <artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<name>example-animal-sniffer-mvn-plugin</name> <name>animal-sniffer-mvn-plugin</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<parent> <parent>

View File

@ -1,15 +1,17 @@
package com.baeldung.poi.powerpoint; package com.baeldung.poi.powerpoint;
import java.io.File;
import java.util.List;
import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape; import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide; import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.util.List;
public class PowerPointIntegrationTest { public class PowerPointIntegrationTest {
@ -17,9 +19,12 @@ public class PowerPointIntegrationTest {
private String fileLocation; private String fileLocation;
private static final String FILE_NAME = "presentation.pptx"; private static final String FILE_NAME = "presentation.pptx";
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
File currDir = new File("."); File currDir = tempFolder.newFolder();
String path = currDir.getAbsolutePath(); String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;

View File

@ -5,7 +5,6 @@
<groupId>com.example</groupId> <groupId>com.example</groupId>
<artifactId>spring-boot-camel</artifactId> <artifactId>spring-boot-camel</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>Spring-Boot - Camel API</name>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -14,6 +14,24 @@
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId> <artifactId>spring-context</artifactId>

View File

@ -0,0 +1,18 @@
package com.baeldung.dependencyinjection.application;
import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
public class FileApplication {
public static void main(String[] args) {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get();
System.out.println(imageFileProcessor.openFile("file1.png"));
System.out.println(imageFileProcessor.writeFile("file1.png"));
System.out.println(imageFileProcessor.saveFile("file1.png"));
container.shutdown();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.dependencyinjection.factories;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.enterprise.inject.Produces;
public class TimeLoggerFactory {
@Produces
public TimeLogger getTimeLogger() {
return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.dependencyinjection.imagefileeditors;
import com.baeldung.dependencyinjection.qualifiers.GifFileEditorQualifier;
@GifFileEditorQualifier
public class GifFileEditor implements ImageFileEditor {
@Override
public String openFile(String fileName) {
return "Opening GIF file " + fileName;
}
@Override
public String editFile(String fileName) {
return "Editing GIF file " + fileName;
}
@Override
public String writeFile(String fileName) {
return "Writing GIF file " + fileName;
}
@Override
public String saveFile(String fileName) {
return "Saving GIF file " + fileName;
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.dependencyinjection.imagefileeditors;
public interface ImageFileEditor {
String openFile(String fileName);
String editFile(String fileName);
String writeFile(String fileName);
String saveFile(String fileName);
}

View File

@ -0,0 +1,27 @@
package com.baeldung.dependencyinjection.imagefileeditors;
import com.baeldung.dependencyinjection.qualifiers.JpgFileEditorQualifier;
@JpgFileEditorQualifier
public class JpgFileEditor implements ImageFileEditor {
@Override
public String openFile(String fileName) {
return "Opening JPG file " + fileName;
}
@Override
public String editFile(String fileName) {
return "Editing JPG file " + fileName;
}
@Override
public String writeFile(String fileName) {
return "Writing JPG file " + fileName;
}
@Override
public String saveFile(String fileName) {
return "Saving JPG file " + fileName;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.dependencyinjection.imagefileeditors;
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
@PngFileEditorQualifier
public class PngFileEditor implements ImageFileEditor {
@Override
public String openFile(String fileName) {
return "Opening PNG file " + fileName;
}
@Override
public String editFile(String fileName) {
return "Editing PNG file " + fileName;
}
@Override
public String writeFile(String fileName) {
return "Writing PNG file " + fileName;
}
@Override
public String saveFile(String fileName) {
return "Saving PNG file " + fileName;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.dependencyinjection.imageprocessors;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
import javax.inject.Inject;
import com.baeldung.dependencyinjection.imagefileeditors.ImageFileEditor;
public class ImageFileProcessor {
private final ImageFileEditor imageFileEditor;
private final TimeLogger timeLogger;
@Inject
public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) {
this.imageFileEditor = imageFileEditor;
this.timeLogger = timeLogger;
}
public ImageFileEditor getImageFileditor() {
return imageFileEditor;
}
public TimeLogger getTimeLogger() {
return timeLogger;
}
public String openFile(String fileName) {
return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime();
}
public String editFile(String fileName) {
return imageFileEditor.editFile(fileName) + " at: " + timeLogger.getTime();
}
public String writeFile(String fileName) {
return imageFileEditor.writeFile(fileName) + " at: " + timeLogger.getTime();
}
public String saveFile(String fileName) {
return imageFileEditor.saveFile(fileName)+ " at: " + timeLogger.getTime();
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.dependencyinjection.loggers;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeLogger {
private final SimpleDateFormat dateFormat;
private final Calendar calendar;
public TimeLogger(SimpleDateFormat dateFormat, Calendar calendar) {
this.dateFormat = dateFormat;
this.calendar = calendar;
}
public String getTime() {
return dateFormat.format(calendar.getTime());
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.dependencyinjection.qualifiers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
public @interface GifFileEditorQualifier {}

View File

@ -0,0 +1,12 @@
package com.baeldung.dependencyinjection.qualifiers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
public @interface JpgFileEditorQualifier {}

View File

@ -0,0 +1,12 @@
package com.baeldung.dependencyinjection.qualifiers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
public @interface PngFileEditorQualifier {}

View File

@ -0,0 +1,37 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
public class GifFileEditorUnitTest {
private static GifFileEditor gifFileEditor;
@BeforeClass
public static void setGifFileEditorInstance() {
gifFileEditor = new GifFileEditor();
}
@Test
public void givenGifFileEditorlInstance_whenCalledopenFile_thenOneAssertion() {
assertThat(gifFileEditor.openFile("file1.gif")).isEqualTo("Opening GIF file file1.gif");
}
@Test
public void givenGifFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
assertThat(gifFileEditor.editFile("file1.gif")).isEqualTo("Editing GIF file file1.gif");
}
@Test
public void givenGifFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
assertThat(gifFileEditor.writeFile("file1.gif")).isEqualTo("Writing GIF file file1.gif");
}
@Test
public void givenGifFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
assertThat(gifFileEditor.saveFile("file1.gif")).isEqualTo("Saving GIF file file1.gif");
}
}

View File

@ -0,0 +1,70 @@
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 org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.BeforeClass;
import org.junit.Test;
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();
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);
}
@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);
}
@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);
}
@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);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
public class JpgFileEditorUnitTest {
private static JpgFileEditor jpgFileUtil;
@BeforeClass
public static void setJpgFileEditorInstance() {
jpgFileUtil = new JpgFileEditor();
}
@Test
public void givenJpgFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
assertThat(jpgFileUtil.openFile("file1.jpg")).isEqualTo("Opening JPG file file1.jpg");
}
@Test
public void givenJpgFileEditorlInstance_whenCallededitFile_thenOneAssertion() {
assertThat(jpgFileUtil.editFile("file1.gif")).isEqualTo("Editing JPG file file1.gif");
}
@Test
public void givenJpgFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
assertThat(jpgFileUtil.writeFile("file1.jpg")).isEqualTo("Writing JPG file file1.jpg");
}
@Test
public void givenJpgFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
assertThat(jpgFileUtil.saveFile("file1.jpg")).isEqualTo("Saving JPG file file1.jpg");
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
import com.baeldung.dependencyinjection.qualifiers.PngFileEditorQualifier;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
@PngFileEditorQualifier
public class PngFileEditorUnitTest {
private static PngFileEditor pngFileEditor;
@BeforeClass
public static void setPngFileEditorInstance() {
pngFileEditor = new PngFileEditor();
}
@Test
public void givenPngFileEditorInstance_whenCalledopenFile_thenOneAssertion() {
assertThat(pngFileEditor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png");
}
@Test
public void givenPngFileEditorInstance_whenCallededitFile_thenOneAssertion() {
assertThat(pngFileEditor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png");
}
@Test
public void givenPngFileEditorInstance_whenCalledwriteFile_thenOneAssertion() {
assertThat(pngFileEditor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png");
}
@Test
public void givenPngFileEditorInstance_whenCalledsaveFile_thenOneAssertion() {
assertThat(pngFileEditor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.factories.TimeLoggerFactory;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TimeLoggerFactoryUnitTest {
@Test
public void givenTimeLoggerFactory_whenCalledgetTimeLogger_thenOneAssertion() {
TimeLoggerFactory timeLoggerFactory = new TimeLoggerFactory();
assertThat(timeLoggerFactory.getTimeLogger()).isInstanceOf(TimeLogger.class);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.test.dependencyinjection;
import com.baeldung.dependencyinjection.loggers.TimeLogger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TimeLoggerUnitTest {
@Test
public void givenTimeLoggerInstance_whenCalledgetLogTime_thenOneAssertion() {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
Calendar calendar = Calendar.getInstance();
TimeLogger timeLogger = new TimeLogger(dateFormat, calendar);
String currentTime = dateFormat.format(calendar.getTime());
assertThat(timeLogger.getTime()).isEqualTo(currentTime);
}
}

View File

@ -52,4 +52,4 @@
- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time) - [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [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) - [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)

View File

@ -0,0 +1,60 @@
package com.baeldung.java8;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.junit.Assert.assertEquals;
public class UnsignedArithmeticUnitTest {
@Test
public void whenDoublingALargeByteNumber_thenOverflow() {
byte b1 = 100;
byte b2 = (byte) (b1 << 1);
assertEquals(-56, b2);
}
@Test
public void whenComparingNumbers_thenNegativeIsInterpretedAsUnsigned() {
int positive = Integer.MAX_VALUE;
int negative = Integer.MIN_VALUE;
int signedComparison = Integer.compare(positive, negative);
assertEquals(1, signedComparison);
int unsignedComparison = Integer.compareUnsigned(positive, negative);
assertEquals(-1, unsignedComparison);
assertEquals(negative, positive + 1);
}
@Test
public void whenDividingNumbers_thenNegativeIsInterpretedAsUnsigned() {
int positive = Integer.MAX_VALUE;
int negative = Integer.MIN_VALUE;
assertEquals(-1, negative / positive);
assertEquals(1, Integer.divideUnsigned(negative, positive));
assertEquals(-1, negative % positive);
assertEquals(1, Integer.remainderUnsigned(negative, positive));
}
@Test
public void whenParsingNumbers_thenNegativeIsInterpretedAsUnsigned() {
Throwable thrown = catchThrowable(() -> Integer.parseInt("2147483648"));
assertThat(thrown).isInstanceOf(NumberFormatException.class);
assertEquals(Integer.MAX_VALUE + 1, Integer.parseUnsignedInt("2147483648"));
}
@Test
public void whenFormattingNumbers_thenNegativeIsInterpretedAsUnsigned() {
String signedString = Integer.toString(Integer.MIN_VALUE);
assertEquals("-2147483648", signedString);
String unsignedString = Integer.toUnsignedString(Integer.MIN_VALUE);
assertEquals("2147483648", unsignedString);
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.typeinference;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
public class TypeInferenceUnitTest {
@Test
public void givenNoTypeInference_whenInvokingGenericMethodsWithTypeParameters_ObjectsAreCreated() {
// Without type inference. code is verbose.
Map<String, Map<String, String>> mapOfMaps = new HashMap<String, Map<String, String>>();
List<String> strList = Collections.<String> emptyList();
List<Integer> intList = Collections.<Integer> emptyList();
assertTrue(mapOfMaps.isEmpty());
assertTrue(strList.isEmpty());
assertTrue(intList.isEmpty());
}
@Test
public void givenTypeInference_whenInvokingGenericMethodsWithoutTypeParameters_ObjectsAreCreated() {
// With type inference. code is concise.
List<String> strListInferred = Collections.emptyList();
List<Integer> intListInferred = Collections.emptyList();
assertTrue(strListInferred.isEmpty());
assertTrue(intListInferred.isEmpty());
}
@Test
public void givenJava7_whenInvokingCostructorWithoutTypeParameters_ObjectsAreCreated() {
// Type Inference for constructor using diamond operator.
Map<String, Map<String, String>> mapOfMapsInferred = new HashMap<>();
assertTrue(mapOfMapsInferred.isEmpty());
assertEquals("public class java.util.HashMap<K,V>", mapOfMapsInferred.getClass()
.toGenericString());
}
static <T> List<T> add(List<T> list, T a, T b) {
list.add(a);
list.add(b);
return list;
}
@Test
public void givenGenericMethod_WhenInvokedWithoutExplicitTypes_TypesAreInferred() {
// Generalized target-type inference
List<String> strListGeneralized = add(new ArrayList<>(), "abc", "def");
List<Integer> intListGeneralized = add(new ArrayList<>(), 1, 2);
List<Number> numListGeneralized = add(new ArrayList<>(), 1, 2.0);
assertEquals("public class java.util.ArrayList<E>", strListGeneralized.getClass()
.toGenericString());
assertFalse(intListGeneralized.isEmpty());
assertEquals(2, numListGeneralized.size());
}
@Test
public void givenLambdaExpressions_whenParameterTypesNotSpecified_ParameterTypesAreInferred() {
// Type Inference and Lambda Expressions.
List<Integer> intList = Arrays.asList(5, 3, 4, 2, 1);
Collections.sort(intList, (a, b) -> {
assertEquals("java.lang.Integer", a.getClass().getName());
return a.compareTo(b);
});
assertEquals("[1, 2, 3, 4, 5]", Arrays.toString(intList.toArray()));
List<String> strList = Arrays.asList("Red", "Blue", "Green");
Collections.sort(strList, (a, b) -> {
assertEquals("java.lang.String", a.getClass().getName());
return a.compareTo(b);
});
assertEquals("[Blue, Green, Red]", Arrays.toString(strList.toArray()));
}
}

View File

@ -25,3 +25,4 @@
- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue) - [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity) - [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional) - [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)

View File

@ -1,6 +1,7 @@
package org.baeldung.java.io; package org.baeldung.java.io;
import org.junit.Test; import org.junit.Test;
import org.junit.Ignore;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -105,6 +106,7 @@ public class JavaReadFromFileUnitTest {
} }
@Test @Test
@Ignore // TODO
public void whenReadUTFEncodedFile_thenCorrect() throws IOException { public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
final String expected_value = "青空"; final String expected_value = "青空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8")); final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));

View File

@ -141,6 +141,7 @@
- [Java KeyStore API](http://www.baeldung.com/java-keystore) - [Java KeyStore API](http://www.baeldung.com/java-keystore)
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking) - [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
- [Guide to Java Clock Class](http://www.baeldung.com/java-clock) - [Guide to Java Clock Class](http://www.baeldung.com/java-clock)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Using Java Assertions](http://www.baeldung.com/java-assert) - [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference) - [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number) - [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
@ -149,5 +150,13 @@
- [NaN in Java](http://www.baeldung.com/java-not-a-number) - [NaN in Java](http://www.baeldung.com/java-not-a-number)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java) - [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords) - [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)
- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)

View File

@ -0,0 +1,9 @@
package com.baeldung.accessmodifiers;
public class Public {
public Public() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in the same package or subclass.
SuperPublic.defaultMethod(); // Available in the same package.
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.accessmodifiers;
public class SubClass extends SuperPublic {
public SubClass() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in the same package or subclass.
SuperPublic.defaultMethod(); // Available in the same package.
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.accessmodifiers;
//Only public or default access modifiers are permitted
public class SuperPublic {
// Always available from anywhere
static public void publicMethod() {
System.out.println(SuperPublic.class.getName() + " publicMethod()");
}
// Available within the same package
static void defaultMethod() {
System.out.println(SuperPublic.class.getName() + " defaultMethod()");
}
// Available within the same package and subclasses
static protected void protectedMethod() {
System.out.println(SuperPublic.class.getName() + " protectedMethod()");
}
// Available within the same class only
static private void privateMethod() {
System.out.println(SuperPublic.class.getName() + " privateMethod()");
}
// Method in the same class = has access to all members within the same class
private void anotherPrivateMethod() {
privateMethod();
defaultMethod();
protectedMethod();
publicMethod(); // Available in the same class only.
}
}
// Only public or default access modifiers are permitted
class SuperDefault {
public void publicMethod() {
System.out.println(this.getClass().getName() + " publicMethod()");
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherPublic {
public AnotherPublic() {
SuperPublic.publicMethod(); // Available everywhere.
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherSubClass extends SuperPublic {
public AnotherSubClass() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in subclass. Let's note different package.
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherSuperPublic {
public AnotherSuperPublic() {
SuperPublic.publicMethod(); // Available everywhere. Let's note different package.
}
}

View File

@ -3,18 +3,18 @@ package com.baeldung.extension;
import com.google.common.io.Files; import com.google.common.io.Files;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import java.util.Optional;
public class Extension { public class Extension {
//Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java //Instead of file name we can also specify full path of a file eg. /baeldung/com/demo/abc.java
public String getExtensionByApacheCommonLib(String filename) { public String getExtensionByApacheCommonLib(String filename) {
return FilenameUtils.getExtension(filename); return FilenameUtils.getExtension(filename);
} }
public String getExtensionByStringHandling(String filename) { public Optional<String> getExtensionByStringHandling(String filename) {
String fileExtension = ""; return Optional.ofNullable(filename)
if (filename.contains(".") && filename.lastIndexOf(".") != 0) { .filter(f -> f.contains("."))
fileExtension = filename.substring(filename.lastIndexOf(".") + 1); .map(f -> f.substring(filename.lastIndexOf(".") + 1));
}
return fileExtension;
} }
public String getExtensionByGuava(String filename) { public String getExtensionByGuava(String filename) {

View File

@ -1,58 +0,0 @@
package com.baeldung.linkedlist;
/**
* Implementation of a singly linked list.
*/
public class LinkedList {
private Node head;
private Node tail;
public Node head() {
return head;
}
public void add(String data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public static class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return this.data;
}
}
}

View File

@ -46,7 +46,7 @@ public class JaggedArrayUnitTest {
ByteArrayOutputStream outContent = new ByteArrayOutputStream(); ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent)); System.setOut(new PrintStream(outContent));
obj.printElements(jaggedArr); obj.printElements(jaggedArr);
assertEquals("[1, 2]\n[3, 4, 5]\n[6, 7, 8, 9]\n", outContent.toString()); assertEquals("[1, 2][3, 4, 5][6, 7, 8, 9]", outContent.toString().replace("\r", "").replace("\n", ""));
System.setOut(System.out); System.setOut(System.out);
} }

View File

@ -0,0 +1,153 @@
package com.baeldung.arrays;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ArraysUnitTest {
private String[] intro;
@Rule
public final ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
intro = new String[] { "once", "upon", "a", "time" };
}
@Test
public void whenCopyOfRange_thenAbridgedArray() {
String[] abridgement = Arrays.copyOfRange(intro, 0, 3);
assertArrayEquals(new String[] { "once", "upon", "a" }, abridgement);
assertFalse(Arrays.equals(intro, abridgement));
}
@Test
public void whenCopyOf_thenNullElement() {
String[] revised = Arrays.copyOf(intro, 3);
String[] expanded = Arrays.copyOf(intro, 5);
assertArrayEquals(Arrays.copyOfRange(intro, 0, 3), revised);
assertNull(expanded[4]);
}
@Test
public void whenFill_thenAllMatch() {
String[] stutter = new String[3];
Arrays.fill(stutter, "once");
assertTrue(Stream.of(stutter).allMatch(el -> "once".equals(el)));
}
@Test
public void whenEqualsContent_thenMatch() {
assertTrue(Arrays.equals(new String[] { "once", "upon", "a", "time" }, intro));
assertFalse(Arrays.equals(new String[] { "once", "upon", "a", null }, intro));
}
@Test
public void whenNestedArrays_thenDeepEqualsPass() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
Object[] copy = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertTrue(Arrays.deepEquals(story, copy));
assertFalse(Arrays.equals(story, copy));
}
@Test
public void whenSort_thenArraySorted() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
assertArrayEquals(new String[] { "a", "once", "time", "upon" }, sorted);
}
@Test
public void whenBinarySearch_thenFindElements() {
String[] sorted = Arrays.copyOf(intro, 4);
Arrays.sort(sorted);
int exact = Arrays.binarySearch(sorted, "time");
int caseInsensitive = Arrays.binarySearch(sorted, "TiMe", String::compareToIgnoreCase);
assertEquals("time", sorted[exact]);
assertEquals(2, exact);
assertEquals(exact, caseInsensitive);
}
@Test
public void whenNullElement_thenArraysHashCodeNotEqual() {
int beforeChange = Arrays.hashCode(intro);
int before = intro.hashCode();
intro[3] = null;
int after = intro.hashCode();
int afterChange = Arrays.hashCode(intro);
assertNotEquals(beforeChange, afterChange);
assertEquals(before, after);
}
@Test
public void whenNestedArrayNullElement_thenEqualsFailDeepHashPass() {
Object[] looping = new Object[] { intro, intro };
int deepHashBefore = Arrays.deepHashCode(looping);
int hashBefore = Arrays.hashCode(looping);
intro[3] = null;
int hashAfter = Arrays.hashCode(looping);
int deepHashAfter = Arrays.deepHashCode(looping);
assertEquals(hashAfter, hashBefore);
assertNotEquals(deepHashAfter, deepHashBefore);
}
@Test
public void whenStreamBadIndex_thenException() {
assertEquals(Arrays.stream(intro).count(), 4);
exception.expect(ArrayIndexOutOfBoundsException.class);
Arrays.stream(intro, 2, 1).count();
}
@Test
public void whenSetAllToUpper_thenAppliedToAllElements() {
String[] longAgo = new String[4];
Arrays.setAll(longAgo, i -> intro[i].toUpperCase());
assertArrayEquals(longAgo, new String[] { "ONCE", "UPON", "A", "TIME" });
}
@Test
public void whenToString_thenFormattedArrayString() {
assertEquals("[once, upon, a, time]", Arrays.toString(intro));
}
@Test
public void whenNestedArrayDeepString_thenFormattedArraysString() {
String[] end = { "the", "end" };
Object[] story = new Object[] { intro, new String[] { "chapter one", "chapter two" }, end };
assertEquals("[[once, upon, a, time], [chapter one, chapter two], [the, end]]", Arrays.deepToString(story));
}
@Test
public void whenAsList_thenImmutableArray() {
List<String> rets = Arrays.asList(intro);
assertTrue(rets.contains("upon"));
assertTrue(rets.contains("time"));
assertEquals(rets.size(), 4);
exception.expect(UnsupportedOperationException.class);
rets.add("the");
}
}

View File

@ -3,6 +3,8 @@ package com.baeldung.extension;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.util.Optional;
public class ExtensionUnitTest { public class ExtensionUnitTest {
private Extension extension = new Extension(); private Extension extension = new Extension();
@ -16,8 +18,9 @@ public class ExtensionUnitTest {
@Test @Test
public void getExtension_whenStringHandle_thenExtensionIsTrue() { public void getExtension_whenStringHandle_thenExtensionIsTrue() {
String expectedExtension = "java"; String expectedExtension = "java";
String actualExtension = extension.getExtensionByStringHandling("Demo.java"); Optional<String> actualExtension = extension.getExtensionByStringHandling("Demo.java");
Assert.assertEquals(expectedExtension, actualExtension); Assert.assertTrue(actualExtension.isPresent());
actualExtension.ifPresent(ext -> Assert.assertEquals(expectedExtension,ext));
} }
@Test @Test

View File

@ -1,58 +0,0 @@
package com.baeldung.linkedlist;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MiddleElementLookupUnitTest {
@Test
public void whenFindingMiddle_thenMiddleFound() {
String middle = MiddleElementLookup.findMiddleElement(createList(5).head());
assertEquals("3", middle);
middle = MiddleElementLookup.findMiddleElement(createList(4).head());
assertEquals("2", middle);
}
@Test
public void whenFindingMiddle1PassRecursively_thenMiddleFound() {
String middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(5).head());
assertEquals("3", middle);
middle = MiddleElementLookup.findMiddleElement1PassRecursively(createList(4).head());
assertEquals("2", middle);
}
@Test
public void whenFindingMiddle1PassIteratively_thenMiddleFound() {
String middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(5).head());
assertEquals("3", middle);
middle = MiddleElementLookup.findMiddleElement1PassIteratively(createList(4).head());
assertEquals("2", middle);
}
@Test
public void whenListEmptyOrNull_thenMiddleNull() {
String middle = MiddleElementLookup.findMiddleElement(null);
assertEquals(null, middle);
middle = MiddleElementLookup.findMiddleElement1PassIteratively(null);
assertEquals(null, middle);
middle = MiddleElementLookup.findMiddleElement1PassRecursively(null);
assertEquals(null, middle);
}
private static LinkedList createList(int n) {
LinkedList list = new LinkedList();
for (int i = 1; i <= n; i++) {
list.add(String.valueOf(i));
}
return list;
}
}

View File

@ -179,7 +179,7 @@ public class JavaMoneyUnitManualTest {
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder
.of(Locale.US) .of(Locale.US)
.set(CurrencyStyle.NAME) .set(CurrencyStyle.NAME)
.set("pattern", "00000.00 <EFBFBD>") .set("pattern", "00000.00 US Dollar")
.build()); .build());
String customFormatted = customFormat.format(oneDollar); String customFormatted = customFormat.format(oneDollar);

View File

@ -104,7 +104,7 @@ public class NashornUnitTest {
public void loadExamples() throws ScriptException { public void loadExamples() throws ScriptException {
Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)"); Object loadResult = engine.eval("load('classpath:js/script.js');" + "increment(5)");
Assert.assertEquals(6.0, loadResult); Assert.assertEquals(6, ((Double) loadResult).intValue());
Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);"); Object math = engine.eval("var math = loadWithNewGlobal('classpath:js/math_module.js');" + "math.increment(5);");

View File

@ -2,46 +2,21 @@ package com.baeldung.enums
enum class CardType(val color: String) : ICardLimit { enum class CardType(val color: String) : ICardLimit {
SILVER("gray") { SILVER("gray") {
override fun getCreditLimit(): Int { override fun getCreditLimit() = 100000
return 100000 override fun calculateCashbackPercent() = 0.25f
}
override fun calculateCashbackPercent(): Float {
return 0.25f
}
}, },
GOLD("yellow") { GOLD("yellow") {
override fun getCreditLimit(): Int { override fun getCreditLimit() = 200000
return 200000 override fun calculateCashbackPercent(): Float = 0.5f
}
override fun calculateCashbackPercent(): Float {
return 0.5f
}
}, },
PLATINUM("black") { PLATINUM("black") {
override fun getCreditLimit(): Int { override fun getCreditLimit() = 300000
return 300000 override fun calculateCashbackPercent() = 0.75f
}
override fun calculateCashbackPercent(): Float {
return 0.75f
}
}; };
companion object { companion object {
fun getCardTypeByColor(color: String): CardType? { fun getCardTypeByColor(color: String) = values().firstOrNull { it.color == color }
for (cardType in CardType.values()) { fun getCardTypeByName(name: String) = valueOf(name.toUpperCase())
if (cardType.color.equals(color)) {
return cardType;
}
}
return null
}
fun getCardTypeByName(name: String): CardType {
return CardType.valueOf(name.toUpperCase())
}
} }
abstract fun calculateCashbackPercent(): Float abstract fun calculateCashbackPercent(): Float

View File

@ -5,6 +5,7 @@ import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Bucket;
@ -19,6 +20,11 @@ public class ClusterServiceImpl implements ClusterService {
private Cluster cluster; private Cluster cluster;
private Map<String, Bucket> buckets = new ConcurrentHashMap<>(); private Map<String, Bucket> buckets = new ConcurrentHashMap<>();
@Autowired
public ClusterServiceImpl(Cluster cluster) {
this.cluster = cluster;
}
@PostConstruct @PostConstruct
private void init() { private void init() {
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create();

View File

@ -18,6 +18,7 @@ public class TutorialBucketService extends AbstractBucketService {
@Autowired @Autowired
public TutorialBucketService(ClusterService clusterService) { public TutorialBucketService(ClusterService clusterService) {
super(clusterService); super(clusterService);
openBucket();
} }
@Override @Override

View File

@ -0,0 +1,24 @@
package com.baeldung.couchbase.async.person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;
@Configuration
@ComponentScan(basePackages = {"com.baeldung.couchbase.async.service", "com.baeldung.couchbase.n1ql"})
public class PersonCrudServiceIntegrationTestConfig {
@Bean
public Cluster cluster() {
CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder()
.connectTimeout(60000)
.build();
return CouchbaseCluster.create(env, "127.0.0.1");
}
}

View File

@ -1,27 +1,31 @@
package com.baeldung.couchbase.async.person; package com.baeldung.couchbase.async.person;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import javax.annotation.PostConstruct;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.couchbase.async.AsyncIntegrationTest; import com.baeldung.couchbase.async.AsyncIntegrationTest;
import com.baeldung.couchbase.async.person.Person;
import com.baeldung.couchbase.async.person.PersonCrudService;
import com.baeldung.couchbase.async.person.PersonDocumentConverter;
import com.baeldung.couchbase.async.service.BucketService; import com.baeldung.couchbase.async.service.BucketService;
import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.JsonDocument;
public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PersonCrudServiceIntegrationTestConfig.class})
public class PersonCrudServiceLiveTest extends AsyncIntegrationTest {
@Autowired @Autowired
private PersonCrudService personService; private PersonCrudService personService;
@ -35,8 +39,8 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest {
private Bucket bucket; private Bucket bucket;
@PostConstruct @Before
private void init() { public void init() {
bucket = bucketService.getBucket(); bucket = bucketService.getBucket();
} }

View File

@ -18,7 +18,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @ContextConfiguration(classes = { AsyncIntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
public class ClusterServiceIntegrationTest extends AsyncIntegrationTest { public class ClusterServiceLiveTest extends AsyncIntegrationTest {
@Autowired @Autowired
private ClusterService couchbaseService; private ClusterService couchbaseService;

View File

@ -14,8 +14,8 @@ import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.view.ViewResult; import com.couchbase.client.java.view.ViewResult;
import com.couchbase.client.java.view.ViewRow; import com.couchbase.client.java.view.ViewRow;
public class StudentGradeServiceIntegrationTest { public class StudentGradeServiceLiveTest {
private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceIntegrationTest.class); private static final Logger logger = LoggerFactory.getLogger(StudentGradeServiceLiveTest.class);
static StudentGradeService studentGradeService; static StudentGradeService studentGradeService;
static Set<String> gradeIds = new HashSet<>(); static Set<String> gradeIds = new HashSet<>();

View File

@ -1,5 +1,23 @@
package com.baeldung.couchbase.n1ql; package com.baeldung.couchbase.n1ql;
import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
import static com.couchbase.client.java.query.Select.select;
import static com.couchbase.client.java.query.dsl.Expression.i;
import static com.couchbase.client.java.query.dsl.Expression.s;
import static com.couchbase.client.java.query.dsl.Expression.x;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster; import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.JsonDocument;
@ -10,28 +28,13 @@ import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow; import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.query.Statement; import com.couchbase.client.java.query.Statement;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import rx.Observable; import rx.Observable;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static com.baeldung.couchbase.n1ql.CodeSnippets.extractJsonResult;
import static com.couchbase.client.java.query.Select.select;
import static com.couchbase.client.java.query.dsl.Expression.*;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class }) @ContextConfiguration(classes = { IntegrationTestConfig.class })
public class N1QLIntegrationTest { public class N1QLLiveTest {
@Autowired @Autowired

View File

@ -10,7 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import com.baeldung.couchbase.spring.IntegrationTest; import com.baeldung.couchbase.spring.IntegrationTest;
public class PersonCrudServiceIntegrationTest extends IntegrationTest { public class PersonCrudServiceLiveTest extends IntegrationTest {
private static final String CLARK_KENT = "Clark Kent"; private static final String CLARK_KENT = "Clark Kent";
private static final String SMALLVILLE = "Smallville"; private static final String SMALLVILLE = "Smallville";

View File

@ -17,7 +17,7 @@ import com.couchbase.client.java.Bucket;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { IntegrationTestConfig.class }) @ContextConfiguration(classes = { IntegrationTestConfig.class })
@TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class })
public class ClusterServiceIntegrationTest extends IntegrationTest { public class ClusterServiceLiveTest extends IntegrationTest {
@Autowired @Autowired
private ClusterService couchbaseService; private ClusterService couchbaseService;

View File

@ -9,6 +9,13 @@
<name>deltaspike</name> <name>deltaspike</name>
<description>A starter Java EE 7 webapp which uses DeltaSpike</description> <description>A starter Java EE 7 webapp which uses DeltaSpike</description>
<url>http://wildfly.org</url> <url>http://wildfly.org</url>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<licenses> <licenses>
<license> <license>
<name>Apache License, Version 2.0</name> <name>Apache License, Version 2.0</name>
@ -16,12 +23,12 @@
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url> <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license> </license>
</licenses> </licenses>
<repositories>
<parent> <repository>
<groupId>com.baeldung</groupId> <id>redhat-repository-techpreview</id>
<artifactId>parent-modules</artifactId> <url>https://maven.repository.redhat.com/techpreview/all/</url>
<version>1.0.0-SNAPSHOT</version> </repository>
</parent> </repositories>
<dependencyManagement> <dependencyManagement>
<dependencies> <dependencies>
@ -47,6 +54,13 @@
<type>pom</type> <type>pom</type>
<scope>import</scope> <scope>import</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.deltaspike.distribution</groupId>
<artifactId>distributions-bom</artifactId>
<version>${deltaspike.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
@ -160,14 +174,12 @@
<dependency> <dependency>
<groupId>org.apache.deltaspike.modules</groupId> <groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-api</artifactId> <artifactId>deltaspike-data-module-api</artifactId>
<version>${deltaspike.version}</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.deltaspike.modules</groupId> <groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-impl</artifactId> <artifactId>deltaspike-data-module-impl</artifactId>
<version>${deltaspike.version}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
@ -184,6 +196,71 @@
<artifactId>querydsl-jpa</artifactId> <artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version> <version>${querydsl.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-impl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-weld</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>${weld.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>1.2.5.Final-redhat-1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<scope>provided</scope>
</dependency>
<!-- Needed for running tests (you may also use TestNG) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Others -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -226,28 +303,6 @@
</build> </build>
<profiles> <profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run
just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile> <profile>
<!-- An optional Arquillian testing profile that executes tests in your <!-- An optional Arquillian testing profile that executes tests in your
@ -273,15 +328,18 @@
resources, i.e. build is platform dependent! --> resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<querydsl.version>3.7.4</querydsl.version> <querydsl.version>3.7.4</querydsl.version>
<deltaspike.version>1.7.2</deltaspike.version> <deltaspike.version>1.8.2</deltaspike.version>
<!-- JBoss dependency versions --> <!-- JBoss dependency versions -->
<wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version> <wildfly.maven.plugin.version>1.0.2.Final</wildfly.maven.plugin.version>
<!-- Define the version of the JBoss BOMs we want to import to specify <!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. --> tested stacks. -->
<jboss.bom.version>8.2.2.Final</jboss.bom.version> <jboss.bom.version>8.2.1.Final</jboss.bom.version>
<weld.version>2.1.2.Final</weld.version>
<!-- other plugin versions --> <!-- other plugin versions -->
<war.plugin.version>2.6</war.plugin.version> <war.plugin.version>2.6</war.plugin.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version> <apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties> </properties>
</project> </project>

View File

@ -16,6 +16,9 @@
*/ */
package baeldung.controller; package baeldung.controller;
import baeldung.model.Member;
import baeldung.service.MemberRegistration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.enterprise.inject.Model; import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces; import javax.enterprise.inject.Produces;
@ -24,9 +27,6 @@ import javax.faces.context.FacesContext;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import baeldung.model.Member;
import baeldung.service.MemberRegistration;
// The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an // The @Model stereotype is a convenience mechanism to make this a request-scoped bean that has an
// EL name // EL name
// Read more about the @Model stereotype in this FAQ: // Read more about the @Model stereotype in this FAQ:
@ -34,11 +34,9 @@ import baeldung.service.MemberRegistration;
@Model @Model
public class MemberController { public class MemberController {
@Inject @Inject private FacesContext facesContext;
private FacesContext facesContext;
@Inject @Inject private MemberRegistration memberRegistration;
private MemberRegistration memberRegistration;
@Produces @Produces
@Named @Named

View File

@ -1,29 +1,18 @@
package baeldung.data; package baeldung.data;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces; import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
@ApplicationScoped
public class EntityManagerProducer { public class EntityManagerProducer {
@PersistenceUnit(unitName = "primary")
private EntityManagerFactory entityManagerFactory;
@Produces @PersistenceContext(unitName = "primary") private EntityManager entityManager;
@Default
@RequestScoped @RequestScoped
@Produces
public EntityManager create() { public EntityManager create() {
return this.entityManagerFactory.createEntityManager(); return entityManager;
} }
public void dispose(@Disposes @Default EntityManager entityManager) {
if (entityManager.isOpen()) {
entityManager.close();
}
}
} }

View File

@ -16,6 +16,8 @@
*/ */
package baeldung.data; package baeldung.data;
import baeldung.model.Member;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes; import javax.enterprise.event.Observes;
@ -25,13 +27,10 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import java.util.List; import java.util.List;
import baeldung.model.Member;
@RequestScoped @RequestScoped
public class MemberListProducer { public class MemberListProducer {
@Inject @Inject private MemberRepository memberRepository;
private MemberRepository memberRepository;
private List<Member> members; private List<Member> members;

View File

@ -18,7 +18,10 @@ package baeldung.data;
import baeldung.model.Member; import baeldung.model.Member;
import baeldung.model.QMember; import baeldung.model.QMember;
import org.apache.deltaspike.data.api.*; import org.apache.deltaspike.data.api.AbstractEntityRepository;
import org.apache.deltaspike.data.api.EntityManagerConfig;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;
import java.util.List; import java.util.List;
@ -35,6 +38,9 @@ public abstract class MemberRepository extends AbstractEntityRepository<Member,
public List<Member> findAllOrderedByNameWithQueryDSL() { public List<Member> findAllOrderedByNameWithQueryDSL() {
final QMember member = QMember.member; final QMember member = QMember.member;
return jpaQuery().from(member).orderBy(member.email.asc()).list(member); return jpaQuery()
.from(member)
.orderBy(member.email.asc())
.list(member);
} }
} }

View File

@ -8,8 +8,7 @@ import javax.inject.Inject;
public class QueryDslRepositoryExtension<E> implements QueryDslSupport, DelegateQueryHandler { public class QueryDslRepositoryExtension<E> implements QueryDslSupport, DelegateQueryHandler {
@Inject @Inject private QueryInvocationContext context;
private QueryInvocationContext context;
@Override @Override
public JPAQuery jpaQuery() { public JPAQuery jpaQuery() {

View File

@ -2,29 +2,20 @@ package baeldung.data;
import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped; import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces; import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
@ApplicationScoped @ApplicationScoped
public class SecondaryEntityManagerProducer { public class SecondaryEntityManagerProducer {
@PersistenceUnit(unitName = "secondary")
private EntityManagerFactory entityManagerFactory; @PersistenceContext(unitName = "secondary") private EntityManager entityManager;
@Produces @Produces
@Default
@RequestScoped @RequestScoped
@SecondaryPersistenceUnit @SecondaryPersistenceUnit
public EntityManager create() { public EntityManager create() {
return this.entityManagerFactory.createEntityManager(); return entityManager;
} }
public void dispose(@Disposes @Default EntityManager entityManager) {
if (entityManager.isOpen()) {
entityManager.close();
}
}
} }

View File

@ -0,0 +1,45 @@
package baeldung.data;
import baeldung.model.User;
import org.apache.deltaspike.data.api.FirstResult;
import org.apache.deltaspike.data.api.MaxResults;
import org.apache.deltaspike.data.api.Repository;
import java.util.Collection;
import java.util.List;
/**
* Created by adam.
*/
@Repository(forEntity = User.class)
public abstract class SimpleUserRepository {
public abstract Collection<User> findAll();
public abstract Collection<User> findAllOrderByFirstNameAsc(@FirstResult int start, @MaxResults int size);
public abstract Collection<User> findTop2OrderByFirstNameAsc();
public abstract Collection<User> findFirst2OrderByFirstNameAsc();
public abstract List<User> findAllOrderByFirstNameAsc();
public abstract List<User> findAllOrderByFirstNameAscLastNameDesc();
public abstract User findById(Long id);
public abstract Collection<User> findByFirstName(String firstName);
public abstract User findAnyByLastName(String lastName);
public abstract Collection<User> findAnyByFirstName(String firstName);
public abstract Collection<User> findByFirstNameAndLastName(String firstName, String lastName);
public abstract Collection<User> findByFirstNameOrLastName(String firstName, String lastName);
public abstract Collection<User> findByAddress_city(String city);
public abstract int count();
public abstract void remove(User user);
}

View File

@ -0,0 +1,31 @@
package baeldung.data;
import baeldung.model.User;
import org.apache.deltaspike.data.api.AbstractEntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;
import java.util.Collection;
import java.util.List;
/**
* Created by adam.
*/
@Repository
public abstract class UserRepository extends AbstractEntityRepository<User, Long> {
public List<User> findByFirstName(String firstName) {
return typedQuery("select u from User u where u.firstName = ?1")
.setParameter(1, firstName)
.getResultList();
}
public abstract List<User> findByLastName(String lastName);
@Query("select u from User u where u.firstName = ?1")
public abstract Collection<User> findUsersWithFirstName(String firstName);
@Query(value = "select * from User where firstName = ?1", isNative = true)
public abstract Collection<User> findUsersWithFirstNameNative(String firstName);
}

View File

@ -0,0 +1,51 @@
package baeldung.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
/**
* Created by adam.
*/
@Entity
public class Address {
@Id
@GeneratedValue
private Long id;
private String street;
private String city;
private String postCode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
}

View File

@ -16,22 +16,16 @@
*/ */
package baeldung.model; package baeldung.model;
import java.io.Serializable; import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column; import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Digits; import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern; import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
@SuppressWarnings("serial") @SuppressWarnings("serial")
@Entity @Entity

View File

@ -0,0 +1,52 @@
package baeldung.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
* Created by adam.
*/
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
@OneToOne private Address address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}

View File

@ -0,0 +1,5 @@
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
</beans>

View File

@ -0,0 +1,21 @@
package baeldung;
import javax.enterprise.inject.Produces;
import javax.validation.Validation;
import javax.validation.Validator;
/**
* Created by adam.
*/
public class ValidatorProducer {
@Produces
public Validator createValidator() {
return Validation
.byDefaultProvider()
.configure()
.buildValidatorFactory()
.getValidator();
}
}

View File

@ -0,0 +1,23 @@
package baeldung.data;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.Specializes;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
/**
* Created by adam.
*/
public class TestEntityManagerProducer extends EntityManagerProducer {
@ApplicationScoped
@Produces
@Specializes
public EntityManager create() {
return Persistence
.createEntityManagerFactory("pu-test")
.createEntityManager();
}
}

View File

@ -16,19 +16,12 @@
*/ */
package baeldung.test; package baeldung.test;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.util.logging.Logger;
import javax.inject.Inject;
import baeldung.data.*; import baeldung.data.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import baeldung.model.Member; import baeldung.model.Member;
import baeldung.service.MemberRegistration; import baeldung.service.MemberRegistration;
import baeldung.util.Resources; import baeldung.util.Resources;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.EmptyAsset;
@ -37,24 +30,39 @@ import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.io.File;
import java.util.logging.Logger;
import static org.junit.Assert.assertNotNull;
@RunWith(Arquillian.class) @RunWith(Arquillian.class)
public class MemberRegistrationIntegrationTest { public class MemberRegistrationIntegrationTest {
@Deployment @Deployment
public static Archive<?> createTestArchive() { public static Archive<?> createTestArchive() {
File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); File[] files = Maven
.resolver()
.loadPomFromFile("pom.xml")
.importRuntimeDependencies()
.resolve()
.withTransitivity()
.asFile();
return ShrinkWrap.create(WebArchive.class, "test.war") return ShrinkWrap
.addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, .create(WebArchive.class, "test.war")
SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, SecondaryEntityManagerProducer.class,
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") SecondaryEntityManagerResolver.class)
.addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
.addAsResource("META-INF/apache-deltaspike.properties")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource("test-ds.xml")
.addAsWebInfResource("test-secondary-ds.xml")
.addAsLibraries(files);
} }
@Inject @Inject MemberRegistration memberRegistration;
MemberRegistration memberRegistration;
@Inject @Inject Logger log;
Logger log;
@Test @Test
public void testRegister() throws Exception { public void testRegister() throws Exception {

View File

@ -0,0 +1,133 @@
package baeldung.test;
import baeldung.data.SimpleUserRepository;
import baeldung.model.User;
import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
@RunWith(CdiTestRunner.class)
public class SimpleUserRepositoryUnitTest {
@Inject private EntityManager entityManager;
@Inject private SimpleUserRepository simpleUserRepository;
@Test
public void givenFourUsersWhenFindAllShouldReturnFourUsers() {
assertThat(simpleUserRepository
.findAll()
.size(), equalTo(4));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() {
assertThat(simpleUserRepository
.findByFirstName("Adam")
.size(), equalTo(2));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenFindAnyByFirstNameShouldReturnTwoUsers() {
assertThat(simpleUserRepository
.findAnyByFirstName("Adam")
.size(), equalTo(2));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenCountByFirstNameShouldReturnSizeTwo() {
assertThat(simpleUserRepository.count(), equalTo(4));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenRemoveByFirstNameShouldReturnSizeTwo() {
simpleUserRepository.remove(entityManager.merge(simpleUserRepository.findById(1L)));
assertThat(entityManager.find(User.class, 1L), nullValue());
}
@Test
public void givenOneUserWithSpecifiedFirstNameAndLastNameWhenFindByFirstNameAndLastNameShouldReturnOneUser() {
assertThat(simpleUserRepository
.findByFirstNameAndLastName("Adam", "LastName1")
.size(), equalTo(1));
assertThat(simpleUserRepository
.findByFirstNameAndLastName("David", "LastName2")
.size(), equalTo(1));
}
@Test
public void givenOneUserWithSpecifiedLastNameWhenFindAnyByLastNameShouldReturnOneUser() {
assertThat(simpleUserRepository.findAnyByLastName("LastName1"), notNullValue());
}
@Test
public void givenOneUserWithSpecifiedAddressCityWhenFindByCityShouldReturnOneUser() {
assertThat(simpleUserRepository
.findByAddress_city("London")
.size(), equalTo(1));
}
@Test
public void givenUsersWithSpecifiedFirstOrLastNameWhenFindByFirstNameOrLastNameShouldReturnTwoUsers() {
assertThat(simpleUserRepository
.findByFirstNameOrLastName("David", "LastName1")
.size(), equalTo(2));
}
@Test
public void givenUsersWhenFindAllOrderByFirstNameAscShouldReturnFirstAdamLastPeter() {
List<User> users = simpleUserRepository.findAllOrderByFirstNameAsc();
assertThat(users
.get(0)
.getFirstName(), equalTo("Adam"));
assertThat(users
.get(3)
.getFirstName(), equalTo("Peter"));
}
@Test
public void givenUsersWhenFindAllOrderByFirstNameAscLastNameDescShouldReturnFirstAdamLastPeter() {
List<User> users = simpleUserRepository.findAllOrderByFirstNameAscLastNameDesc();
assertThat(users
.get(0)
.getFirstName(), equalTo("Adam"));
assertThat(users
.get(3)
.getFirstName(), equalTo("Peter"));
}
@Test
public void givenUsersWhenFindTop2ShouldReturnTwoUsers() {
assertThat(simpleUserRepository
.findTop2OrderByFirstNameAsc()
.size(), equalTo(2));
}
@Test
public void givenUsersWhenFindFirst2ShouldReturnTwoUsers() {
assertThat(simpleUserRepository
.findFirst2OrderByFirstNameAsc()
.size(), equalTo(2));
}
@Test
public void givenPagesWithSizeTwoWhenFindAllOrderByFirstNameAscShouldReturnTwoPages() {
assertThat(simpleUserRepository
.findAllOrderByFirstNameAsc(0, 2)
.size(), equalTo(2));
assertThat(simpleUserRepository
.findAllOrderByFirstNameAsc(2, 4)
.size(), equalTo(2));
}
}

View File

@ -0,0 +1,55 @@
package baeldung.test;
import baeldung.data.UserRepository;
import org.apache.deltaspike.testcontrol.api.junit.CdiTestRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
/**
* Created by adam.
*/
@RunWith(CdiTestRunner.class)
public class UserRepositoryUnitTest {
@Inject private UserRepository userRepository;
@Test
public void givenFourUsersWhenFindAllShouldReturnFourUsers() {
assertThat(userRepository
.findAll()
.size(), equalTo(4));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenFindByFirstNameShouldReturnTwoUsers() {
assertThat(userRepository
.findByFirstName("Adam")
.size(), equalTo(2));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameShouldReturnTwoUsers() {
assertThat(userRepository
.findUsersWithFirstName("Adam")
.size(), equalTo(2));
}
@Test
public void givenTwoUsersWithSpecifiedNameWhenFindUsersWithFirstNameNativeShouldReturnTwoUsers() {
assertThat(userRepository
.findUsersWithFirstNameNative("Adam")
.size(), equalTo(2));
}
@Test
public void givenTwoUsersWithSpecifiedLastNameWhenFindByLastNameShouldReturnTwoUsers() {
assertThat(userRepository
.findByLastName("LastName3")
.size(), equalTo(2));
}
}

View File

@ -1 +1,3 @@
globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy globalAlternatives.org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy=org.apache.deltaspike.jpa.impl.transaction.BeanManagedUserTransactionStrategy
org.apache.deltaspike.ProjectStage=UnitTest
deltaspike.testcontrol.stop_container=false

View File

@ -0,0 +1,18 @@
<!--<?xml version="1.0" encoding="UTF-8"?>-->
<!--&lt;!&ndash; JBoss, Home of Professional Open Source Copyright 2013, Red Hat, Inc. -->
<!--and/or its affiliates, and individual contributors by the @authors tag. See -->
<!--the copyright.txt in the distribution for a full listing of individual contributors. -->
<!--Licensed under the Apache License, Version 2.0 (the "License"); you may not -->
<!--use this file except in compliance with the License. You may obtain a copy -->
<!--of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required -->
<!--by applicable law or agreed to in writing, software distributed under the -->
<!--License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS -->
<!--OF ANY KIND, either express or implied. See the License for the specific -->
<!--language governing permissions and limitations under the License. &ndash;&gt;-->
<!--&lt;!&ndash; Marker file indicating CDI should be enabled &ndash;&gt;-->
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
</beans>

View File

@ -11,6 +11,7 @@
<property name="hibernate.show_sql" value="false" /> <property name="hibernate.show_sql" value="false" />
</properties> </properties>
</persistence-unit> </persistence-unit>
<persistence-unit name="secondary"> <persistence-unit name="secondary">
<jta-data-source>java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS</jta-data-source> <jta-data-source>java:jboss/datasources/baeldung-jee7-seedTestSecondaryDS</jta-data-source>
<properties> <properties>
@ -18,4 +19,23 @@
<property name="hibernate.show_sql" value="false" /> <property name="hibernate.show_sql" value="false" />
</properties> </properties>
</persistence-unit> </persistence-unit>
<persistence-unit name="pu-test" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<!-- add classes -->
<class>baeldung.model.User</class>
<class>baeldung.model.Address</class>
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence> </persistence>

View File

@ -28,12 +28,4 @@
<!-- Force the use of the Servlet 3.0 protocol with all containers, as it is the most mature --> <!-- Force the use of the Servlet 3.0 protocol with all containers, as it is the most mature -->
<defaultProtocol type="Servlet 3.0" /> <defaultProtocol type="Servlet 3.0" />
<!-- Example configuration for a remote WildFly instance -->
<container qualifier="jboss" default="true">
<!-- By default, arquillian will use the JBOSS_HOME environment variable. Alternatively, the configuration below can be uncommented. -->
<configuration>
<property name="jbossHome">target\wildfly-run\wildfly-10.0.0.Final</property>
</configuration>
</container>
</arquillian> </arquillian>

View File

@ -0,0 +1,6 @@
INSERT INTO ADDRESS(ID, STREET, CITY, POSTCODE) VALUES (1, 'Oxford', 'London', 'N121');
INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (1, 'Adam', 'LastName1', null);
INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (2, 'David', 'LastName2', null);
INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (3, 'Adam', 'LastName3', null);
INSERT INTO USER(ID, FIRSTNAME, LASTNAME, ADDRESS_ID) VALUES (4, 'Peter', 'LastName3', 1);

View File

@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>ejb-client</artifactId> <artifactId>ejb-client</artifactId>
<name>EJB3 Client Maven</name>
<description>EJB3 Client Maven</description> <description>EJB3 Client Maven</description>
<parent> <parent>

View File

@ -3,3 +3,4 @@
### Relevant Articles: ### Relevant Articles:
- [Introduction to EthereumJ](http://www.baeldung.com/ethereumj) - [Introduction to EthereumJ](http://www.baeldung.com/ethereumj)
- [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity) - [Creating and Deploying Smart Contracts with Solidity](http://www.baeldung.com/smart-contracts-ethereum-solidity)
- [Lightweight Ethereum Clients Using Web3j](http://www.baeldung.com/web3j)

View File

@ -10,10 +10,10 @@
<name>ethereumj</name> <name>ethereumj</name>
<parent> <parent>
<artifactId>parent-boot-5</artifactId> <artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath> <relativePath>../parent-boot-1</relativePath>
</parent> </parent>
<repositories> <repositories>

View File

@ -8,10 +8,10 @@
<name>flips</name> <name>flips</name>
<parent> <parent>
<artifactId>parent-boot-5</artifactId> <artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath> <relativePath>../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -8,10 +8,10 @@
<description>Flyway Callbacks Demo</description> <description>Flyway Callbacks Demo</description>
<parent> <parent>
<artifactId>parent-boot-5</artifactId> <artifactId>parent-boot-1</artifactId>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-5</relativePath> <relativePath>../parent-boot-1</relativePath>
</parent> </parent>
<dependencies> <dependencies>

View File

@ -5,8 +5,6 @@
<artifactId>grpc-demo</artifactId> <artifactId>grpc-demo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>grpc-demo</name>
<url>http://maven.apache.org</url>
<parent> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>

View File

@ -6,3 +6,4 @@
### Relevant Articles: ### Relevant Articles:
- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide) - [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
- [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson) - [Jackson vs Gson](http://www.baeldung.com/jackson-vs-gson)
- [Exclude Fields from Serialization in Gson](http://www.baeldung.com/gson-exclude-fields-serialization)

View File

@ -1,3 +1,2 @@
Manifest-Version: 1.0 Manifest-Version: 1.0
Class-Path: Class-Path:

View File

@ -0,0 +1,16 @@
# Alpine Linux with OpenJDK JRE
FROM openjdk:8-jre-alpine
RUN apk add --no-cache bash
# copy fat WAR
COPY spring-boot-app-0.0.1-SNAPSHOT.war /app.war
# copy fat WAR
COPY logback.xml /logback.xml
COPY run.sh /run.sh
# runs application
#CMD ["/usr/bin/java", "-jar", "-Dspring.profiles.active=default", "-Dlogging.config=/logback.xml", "/app.war"]
ENTRYPOINT ["/run.sh"]

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>/var/log/Application/application.log</file>
<append>true</append>
<encoder>
<pattern>%-7d{yyyy-MM-dd HH:mm:ss:SSS} %m%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>

View File

@ -0,0 +1,4 @@
#!/bin/sh
java -Dspring.profiles.active=$1 -Dlogging.config=/logback.xml -jar /app.war

View File

@ -51,6 +51,22 @@
<warSourceDirectory>WebContent</warSourceDirectory> <warSourceDirectory>WebContent</warSourceDirectory>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<mainClass>com.stackify.Application</mainClass>
<outputDirectory>${project.basedir}/docker</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -27,28 +27,6 @@
</dependency> </dependency>
</dependencies> </dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

View File

@ -45,28 +45,6 @@
</dependency> </dependency>
</dependencies> </dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"
>
<http use-expressions="true">
<intercept-url pattern="/login*" access="permitAll"/>
<intercept-url pattern="/logout*" access="permitAll"/>
<intercept-url pattern="/home*" access="permitAll"/>
<intercept-url pattern="/files/**" access="permitAll"/>
<intercept-url pattern="/resources/**" access="permitAll"/>
<intercept-url pattern="/js/**" access="permitAll"/>
<intercept-url pattern="/other-files/**" access="permitAll"/>
<intercept-url pattern="/invalidSession*" access="isAnonymous()"/>
<intercept-url pattern="/**" access="isAuthenticated()"/>
<form-login login-page='/login.html' authentication-failure-url="/login.html?error=true" authentication-success-handler-ref="myAuthenticationSuccessHandler"
default-target-url="home.html"/>
<session-management invalid-session-url="/invalidSession.html" session-fixation-protection="none"/>
<logout invalidate-session="false" logout-success-url="/logout.html?logSucc=true" delete-cookies="JSESSIONID"/>
</http>
<!-- for XML static resource confguration- comment out for java based config -->
<!-- -<mvc:resources mapping="/resources/**" location="/resources/" /> -->
<beans:bean id="myAuthenticationSuccessHandler" class="org.baeldung.security.MySimpleUrlAuthenticationSuccessHandler"/>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER"/>
<user name="admin1" password="admin1Pass" authorities="ROLE_ADMIN"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
</beans>

View File

@ -11,4 +11,5 @@
- [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob) - [Mapping LOB Data in Hibernate](http://www.baeldung.com/hibernate-lob)
- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking) - [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
- [Bootstrapping JPA Programmatically in Java](http://www.baeldung.com/java-bootstrap-jpa)

View File

@ -1,5 +1,7 @@
package com.baeldung.hibernate; package com.baeldung.hibernate;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
import com.baeldung.hibernate.pessimisticlocking.Individual; import com.baeldung.hibernate.pessimisticlocking.Individual;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee; import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
@ -70,6 +72,8 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(PessimisticLockingCourse.class); metadataSources.addAnnotatedClass(PessimisticLockingCourse.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Customer.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.pessimisticlocking.Address.class);
metadataSources.addAnnotatedClass(OptimisticLockingCourse.class);
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
Metadata metadata = metadataSources.buildMetadata(); Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder() return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,34 @@
package com.baeldung.hibernate.jpabootstrap.application;
import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
import com.baeldung.hibernate.jpabootstrap.entities.User;
import javax.persistence.EntityManager;
public class Application {
public static void main(String[] args) {
EntityManager entityManager = getJpaEntityManager();
User user = entityManager.find(User.class, 1);
System.out.println(user);
entityManager.getTransaction().begin();
user.setName("John");
user.setEmail("john@domain.com");
entityManager.merge(user);
entityManager.getTransaction().commit();
entityManager.getTransaction().begin();
entityManager.persist(new User("Monica", "monica@domain.com"));
entityManager.getTransaction().commit();
// additional CRUD operations
}
private static class EntityManagerHolder {
private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
new Class[]{User.class}).getEntityManager();
}
public static EntityManager getJpaEntityManager() {
return EntityManagerHolder.ENTITY_MANAGER;
}
}

View File

@ -0,0 +1,131 @@
package com.baeldung.hibernate.jpabootstrap.config;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.jpa.HibernatePersistenceProvider;
public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
public static final String JPA_VERSION = "2.1";
private final String persistenceUnitName;
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
private final List<String> managedClassNames;
private final List<String> mappingFileNames = new ArrayList<>();
private final Properties properties;
private DataSource jtaDataSource;
private DataSource nonjtaDataSource;
private final List<ClassTransformer> transformers = new ArrayList<>();
public HibernatePersistenceUnitInfo(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
this.persistenceUnitName = persistenceUnitName;
this.managedClassNames = managedClassNames;
this.properties = properties;
}
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
public HibernatePersistenceUnitInfo setJtaDataSource(DataSource jtaDataSource) {
this.jtaDataSource = jtaDataSource;
this.nonjtaDataSource = null;
transactionType = PersistenceUnitTransactionType.JTA;
return this;
}
@Override
public DataSource getJtaDataSource() {
return jtaDataSource;
}
public HibernatePersistenceUnitInfo setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonjtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public DataSource getNonJtaDataSource() {
return nonjtaDataSource;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
transformers.add(transformer);
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
}

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