diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml new file mode 100644 index 0000000000..6d07394b87 --- /dev/null +++ b/annotations/annotation-processing/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + com.baeldung + 1.0.0-SNAPSHOT + annotations + ../ + + + annotation-processing + + + 1.0-rc2 + 3.5.1 + + + + + + com.google.auto.service + auto-service + ${auto-service.version} + provided + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java new file mode 100644 index 0000000000..0883e108e7 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java @@ -0,0 +1,132 @@ +package com.baeldung.annotation.processor; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.processing.*; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.ExecutableType; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import com.google.auto.service.AutoService; + +@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty") +@SupportedSourceVersion(SourceVersion.RELEASE_8) +@AutoService(Processor.class) +public class BuilderProcessor extends AbstractProcessor { + + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { + for (TypeElement annotation : annotations) { + + Set annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); + + Map> annotatedMethods = annotatedElements.stream() + .collect(Collectors.partitioningBy(element -> + ((ExecutableType) element.asType()).getParameterTypes().size() == 1 + && element.getSimpleName().toString().startsWith("set"))); + + List setters = annotatedMethods.get(true); + List otherMethods = annotatedMethods.get(false); + + otherMethods.forEach(element -> + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "@BuilderProperty must be applied to a setXxx method with a single argument", element)); + + if (setters.isEmpty()) { + continue; + } + + String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); + + Map setterMap = setters.stream().collect(Collectors.toMap( + setter -> setter.getSimpleName().toString(), + setter -> ((ExecutableType) setter.asType()) + .getParameterTypes().get(0).toString() + )); + + try { + writeBuilderFile(className, setterMap); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + return true; + } + + private void writeBuilderFile(String className, Map setterMap) throws IOException { + + String packageName = null; + int lastDot = className.lastIndexOf('.'); + if (lastDot > 0) { + packageName = className.substring(0, lastDot); + } + + String simpleClassName = className.substring(lastDot + 1); + String builderClassName = className + "Builder"; + String builderSimpleClassName = builderClassName.substring(lastDot + 1); + + JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName); + try (PrintWriter out = new PrintWriter(builderFile.openWriter())) { + + if (packageName != null) { + out.print("package "); + out.print(packageName); + out.println(";"); + out.println(); + } + + out.print("public class "); + out.print(builderSimpleClassName); + out.println(" {"); + out.println(); + + out.print(" private "); + out.print(simpleClassName); + out.print(" object = new "); + out.print(simpleClassName); + out.println("();"); + out.println(); + + out.print(" public "); + out.print(simpleClassName); + out.println(" build() {"); + out.println(" return object;"); + out.println(" }"); + out.println(); + + setterMap.entrySet().forEach(setter -> { + String methodName = setter.getKey(); + String argumentType = setter.getValue(); + + out.print(" public "); + out.print(builderSimpleClassName); + out.print(" "); + out.print(methodName); + + out.print("("); + + out.print(argumentType); + out.println(" value) {"); + out.print(" object."); + out.print(methodName); + out.println("(value);"); + out.println(" return this;"); + out.println(" }"); + out.println(); + }); + + out.println("}"); + + } + } + +} diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java new file mode 100644 index 0000000000..84fcc73850 --- /dev/null +++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java @@ -0,0 +1,8 @@ +package com.baeldung.annotation.processor; + +import java.lang.annotation.*; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.SOURCE) +public @interface BuilderProperty { +} diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml new file mode 100644 index 0000000000..f76f691f93 --- /dev/null +++ b/annotations/annotation-user/pom.xml @@ -0,0 +1,51 @@ + + + 4.0.0 + + + annotations + com.baeldung + 1.0.0-SNAPSHOT + ../ + + + annotation-user + + + + + com.baeldung + annotation-processing + ${project.parent.version} + + + + junit + junit + 4.12 + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + + \ No newline at end of file diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java new file mode 100644 index 0000000000..23787ba4f4 --- /dev/null +++ b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java @@ -0,0 +1,29 @@ +package com.baeldung.annotation; + +import com.baeldung.annotation.processor.BuilderProperty; + +public class Person { + + private int age; + + private String name; + + public int getAge() { + return age; + } + + @BuilderProperty + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + @BuilderProperty + public void setName(String name) { + this.name = name; + } + +} diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java new file mode 100644 index 0000000000..72f9ac8bc7 --- /dev/null +++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java @@ -0,0 +1,22 @@ +package com.baeldung.annotation; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class PersonBuilderTest { + + @Test + public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { + + Person person = new PersonBuilder() + .setAge(25) + .setName("John") + .build(); + + assertEquals(25, person.getAge()); + assertEquals("John", person.getName()); + + } + +} diff --git a/spring-cloud/spring-cloud-integration/pom.xml b/annotations/pom.xml similarity index 55% rename from spring-cloud/spring-cloud-integration/pom.xml rename to annotations/pom.xml index 1d56995009..f691674cf1 100644 --- a/spring-cloud/spring-cloud-integration/pom.xml +++ b/annotations/pom.xml @@ -2,14 +2,19 @@ + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + 4.0.0 - com.baeldung.spring.cloud - spring-cloud-integration - 1.0.0-SNAPSHOT + annotations pom - part-1 + annotation-processing + annotation-user + \ No newline at end of file diff --git a/annotations/readme.md b/annotations/readme.md new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/annotations/readme.md @@ -0,0 +1 @@ + diff --git a/core-java-8/README.md b/core-java-8/README.md index e6bac2a4c9..c130e6bd41 100644 --- a/core-java-8/README.md +++ b/core-java-8/README.md @@ -11,4 +11,14 @@ - [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips) - [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator) - [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams) -- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) \ No newline at end of file +- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer) +- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string) +- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces) +- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture) +- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava) +- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors) +- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams) +- [New Features in Java 8](http://www.baeldung.com/java-8-new-features) +- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction) +- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join) diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index 63df0e1b95..566eb4e43a 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,9 +1,10 @@ 4.0.0 + com.baeldung + 1.0.0-SNAPSHOT core-java8 - 0.1-SNAPSHOT core-java8 @@ -111,6 +112,9 @@ + + UTF-8 + 1.7.13 1.0.13 diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java-8/src/main/resources/fileTest.txt new file mode 100644 index 0000000000..ce4bea208b --- /dev/null +++ b/core-java-8/src/main/resources/fileTest.txt @@ -0,0 +1 @@ +Hello World from fileTest.txt!!! \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java index 8143da5794..1918c801dc 100644 --- a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java +++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java @@ -1,17 +1,71 @@ package com.baeldung; +import com.google.common.collect.Lists; import org.junit.Test; -import java.util.Arrays; -import java.util.List; -import java.util.Random; +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; public class RandomListElementTest { @Test - public void givenList_whenRandomNumberChosen_shouldReturnARandomElement() { - List givenList = Arrays.asList(1, 2, 3); + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() { + List givenList = Lists.newArrayList(1, 2, 3); Random rand = new Random(); + givenList.get(rand.nextInt(givenList.size())); } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() { + List givenList = Lists.newArrayList(1, 2, 3); + + givenList.get((int)(Math.random() * givenList.size())); + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + } + } + + @Test + public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() { + Random rand = new Random(); + List givenList = Lists.newArrayList("one", "two", "three", "four"); + + int numberOfElements = 2; + + for (int i = 0; i < numberOfElements; i++) { + int randomIndex = rand.nextInt(givenList.size()); + givenList.get(randomIndex); + givenList.remove(randomIndex); + } + } + + @Test + public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + Collections.shuffle(givenList); + + int randomSeriesLength = 3; + + givenList.subList(0, randomSeriesLength - 1); + } + + @Test + public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() { + List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6); + int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size(); + + givenList.get(randomIndex); + } + } diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java new file mode 100644 index 0000000000..3752fc5b7f --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java @@ -0,0 +1,123 @@ +package com.baeldung.file; + +import org.apache.commons.io.FileUtils; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Test; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +public class FileOperationsTest { + + @Test + public void givenFileName_whenUsingClassloader_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + InputStream inputStream = new FileInputStream(file); + String data = readFromInputStream(inputStream); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Class clazz = FileOperationsTest.class; + InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFileName_whenUsingJarFile_thenFileData() throws IOException { + String expectedData = "BSD License"; + + Class clazz = Matchers.class; + InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt"); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenURLName_whenUsingURL_thenFileData() throws IOException { + String expectedData = "Baeldung"; + + URL urlObject = new URL("http://www.baeldung.com/"); + + URLConnection urlConnection = urlObject.openConnection(); + + InputStream inputStream = urlConnection.getInputStream(); + String data = readFromInputStream(inputStream); + + Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData)); + } + + @Test + public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException { + String expectedData = "Hello World from fileTest.txt!!!"; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("fileTest.txt").getFile()); + String data = FileUtils.readFileToString(file); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + byte[] fileBytes = Files.readAllBytes(path); + String data = new String(fileBytes); + + Assert.assertEquals(expectedData, data.trim()); + } + + @Test + public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException { + String expectedData = "Hello World from fileTest.txt!!!"; + + Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI()); + + StringBuilder data = new StringBuilder(); + Stream lines = Files.lines(path); + lines.forEach(line -> data.append(line).append("\n")); + + Assert.assertEquals(expectedData, data.toString().trim()); + } + + private String readFromInputStream(InputStream inputStream) throws IOException { + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + StringBuilder resultStringBuilder = new StringBuilder(); + String line; + while ((line = bufferedReader.readLine()) != null) { + resultStringBuilder.append(line); + resultStringBuilder.append("\n"); + } + bufferedReader.close(); + inputStreamReader.close(); + inputStream.close(); + return resultStringBuilder.toString(); + } +} \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index efd548a4b1..f2e7452137 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -21,7 +21,7 @@ public class JavaFolderSizeTest { @Before public void init() { final String separator = File.separator; - path = "src" + separator + "test" + separator + "resources"; + path = String.format("src%stest%sresources", separator, separator); } @Test @@ -79,7 +79,9 @@ public class JavaFolderSizeTest { final File folder = new File(path); final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder); - final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum(); + final long size = StreamSupport.stream(files.spliterator(), false) + .filter(File::isFile) + .mapToLong(File::length).sum(); assertEquals(expectedSize, size); } @@ -101,13 +103,11 @@ public class JavaFolderSizeTest { long length = 0; final File[] files = folder.listFiles(); - final int count = files.length; - - for (int i = 0; i < count; i++) { - if (files[i].isFile()) { - length += files[i].length(); + for (File file : files) { + if (file.isFile()) { + length += file.length(); } else { - length += getFolderSize(files[i]); + length += getFolderSize(file); } } return length; diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java index 06d9394a5e..599d5a5894 100644 --- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java +++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java @@ -1,47 +1,57 @@ package com.baeldung.util; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import java.time.Clock; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; +import java.time.ZoneId; import java.time.temporal.ChronoField; -import java.util.Calendar; -import java.util.GregorianCalendar; +import org.junit.BeforeClass; import org.junit.Test; +import org.mockito.Mockito; public class CurrentDateTimeTest { + private static Clock clock; + + @BeforeClass + public static void setup() { + final Instant currentTime = Instant.parse("2016-10-09T15:10:30.00Z"); + + clock = Mockito.mock(Clock.class); + when(clock.instant()).thenAnswer((invocation) -> currentTime); + when(clock.getZone()).thenAnswer((invocation) -> ZoneId.of("UTC")); + } + @Test public void shouldReturnCurrentDate() { - final LocalDate now = LocalDate.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalDate now = LocalDate.now(clock); - assertEquals("10-10-2010".length(), now.toString().length()); - assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH)); - assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1); - assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR)); + assertEquals(9, now.get(ChronoField.DAY_OF_MONTH)); + assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR)); + assertEquals(2016, now.get(ChronoField.YEAR)); } @Test public void shouldReturnCurrentTime() { - final LocalTime now = LocalTime.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final LocalTime now = LocalTime.now(clock); - assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY)); - assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR)); - assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE)); + assertEquals(15, now.get(ChronoField.HOUR_OF_DAY)); + assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR)); + assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE)); } @Test public void shouldReturnCurrentTimestamp() { - final Instant now = Instant.now(); - final Calendar calendar = GregorianCalendar.getInstance(); + final Instant now = Instant.now(clock); - assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond()); + assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond()); } } diff --git a/core-java-8/src/test/resources/.gitignore b/core-java-8/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/core-java-8/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt new file mode 100644 index 0000000000..652d70630f --- /dev/null +++ b/core-java-8/src/test/resources/test.txt @@ -0,0 +1 @@ +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat. \ No newline at end of file diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java index 102ceda18f..b0684a94f8 100644 --- a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java +++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java @@ -42,6 +42,19 @@ public class Java9OptionalsStreamTest { assertEquals("bar", filteredList.get(1)); } + @Test + public void filterOutPresentOptionalsWithFlatMap2() { + assertEquals(4, listOfOptionals.size()); + + List filteredList = listOfOptionals.stream() + .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) + .collect(Collectors.toList()); + assertEquals(2, filteredList.size()); + + assertEquals("foo", filteredList.get(0)); + assertEquals("bar", filteredList.get(1)); + } + @Test public void filterOutPresentOptionalsWithJava9() { assertEquals(4, listOfOptionals.size()); diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD @@ -0,0 +1 @@ + diff --git a/core-java/pom.xml b/core-java/pom.xml index bc533607e7..bce97d1148 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -123,6 +123,12 @@ ${mockito.version} test + + + commons-codec + commons-codec + 1.10 + diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java new file mode 100644 index 0000000000..414401eb85 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/java/regex/RegexTest.java @@ -0,0 +1,502 @@ +package com.baeldung.java.regex; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class RegexTest { + private static Pattern pattern; + private static Matcher matcher; + + @Test + public void givenText_whenSimpleRegexMatches_thenCorrect() { + Pattern pattern = Pattern.compile("foo"); + Matcher matcher = pattern.matcher("foo"); + assertTrue(matcher.find()); + } + + @Test + public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() { + Pattern pattern = Pattern.compile("foo"); + Matcher matcher = pattern.matcher("foofoo"); + int matches = 0; + while (matcher.find()) + matches++; + assertEquals(matches, 2); + + } + + @Test + public void givenText_whenMatchesWithDotMetach_thenCorrect() { + int matches = runTest(".", "foo"); + assertTrue(matches > 0); + } + + @Test + public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() { + int matches = runTest("foo.", "foofoo"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenORSet_whenMatchesAny_thenCorrect() { + int matches = runTest("[abc]", "b"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenORSet_whenMatchesAnyAndAll_thenCorrect() { + int matches = runTest("[abc]", "cab"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenORSet_whenMatchesAllCombinations_thenCorrect() { + int matches = runTest("[bcr]at", "bat cat rat"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenNORSet_whenMatchesNon_thenCorrect() { + int matches = runTest("[^abc]", "g"); + assertTrue(matches > 0); + } + + @Test + public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() { + int matches = runTest("[^bcr]at", "sat mat eat"); + assertTrue(matches > 0); + } + + @Test + public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() { + int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() { + int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 26); + } + + @Test + public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() { + int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 28); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect() { + int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenNumberRange_whenMatchesAccurately_thenCorrect2() { + int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenTwoSets_whenMatchesUnion_thenCorrect() { + int matches = runTest("[1-3[7-9]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 6); + } + + @Test + public void givenTwoSets_whenMatchesIntersection_thenCorrect() { + int matches = runTest("[1-6&&[3-9]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 4); + } + + @Test + public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() { + int matches = runTest("[0-9&&[^2468]]", "123456789"); + assertTrue(matches > 0); + assertEquals(matches, 5); + } + + @Test + public void givenDigits_whenMatches_thenCorrect() { + int matches = runTest("\\d", "123"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenNonDigits_whenMatches_thenCorrect() { + int matches = runTest("\\D", "a6c"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenWhiteSpace_whenMatches_thenCorrect() { + int matches = runTest("\\s", "a c"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenNonWhiteSpace_whenMatches_thenCorrect() { + int matches = runTest("\\S", "a c"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenWordCharacter_whenMatches_thenCorrect() { + int matches = runTest("\\w", "hi!"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenNonWordCharacter_whenMatches_thenCorrect() { + int matches = runTest("\\W", "hi!"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a?", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{0,1}", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a*", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{0,}", "hi"); + assertTrue(matches > 0); + assertEquals(matches, 3); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect() { + int matches = runTest("\\a+", "hi"); + assertFalse(matches > 0); + } + + @Test + public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() { + int matches = runTest("\\a{1,}", "hi"); + assertFalse(matches > 0); + } + + @Test + public void givenBraceQuantifier_whenMatches_thenCorrect() { + int matches = runTest("a{3}", "aaaaaa"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() { + int matches = runTest("a{3}", "aa"); + assertFalse(matches > 0); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() { + int matches = runTest("a{2,3}", "aaaa"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() { + int matches = runTest("a{2,3}?", "aaaa"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect() { + int matches = runTest("(\\d\\d)", "12"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect2() { + int matches = runTest("(\\d\\d)", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 2); + } + + @Test + public void givenCapturingGroup_whenMatches_thenCorrect3() { + int matches = runTest("(\\d\\d)(\\d\\d)", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() { + int matches = runTest("(\\d\\d)\\1", "1212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() { + int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212"); + assertTrue(matches > 0); + assertEquals(matches, 1); + } + + @Test + public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() { + int matches = runTest("(\\d\\d)\\1", "1213"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtBeginning_thenCorrect() { + int matches = runTest("^dog", "dogs are friendly"); + assertTrue(matches > 0); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() { + int matches = runTest("^dog", "are dogs are friendly?"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtEnd_thenCorrect() { + int matches = runTest("dog$", "Man's best friend is a dog"); + assertTrue(matches > 0); + } + + @Test + public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() { + int matches = runTest("dog$", "is a dog man's best friend?"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect() { + int matches = runTest("\\bdog\\b", "a dog is friendly"); + assertTrue(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordBoundary_thenCorrect2() { + int matches = runTest("\\bdog\\b", "dog is man's best friend"); + assertTrue(matches > 0); + } + + @Test + public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() { + int matches = runTest("\\bdog\\b", "snoop dogg is a rapper"); + assertFalse(matches > 0); + } + + @Test + public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() { + int matches = runTest("\\bdog\\B", "snoop dogg is a rapper"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() { + int matches = runTest("\u00E9", "\u0065\u0301"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() { + int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() { + int matches = runTest("dog", "This is a Dog"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() { + int matches = runTest("(?i)dog", "This is a Dog"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() { + int matches = runTest("dog$ #check for word dog at end of text", "This is a dog"); + assertFalse(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() { + int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() { + int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog"); + assertTrue(matches > 0); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() { + Pattern pattern = Pattern.compile("(?s)(.*)"); + Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line"); + matcher.find(); + assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); + } + + @Test + public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text"); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text", Pattern.LITERAL); + assertFalse(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() { + int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() { + int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertFalse(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() { + int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE); + assertTrue(matches > 0); + } + + @Test + public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() { + int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox"); + assertTrue(matches > 0); + } + + @Test + public void givenMatch_whenGetsIndices_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("This dog is mine"); + matcher.find(); + assertEquals(5, matcher.start()); + assertEquals(8, matcher.end()); + } + + @Test + public void whenStudyMethodsWork_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are friendly"); + assertTrue(matcher.lookingAt()); + assertFalse(matcher.matches()); + + } + + @Test + public void whenMatchesStudyMethodWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dog"); + assertTrue(matcher.matches()); + + } + + @Test + public void whenReplaceFirstWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceFirst("cat"); + assertEquals("cats are domestic animals, dogs are friendly", newStr); + + } + + @Test + public void whenReplaceAllWorks_thenCorrect() { + Pattern pattern = Pattern.compile("dog"); + Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); + String newStr = matcher.replaceAll("cat"); + assertEquals("cats are domestic animals, cats are friendly", newStr); + + } + + public synchronized static int runTest(String regex, String text) { + pattern = Pattern.compile(regex); + matcher = pattern.matcher(text); + int matches = 0; + while (matcher.find()) + matches++; + return matches; + } + + public synchronized static int runTest(String regex, String text, int flags) { + pattern = Pattern.compile(regex, flags); + matcher = pattern.matcher(text); + int matches = 0; + while (matcher.find()) + matches++; + return matches; + } +} + diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java new file mode 100644 index 0000000000..23be2200d3 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionTest.java @@ -0,0 +1,57 @@ +package org.baeldung.core.exceptions; + +import org.apache.log4j.Logger; +import org.junit.Test; + +import java.io.*; + +public class FileNotFoundExceptionTest { + + private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class); + + private String fileName = Double.toString(Math.random()); + + @Test(expected = BusinessException.class) + public void raiseBusinessSpecificException() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + throw new BusinessException("BusinessException: necessary file was not present.", ex); + } + } + + @Test + public void createFile() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + try { + new File(fileName).createNewFile(); + readFailingFile(); + } catch (IOException ioe) { + throw new RuntimeException("BusinessException: even creation is not possible.", ioe); + } + } + } + + @Test + public void logError() throws IOException { + try { + readFailingFile(); + } catch (FileNotFoundException ex) { + LOG.error("Optional file " + fileName + " was not found.", ex); + } + } + + private void readFailingFile() throws IOException { + BufferedReader rd = new BufferedReader(new FileReader(new File(fileName))); + rd.readLine(); + // no need to close file + } + + private class BusinessException extends RuntimeException { + BusinessException(String string, FileNotFoundException ex) { + super(string, ex); + } + } +} diff --git a/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java new file mode 100644 index 0000000000..83f1fb33b6 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/md5/JavaMD5Test.java @@ -0,0 +1,90 @@ +package org.baeldung.java.md5; + +import static org.junit.Assert.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.xml.bind.DatatypeConverter; + +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +import java.io.File; +import java.io.IOException; +import java.nio.*; +import static org.assertj.core.api.Assertions.assertThat; + + +public class JavaMD5Test { + + + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + + + @Test + public void givenPassword_whenHashing_thenVerifying() throws NoSuchAlgorithmException { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(password.getBytes()); + byte[] digest = md.digest(); + String myHash = DatatypeConverter.printHexBinary(digest).toUpperCase(); + + assertThat(myHash.equals(hash)).isTrue(); + } + + @Test + public void givenFile_generatingChecksum_thenVerifying() throws NoSuchAlgorithmException, IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(Files.readAllBytes(Paths.get(filename))); + byte[] digest = md.digest(); + String myChecksum = DatatypeConverter + .printHexBinary(digest).toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + @Test + public void givenPassword_whenHashingUsingCommons_thenVerifying() { + String hash = "35454B055CC325EA1AF2126E27707052"; + String password = "ILoveJava"; + + String md5Hex = DigestUtils + .md5Hex(password).toUpperCase(); + + assertThat(md5Hex.equals(hash)).isTrue(); + } + + + @Test + public void givenFile_whenChecksumUsingGuava_thenVerifying() throws IOException { + String filename = "src/test/resources/test_md5.txt"; + String checksum = "5EB63BBBE01EEED093CB22BB8F5ACDC3"; + + HashCode hash = com.google.common.io.Files + .hash(new File(filename), Hashing.md5()); + String myChecksum = hash.toString() + .toUpperCase(); + + assertThat(myChecksum.equals(checksum)).isTrue(); + } + + +} diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-async/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java deleted file mode 100644 index d593aac52d..0000000000 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.couchbase; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase"}) -public class IntegrationTestConfig { -} diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-intro/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-intro/mvnw b/couchbase-sdk-intro/mvnw deleted file mode 100755 index a1ba1bf554..0000000000 --- a/couchbase-sdk-intro/mvnw +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/couchbase-sdk-intro/mvnw.cmd b/couchbase-sdk-intro/mvnw.cmd deleted file mode 100644 index 2b934e89dd..0000000000 --- a/couchbase-sdk-intro/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% \ No newline at end of file diff --git a/couchbase-sdk-intro/pom.xml b/couchbase-sdk-intro/pom.xml deleted file mode 100644 index 1c2ca5ee05..0000000000 --- a/couchbase-sdk-intro/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - com.baeldung - couchbase-sdk-intro - 0.1-SNAPSHOT - jar - couchbase-sdk-intro - Intro to the Couchbase SDK - - - - - com.couchbase.client - java-client - ${couchbase.client.version} - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 2.2.6 - - - diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 5fd4d5023f..0000000000 Binary files a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties b/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index eb91947648..0000000000 --- a/couchbase-sdk-spring-service/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.3/apache-maven-3.3.3-bin.zip \ No newline at end of file diff --git a/couchbase-sdk-spring-service/mvnw b/couchbase-sdk-spring-service/mvnw deleted file mode 100755 index a1ba1bf554..0000000000 --- a/couchbase-sdk-spring-service/mvnw +++ /dev/null @@ -1,233 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # - # Look for the Apple JDKs first to preserve the existing behaviour, and then look - # for the new JDKs provided by Oracle. - # - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then - # - # Apple JDKs - # - export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then - # - # Oracle JDKs - # - export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home - fi - - if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then - # - # Apple JDKs - # - export JAVA_HOME=`/usr/libexec/java_home` - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` -fi - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - local basedir=$(pwd) - local wdir=$(pwd) - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - wdir=$(cd "$wdir/.."; pwd) - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)} -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} "$@" diff --git a/couchbase-sdk-spring-service/mvnw.cmd b/couchbase-sdk-spring-service/mvnw.cmd deleted file mode 100644 index 2b934e89dd..0000000000 --- a/couchbase-sdk-spring-service/mvnw.cmd +++ /dev/null @@ -1,145 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -set MAVEN_CMD_LINE_ARGS=%* - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar"" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS% -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% \ No newline at end of file diff --git a/couchbase-sdk-spring-service/pom.xml b/couchbase-sdk-spring-service/pom.xml deleted file mode 100644 index d344f8c756..0000000000 --- a/couchbase-sdk-spring-service/pom.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - 4.0.0 - com.baeldung - couchbase-sdk-spring-service - 0.1-SNAPSHOT - jar - couchbase-sdk-spring-service - Intro to the Couchbase SDK - - - - - com.couchbase.client - java-client - ${couchbase.client.version} - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-context-support - ${spring-framework.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - org.springframework - spring-test - ${spring-framework.version} - test - - - junit - junit - ${junit.version} - test - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - test - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 2.2.6 - 4.2.4.RELEASE - 1.1.3 - 1.7.12 - 4.11 - 3.4 - - - diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java b/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java deleted file mode 100644 index 8210c10b3a..0000000000 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/FluentPersonDocumentConverter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.couchbase.person; - -import org.springframework.stereotype.Service; - -import com.baeldung.couchbase.service.JsonDocumentConverter; -import com.couchbase.client.java.document.JsonDocument; -import com.couchbase.client.java.document.json.JsonObject; - -@Service -public class FluentPersonDocumentConverter implements JsonDocumentConverter { - - @Override - public JsonDocument toDocument(Person p) { - JsonObject content = JsonObject.empty() - .put("type", "Person") - .put("name", p.getName()) - .put("homeTown", p.getHomeTown()); - return JsonDocument.create(p.getId(), content); - } - - @Override - public Person fromDocument(JsonDocument doc) { - JsonObject content = doc.content(); - return Person.Builder.newInstance() - .id(doc.id()) - .type("Person") - .name(content.getString("name")) - .homeTown(content.getString("homeTown")) - .build(); - } -} diff --git a/couchbase-sdk-spring-service/src/main/resources/logback.xml b/couchbase-sdk-spring-service/src/main/resources/logback.xml deleted file mode 100644 index efcc6fb4c7..0000000000 --- a/couchbase-sdk-spring-service/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - \ No newline at end of file diff --git a/couchbase-sdk/README.md b/couchbase-sdk/README.md new file mode 100644 index 0000000000..9cdcdea012 --- /dev/null +++ b/couchbase-sdk/README.md @@ -0,0 +1,50 @@ +## Couchbase SDK Tutorial Project + +### Relevant Articles: +- [Introduction to Couchbase SDK for Java](http://www.baeldung.com/java-couchbase-sdk) +- [Using Couchbase in a Spring Application](http://www.baeldung.com/couchbase-sdk-spring) +- [Asynchronous Batch Opereations in Couchbase](http://www.baeldung.com/async-batch-operations-in-couchbase) + +### Overview +This Maven project contains the Java code for the Couchbase entities and Spring services +as described in the tutorials, as well as a unit/integration test +for each service implementation. + +### Working with the Code +The project was developed and tested using Java 7 and 8 in the Eclipse-based +Spring Source Toolkit (STS) and therefore should run fine in any +recent version of Eclipse or another IDE of your choice +that supports Java 7 or later. + +### Building the Project +You can also build the project using Maven outside of any IDE: +``` +mvn clean install +``` + +### Package Organization +Java classes for the intro tutorial are in the +org.baeldung.couchbase.intro package. + +Java classes for the Spring service tutorial are in the +org.baeldung.couchbase.spring package hierarchy. + +Java classes for the Asynchronous Couchbase tutorial are in the +org.baeldung.couchbase.async package hierarchy. + + +### Running the tests +The test classes for the Spring service tutorial are: +- org.baeldung.couchbase.spring.service.ClusterServiceTest +- org.baeldung.couchbase.spring.person.PersonCrudServiceTest + +The test classes for the Asynchronous Couchbase tutorial are in the +org.baeldung.couchbase.async package hierarchy: +- org.baeldung.couchbase.async.service.ClusterServiceTest +- org.baeldung.couchbase.async.person.PersonCrudServiceTest + +The test classes may be run as JUnit tests from your IDE +or using the Maven command line: +``` +mvn test +``` diff --git a/couchbase-sdk-async/mvnw b/couchbase-sdk/mvnw similarity index 100% rename from couchbase-sdk-async/mvnw rename to couchbase-sdk/mvnw diff --git a/couchbase-sdk-async/mvnw.cmd b/couchbase-sdk/mvnw.cmd similarity index 100% rename from couchbase-sdk-async/mvnw.cmd rename to couchbase-sdk/mvnw.cmd diff --git a/couchbase-sdk-async/pom.xml b/couchbase-sdk/pom.xml similarity index 95% rename from couchbase-sdk-async/pom.xml rename to couchbase-sdk/pom.xml index 9062ef8e15..4c277f4c85 100644 --- a/couchbase-sdk-async/pom.xml +++ b/couchbase-sdk/pom.xml @@ -3,11 +3,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung - couchbase-sdk-async + couchbase-sdk 0.1-SNAPSHOT jar - couchbase-sdk-async - Couchbase SDK Asynchronous Operations + couchbase-sdk + Couchbase SDK Tutorials diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java similarity index 70% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java index 4d2500197b..16e1876719 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CouchbaseEntity.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async; public interface CouchbaseEntity { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java similarity index 94% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java index bf248c3999..32ed2ebbe4 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/Person.java @@ -1,6 +1,6 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; -import com.baeldung.couchbase.service.CouchbaseEntity; +import com.baeldung.couchbase.async.CouchbaseEntity; public class Person implements CouchbaseEntity { diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java similarity index 77% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java index d5302bd6db..b2ef985725 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import javax.annotation.PostConstruct; @@ -6,8 +6,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.AbstractCrudService; -import com.baeldung.couchbase.service.BucketService; +import com.baeldung.couchbase.async.service.AbstractCrudService; +import com.baeldung.couchbase.async.service.BucketService; @Service public class PersonCrudService extends AbstractCrudService { diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java similarity index 88% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java index cfb20a2bfb..8646cf247a 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.JsonDocumentConverter; +import com.baeldung.couchbase.async.service.JsonDocumentConverter; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java index 53af1c4041..926cd7f4e8 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java index 08acf5deed..cbc03cbcda 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java similarity index 98% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java index ce95074015..861e2404e5 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/AbstractCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.ArrayList; import java.util.List; @@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.baeldung.couchbase.async.CouchbaseEntity; import com.couchbase.client.core.BackpressureException; import com.couchbase.client.core.time.Delay; import com.couchbase.client.java.AsyncBucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java similarity index 69% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java index df9156d87d..28470be99f 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/BucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java similarity index 74% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java index 437ec00ff4..ee67405b12 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java similarity index 95% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java index c8ff56269d..7ce75d21f5 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java similarity index 89% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java index e0f0831abb..5bd0e52214 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/CrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import java.util.List; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java similarity index 79% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java index 87331d2a17..85e14a87ce 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java similarity index 93% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java index 2e40321272..459585d995 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import javax.annotation.PostConstruct; diff --git a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java similarity index 98% rename from couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java index 088f7af7b1..2cb9e1f4f7 100644 --- a/couchbase-sdk-intro/src/main/java/com/baeldung/couchbase/examples/CodeSnippets.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.examples; +package com.baeldung.couchbase.intro; import java.util.List; import java.util.UUID; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java similarity index 97% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java index 48b7a38780..0348ba1e5f 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/Person.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/Person.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; public class Person { diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java similarity index 88% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java index 0203bf30bb..de035f1d2c 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/PersonCrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import java.util.List; import java.util.UUID; @@ -8,8 +8,9 @@ import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.CrudService; -import com.baeldung.couchbase.service.TutorialBucketService;import com.couchbase.client.java.Bucket; +import com.baeldung.couchbase.spring.service.CrudService; +import com.baeldung.couchbase.spring.service.TutorialBucketService; +import com.couchbase.client.java.Bucket; import com.couchbase.client.java.ReplicaMode; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java similarity index 88% rename from couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java index cfb20a2bfb..030c9fde27 100644 --- a/couchbase-sdk-async/src/main/java/com/baeldung/couchbase/person/PersonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java @@ -1,8 +1,8 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import org.springframework.stereotype.Service; -import com.baeldung.couchbase.service.JsonDocumentConverter; +import com.baeldung.couchbase.spring.service.JsonDocumentConverter; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java similarity index 93% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java index 53af1c4041..5ffe7acf24 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/person/RegistrationService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java similarity index 69% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java index c2562dd38e..97ff1e4fd5 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/BucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import com.couchbase.client.java.Bucket; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java similarity index 90% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java index 4713893899..a8543fbd91 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import java.util.List; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java similarity index 98% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java index 3c355d2a27..3499fa956e 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/ClusterServiceImpl.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import java.util.ArrayList; import java.util.List; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java similarity index 82% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java index 20ee851b39..f683b9f562 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/CrudService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; public interface CrudService { diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java similarity index 79% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java index 87331d2a17..cf4861fbeb 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/JsonDocumentConverter.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import com.couchbase.client.java.document.JsonDocument; diff --git a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java similarity index 93% rename from couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java rename to couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java index 903a568399..8a28deb1d6 100644 --- a/couchbase-sdk-spring-service/src/main/java/com/baeldung/couchbase/service/TutorialBucketService.java +++ b/couchbase-sdk/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import javax.annotation.PostConstruct; diff --git a/couchbase-sdk-async/src/main/resources/application.properties b/couchbase-sdk/src/main/resources/application.properties similarity index 100% rename from couchbase-sdk-async/src/main/resources/application.properties rename to couchbase-sdk/src/main/resources/application.properties diff --git a/couchbase-sdk-async/src/main/resources/logback.xml b/couchbase-sdk/src/main/resources/logback.xml similarity index 100% rename from couchbase-sdk-async/src/main/resources/logback.xml rename to couchbase-sdk/src/main/resources/logback.xml diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java similarity index 74% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java index d1cc807f7a..3079fc928a 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.async; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class IntegrationTest { +public abstract class AsyncIntegrationTest { } diff --git a/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java new file mode 100644 index 0000000000..6afdfe04bd --- /dev/null +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.couchbase.async; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages={"com.baeldung.couchbase.async"}) +public class AsyncIntegrationTestConfig { +} diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java similarity index 93% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java index 3da282492c..afc5bbd53b 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.async.person; import static org.junit.Assert.*; @@ -13,12 +13,15 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.service.BucketService; +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.couchbase.client.java.Bucket; import com.couchbase.client.java.document.JsonDocument; -public class PersonCrudServiceTest extends IntegrationTest { +public class PersonCrudServiceTest extends AsyncIntegrationTest { @Autowired private PersonCrudService personService; diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java similarity index 73% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java index 7795f41c93..8ecb51a4b9 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.async.service; import static org.junit.Assert.*; @@ -10,14 +10,15 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.IntegrationTestConfig; +import com.baeldung.couchbase.async.AsyncIntegrationTest; +import com.baeldung.couchbase.async.AsyncIntegrationTestConfig; +import com.baeldung.couchbase.async.service.ClusterService; import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { IntegrationTestConfig.class }) +@ContextConfiguration(classes = { AsyncIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public class ClusterServiceTest extends IntegrationTest { +public class ClusterServiceTest extends AsyncIntegrationTest { @Autowired private ClusterService couchbaseService; diff --git a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java similarity index 93% rename from couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java index d1cc807f7a..9c0b0a50c1 100644 --- a/couchbase-sdk-async/src/test/java/com/baeldung/couchbase/IntegrationTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.spring; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java similarity index 63% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java index d593aac52d..ac71911b9b 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/IntegrationTestConfig.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java @@ -1,9 +1,9 @@ -package com.baeldung.couchbase; +package com.baeldung.couchbase.spring; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages={"com.baeldung.couchbase"}) +@ComponentScan(basePackages={"com.baeldung.couchbase.spring"}) public class IntegrationTestConfig { } diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java similarity index 96% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java index e19e90769c..601b261f6e 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/person/PersonCrudServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.person; +package com.baeldung.couchbase.spring.person; import static org.junit.Assert.*; @@ -8,7 +8,7 @@ import org.apache.commons.lang3.RandomStringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import com.baeldung.couchbase.IntegrationTest; +import com.baeldung.couchbase.spring.IntegrationTest; public class PersonCrudServiceTest extends IntegrationTest { diff --git a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java similarity index 87% rename from couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java rename to couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java index 7795f41c93..d1968e1c04 100644 --- a/couchbase-sdk-spring-service/src/test/java/com/baeldung/couchbase/service/ClusterServiceTest.java +++ b/couchbase-sdk/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceTest.java @@ -1,4 +1,4 @@ -package com.baeldung.couchbase.service; +package com.baeldung.couchbase.spring.service; import static org.junit.Assert.*; @@ -10,8 +10,8 @@ import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import com.baeldung.couchbase.IntegrationTest; -import com.baeldung.couchbase.IntegrationTestConfig; +import com.baeldung.couchbase.spring.IntegrationTest; +import com.baeldung.couchbase.spring.IntegrationTestConfig; import com.couchbase.client.java.Bucket; @RunWith(SpringJUnit4ClassRunner.class) diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java b/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java deleted file mode 100644 index abadcc0d76..0000000000 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.enterprise.patterns.front.controller.data; - -public interface Book { - String getAuthor(); - - void setAuthor(String author); - - String getTitle(); - - void setTitle(String title); - - Double getPrice(); - - void setPrice(Double price); -} diff --git a/enterprise-patterns/pom.xml b/enterprise-patterns/pom.xml deleted file mode 100644 index 2fba12547f..0000000000 --- a/enterprise-patterns/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - - com.baeldung.enterprise.patterns - enterprise-patterns-parent - pom - - front-controller-pattern - - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - - - diff --git a/flyway-migration/README.MD b/flyway-migration/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/flyway-migration/README.MD @@ -0,0 +1 @@ + diff --git a/log4j/pom.xml b/log4j/pom.xml index 586769aa71..1081513dcf 100644 --- a/log4j/pom.xml +++ b/log4j/pom.xml @@ -15,13 +15,6 @@ log4j 1.2.17 - @@ -40,13 +33,6 @@ disruptor 3.3.4 - @@ -54,14 +40,6 @@ logback-classic 1.1.7 - - diff --git a/okhttp/pom.xml b/okhttp/pom.xml new file mode 100644 index 0000000000..ba5bcf9725 --- /dev/null +++ b/okhttp/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.baeldung.okhttp + okhttp + 0.0.1-SNAPSHOT + + + + + + com.squareup.okhttp3 + okhttp + ${com.squareup.okhttp3.version} + + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + + + + + 3.4.1 + + + 1.3 + 4.12 + + + + diff --git a/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java new file mode 100644 index 0000000000..2a33a1febd --- /dev/null +++ b/okhttp/src/main/java/org/baeldung/okhttp/DefaultContentTypeInterceptor.java @@ -0,0 +1,26 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class DefaultContentTypeInterceptor implements Interceptor { + + private final String contentType; + + public DefaultContentTypeInterceptor(String contentType) { + this.contentType = contentType; + } + + public Response intercept(Interceptor.Chain chain) throws IOException { + + Request originalRequest = chain.request(); + Request requestWithUserAgent = originalRequest.newBuilder() + .header("Content-Type", contentType) + .build(); + + return chain.proceed(requestWithUserAgent); + } +} diff --git a/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java new file mode 100644 index 0000000000..6a98f8d20a --- /dev/null +++ b/okhttp/src/main/java/org/baeldung/okhttp/ProgressRequestWrapper.java @@ -0,0 +1,68 @@ +package org.baeldung.okhttp; + +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.*; + +import java.io.IOException; + +public class ProgressRequestWrapper extends RequestBody { + + protected RequestBody delegate; + protected ProgressListener listener; + + protected CountingSink countingSink; + + public ProgressRequestWrapper(RequestBody delegate, ProgressListener listener) { + this.delegate = delegate; + this.listener = listener; + } + + @Override + public MediaType contentType() { + return delegate.contentType(); + } + + @Override + public long contentLength() throws IOException { + return delegate.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + + BufferedSink bufferedSink; + + countingSink = new CountingSink(sink); + bufferedSink = Okio.buffer(countingSink); + + delegate.writeTo(bufferedSink); + + bufferedSink.flush(); + } + + protected final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0; + + public CountingSink(Sink delegate) { + super(delegate); + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + + super.write(source, byteCount); + + bytesWritten += byteCount; + listener.onRequestProgress(bytesWritten, contentLength()); + } + + } + + public interface ProgressListener { + void onRequestProgress(long bytesWritten, long contentLength); + + } +} + diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java new file mode 100644 index 0000000000..32457fc11b --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpFileUploadingTest.java @@ -0,0 +1,81 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.baeldung.okhttp.ProgressRequestWrapper; +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpFileUploadingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenUploadFileUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetUploadFileProgressUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + + ProgressRequestWrapper.ProgressListener listener = new ProgressRequestWrapper.ProgressListener() { + + public void onRequestProgress(long bytesWritten, long contentLength) { + + float percentage = 100f * bytesWritten / contentLength; + assertFalse(Float.compare(percentage, 100) > 0); + } + }; + + ProgressRequestWrapper countingBody = new ProgressRequestWrapper(requestBody, listener); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/upload") + .post(countingBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java new file mode 100644 index 0000000000..e8edff92df --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpGetTest.java @@ -0,0 +1,78 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpGetTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + @Test + public void whenGetRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenGetRequestWithQueryParameterUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + HttpUrl.Builder urlBuilder = HttpUrl.parse(BASE_URL + "/ex/bars").newBuilder(); + urlBuilder.addQueryParameter("id", "1"); + + String url = urlBuilder.build().toString(); + + Request request = new Request.Builder() + .url(url) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenAsynchronousGetRequestUsingOkHttp_thenCorrect() { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/date") + .build(); + + Call call = client.newCall(request); + + call.enqueue(new Callback() { + + public void onResponse(Call call, Response response) throws IOException { + assertThat(response.code(), equalTo(200)); + } + + public void onFailure(Call call, IOException e) { + + } + }); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java new file mode 100644 index 0000000000..5b2e89eca8 --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpHeaderTest.java @@ -0,0 +1,48 @@ +package org.baeldung.okhttp; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpHeaderTest { + + private static final String SAMPLE_URL = "http://www.github.com"; + + @Test + public void whenSetHeaderUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .addHeader("Content-Type", "application/json") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + @Test + public void whenSetDefaultHeaderUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + .addInterceptor(new DefaultContentTypeInterceptor("application/json")) + .build(); + + Request request = new Request.Builder() + .url(SAMPLE_URL) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java new file mode 100644 index 0000000000..829bafe8ef --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpMiscTest.java @@ -0,0 +1,113 @@ +package org.baeldung.okhttp; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; + +import okhttp3.Cache; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpMiscTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + + //@Test + public void whenSetRequestTimeoutUsingOkHttp_thenFail() throws IOException { + + OkHttpClient client = new OkHttpClient.Builder() + //.connectTimeout(10, TimeUnit.SECONDS) + //.writeTimeout(10, TimeUnit.SECONDS) + .readTimeout(1, TimeUnit.SECONDS) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + response.close(); + } + + //@Test + public void whenCancelRequestUsingOkHttp_thenCorrect() throws IOException { + + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(BASE_URL + "/delay/2") // This URL is served with a 2 second delay. + .build(); + + final int seconds = 1; + //final int seconds = 3; + + final long startNanos = System.nanoTime(); + final Call call = client.newCall(request); + + // Schedule a job to cancel the call in 1 second. + executor.schedule(new Runnable() { + public void run() { + + System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); + call.cancel(); + System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); + } + }, seconds, TimeUnit.SECONDS); + + try { + + System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); + Response response = call.execute(); + System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); + + } catch (IOException e) { + + System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); + } + } + + @Test + public void whenSetResponseCacheUsingOkHttp_thenCorrect() throws IOException { + + int cacheSize = 10 * 1024 * 1024; // 10 MiB + File cacheDirectory = new File("src/test/resources/cache"); + Cache cache = new Cache(cacheDirectory, cacheSize); + + OkHttpClient client = new OkHttpClient.Builder() + .cache(cache) + .build(); + + Request request = new Request.Builder() + .url("http://publicobject.com/helloworld.txt") + //.cacheControl(CacheControl.FORCE_NETWORK) + //.cacheControl(CacheControl.FORCE_CACHE) + .build(); + + Response response1 = client.newCall(request).execute(); + + String responseBody1 = response1.body().string(); + + System.out.println("Response 1 response: " + response1); + System.out.println("Response 1 cache response: " + response1.cacheResponse()); + System.out.println("Response 1 network response: " + response1.networkResponse()); + System.out.println("Response 1 responseBody: " + responseBody1); + + Response response2 = client.newCall(request).execute(); + + String responseBody2 = response2.body().string(); + + System.out.println("Response 2 response: " + response2); + System.out.println("Response 2 cache response: " + response2.cacheResponse()); + System.out.println("Response 2 network response: " + response2.networkResponse()); + System.out.println("Response 2 responseBody: " + responseBody2); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java new file mode 100644 index 0000000000..1ba2d517c5 --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpPostingTest.java @@ -0,0 +1,109 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.Credentials; +import okhttp3.FormBody; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +public class OkHttpPostingTest { + + private static final String BASE_URL = "http://localhost:8080/spring-rest"; + private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php"; + + @Test + public void whenSendPostRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody formBody = new FormBody.Builder() + .add("username", "test") + .add("password", "test") + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users") + .post(formBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendPostRequestWithAuthorizationUsingOkHttp_thenCorrect() throws IOException { + + String postBody = "test post"; + + OkHttpClient client = new OkHttpClient(); + + Request request = new Request.Builder() + .url(URL_SECURED_BY_BASIC_AUTHENTICATION) + .addHeader("Authorization", Credentials.basic("test", "test")) + .post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), postBody)) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenPostJsonUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + String json = "{\"id\":1,\"name\":\"John\"}"; + + RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/detail") + .post(body) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } + + @Test + public void whenSendMultipartRequestUsingOkHttp_thenCorrect() throws IOException { + + OkHttpClient client = new OkHttpClient(); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("username", "test") + .addFormDataPart("password", "test") + .addFormDataPart("file", "file.txt", + RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))) + .build(); + + Request request = new Request.Builder() + .url(BASE_URL + "/users/multipart") + .post(requestBody) + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(200)); + } +} diff --git a/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java new file mode 100644 index 0000000000..1582a5ff7f --- /dev/null +++ b/okhttp/src/test/java/org/baeldung/okhttp/OkHttpRedirectTest.java @@ -0,0 +1,33 @@ +package org.baeldung.okhttp; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.io.IOException; + +import org.junit.Test; + +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class OkHttpRedirectTest { + + @Test + public void whenSetFollowRedirectsUsingOkHttp_thenNotRedirected() throws IOException { + + OkHttpClient client = new OkHttpClient().newBuilder() + .followRedirects(false) + .build(); + + Request request = new Request.Builder() + .url("http://t.co/I5YYd9tddw") + .build(); + + Call call = client.newCall(request); + Response response = call.execute(); + + assertThat(response.code(), equalTo(301)); + } +} diff --git a/okhttp/src/test/resources/test.txt b/okhttp/src/test/resources/test.txt new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/okhttp/src/test/resources/test.txt @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/enterprise-patterns/front-controller-pattern/pom.xml b/patterns/pom.xml similarity index 77% rename from enterprise-patterns/front-controller-pattern/pom.xml rename to patterns/pom.xml index dbcd4f1b1d..7c23b6f55d 100644 --- a/enterprise-patterns/front-controller-pattern/pom.xml +++ b/patterns/pom.xml @@ -4,15 +4,10 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - front-controller-pattern + com.baeldung.enterprise.patterns + patterns war - - enterprise-patterns-parent - com.baeldung.enterprise.patterns - 1.0.0-SNAPSHOT - - javax.servlet @@ -22,11 +17,22 @@ + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + org.apache.maven.plugins maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + org.eclipse.jetty diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/FrontControllerServlet.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/FrontCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/SearchCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/commands/UnknownCommand.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java similarity index 75% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java index b270bc7985..634e05c3a0 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookImpl.java +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Book.java @@ -1,45 +1,39 @@ package com.baeldung.enterprise.patterns.front.controller.data; -public class BookImpl implements Book { +public class Book { private String author; private String title; private Double price; - public BookImpl() { + public Book() { } - public BookImpl(String author, String title, Double price) { + public Book(String author, String title, Double price) { this.author = author; this.title = title; this.price = price; } - @Override public String getAuthor() { return author; } - @Override public void setAuthor(String author) { this.author = author; } - @Override public String getTitle() { return title; } - @Override public void setTitle(String title) { this.title = title; } - @Override public Double getPrice() { return price; } - @Override public void setPrice(Double price) { this.price = price; } diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java similarity index 55% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java index 1e30452d95..524e000bd9 100644 --- a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java +++ b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/Bookshelf.java @@ -3,8 +3,8 @@ package com.baeldung.enterprise.patterns.front.controller.data; public interface Bookshelf { default void init() { - add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); - add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); + add(new Book("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99)); + add(new Book("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88)); } Bookshelf getInstance(); diff --git a/enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java b/patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java rename to patterns/src/main/java/com/baeldung/enterprise/patterns/front/controller/data/BookshelfImpl.java diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png b/patterns/src/main/resources/front controller.png similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/resources/front controller.png rename to patterns/src/main/resources/front controller.png diff --git a/enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml b/patterns/src/main/resources/front controller.puml similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/resources/front controller.puml rename to patterns/src/main/resources/front controller.puml diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-found.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/book-found.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp b/patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/book-notfound.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/book-notfound.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp b/patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/jsp/unknown.jsp rename to patterns/src/main/webapp/WEB-INF/jsp/unknown.jsp diff --git a/enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml b/patterns/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from enterprise-patterns/front-controller-pattern/src/main/webapp/WEB-INF/web.xml rename to patterns/src/main/webapp/WEB-INF/web.xml diff --git a/play-framework/student-api/app/controllers/AsyncController.java b/play-framework/student-api/app/controllers/AsyncController.java index 33cd112837..92c84bb755 100644 --- a/play-framework/student-api/app/controllers/AsyncController.java +++ b/play-framework/student-api/app/controllers/AsyncController.java @@ -1,13 +1,17 @@ package controllers; import akka.actor.ActorSystem; + import javax.inject.*; + import play.*; import play.mvc.*; + import java.util.concurrent.Executor; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; + import scala.concurrent.duration.Duration; import scala.concurrent.ExecutionContextExecutor; @@ -17,11 +21,11 @@ import scala.concurrent.ExecutionContextExecutor; * asynchronously delay sending a response for 1 second. * * @param actorSystem We need the {@link ActorSystem}'s - * {@link Scheduler} to run code after a delay. - * @param exec We need a Java {@link Executor} to apply the result - * of the {@link CompletableFuture} and a Scala - * {@link ExecutionContext} so we can use the Akka {@link Scheduler}. - * An {@link ExecutionContextExecutor} implements both interfaces. + * {@link Scheduler} to run code after a delay. + * @param exec We need a Java {@link Executor} to apply the result + * of the {@link CompletableFuture} and a Scala + * {@link ExecutionContext} so we can use the Akka {@link Scheduler}. + * An {@link ExecutionContextExecutor} implements both interfaces. */ @Singleton public class AsyncController extends Controller { @@ -31,14 +35,14 @@ public class AsyncController extends Controller { @Inject public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) { - this.actorSystem = actorSystem; - this.exec = exec; + this.actorSystem = actorSystem; + this.exec = exec; } /** * An action that returns a plain text message after a delay * of 1 second. - * + *

* The configuration in the routes file means that this method * will be called when the application receives a GET request with * a path of /message. @@ -50,9 +54,9 @@ public class AsyncController extends Controller { private CompletionStage getFutureMessage(long time, TimeUnit timeUnit) { CompletableFuture future = new CompletableFuture<>(); actorSystem.scheduler().scheduleOnce( - Duration.create(time, timeUnit), - () -> future.complete("Hi!"), - exec + Duration.create(time, timeUnit), + () -> future.complete("Hi!"), + exec ); return future; } diff --git a/play-framework/student-api/app/controllers/StudentController.java b/play-framework/student-api/app/controllers/StudentController.java index 0adedfa432..8b759b9598 100644 --- a/play-framework/student-api/app/controllers/StudentController.java +++ b/play-framework/student-api/app/controllers/StudentController.java @@ -1,56 +1,63 @@ package controllers; -import models.*; -import util.*; -import play.mvc.*; -import play.libs.Json; -import play.libs.Json.*; -import com.fasterxml.jackson.databind.JsonNode; + +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import java.util.List; +import models.Student; +import models.StudentStore; +import play.libs.Json; +import play.mvc.Controller; +import play.mvc.Result; +import util.Util; + +import java.util.Set; public class StudentController extends Controller { public Result create() { - JsonNode json = request().body().asJson(); - if(json == null) - return badRequest(Util.createResponse("Expecting Json data",false)); - Student student=StudentStore.getInstance().addStudent((Student)Json.fromJson(json,Student.class)); - JsonNode jsonObject=Json.toJson(student); - return created(Util.createResponse(jsonObject,true)); - } - public Result update() { JsonNode json = request().body().asJson(); - if(json == null) - return badRequest(Util.createResponse("Expecting Json data",false)); - Student student=StudentStore.getInstance().updateStudent((Student)Json.fromJson(json,Student.class)); - if(student==null){ - return notFound(Util.createResponse("Student not found",false)); - } - - JsonNode jsonObject=Json.toJson(student); - return ok(Util.createResponse(jsonObject,true)); + if (json == null) { + return badRequest(Util.createResponse("Expecting Json data", false)); + } + Student student = StudentStore.getInstance().addStudent(Json.fromJson(json, Student.class)); + JsonNode jsonObject = Json.toJson(student); + return created(Util.createResponse(jsonObject, true)); } - public Result retrieve(int id) { - Student student=StudentStore.getInstance().getStudent(id); - if(student==null){ - return notFound(Util.createResponse("Student with id:"+id+" not found",false)); - } - JsonNode jsonObjects=Json.toJson(student); - return ok(Util.createResponse(jsonObjects,true)); - } - public Result listStudents() { - List result=StudentStore.getInstance().getAllStudents(); - ObjectMapper mapper = new ObjectMapper(); - JsonNode jsonData=mapper.convertValue(result, JsonNode.class); - return ok(Util.createResponse(jsonData,true)); + public Result update() { + JsonNode json = request().body().asJson(); + if (json == null) { + return badRequest(Util.createResponse("Expecting Json data", false)); + } + Student student = StudentStore.getInstance().updateStudent(Json.fromJson(json, Student.class)); + if (student == null) { + return notFound(Util.createResponse("Student not found", false)); + } + + JsonNode jsonObject = Json.toJson(student); + return ok(Util.createResponse(jsonObject, true)); + } + + public Result retrieve(int id) { + if (StudentStore.getInstance().getStudent(id) == null) { + return notFound(Util.createResponse("Student with id:" + id + " not found", false)); + } + JsonNode jsonObjects = Json.toJson(StudentStore.getInstance().getStudent(id)); + return ok(Util.createResponse(jsonObjects, true)); + } + + public Result listStudents() { + Set result = StudentStore.getInstance().getAllStudents(); + ObjectMapper mapper = new ObjectMapper(); + + JsonNode jsonData = mapper.convertValue(result, JsonNode.class); + return ok(Util.createResponse(jsonData, true)); } - public Result delete(int id) { - boolean status=StudentStore.getInstance().deleteStudent(id); - if(!status){ - return notFound(Util.createResponse("Student with id:"+id+" not found",false)); - } - return ok(Util.createResponse("Student with id:"+id+" deleted",true)); + + public Result delete(int id) { + if (!StudentStore.getInstance().deleteStudent(id)) { + return notFound(Util.createResponse("Student with id:" + id + " not found", false)); + } + return ok(Util.createResponse("Student with id:" + id + " deleted", true)); } } diff --git a/play-framework/student-api/app/models/StudentStore.java b/play-framework/student-api/app/models/StudentStore.java index 3290e141cd..add6a5dbd6 100644 --- a/play-framework/student-api/app/models/StudentStore.java +++ b/play-framework/student-api/app/models/StudentStore.java @@ -1,40 +1,39 @@ package models; -import java.util.ArrayList; + import java.util.HashMap; -import java.util.List; +import java.util.HashSet; import java.util.Map; +import java.util.Set; public class StudentStore { private static StudentStore instance; private Map students = new HashMap<>(); public static StudentStore getInstance() { - if (instance == null) + if (instance == null) { instance = new StudentStore(); + } return instance; } public Student addStudent(Student student) { - int id = students.size() + 1; + int id = students.size(); student.setId(id); students.put(id, student); return student; } public Student getStudent(int id) { - if (students.containsKey(id)) - return students.get(id); - return null; + return students.get(id); } - public List getAllStudents() { - return new ArrayList(students.values()); + public Set getAllStudents() { + return new HashSet<>(students.values()); } public Student updateStudent(Student student) { - int id=student.getId(); + int id = student.getId(); if (students.containsKey(id)) { - student.setId(id); students.put(id, student); return student; } @@ -42,11 +41,6 @@ public class StudentStore { } public boolean deleteStudent(int id) { - - if (!students.containsKey(id)) - return false; - students.remove(id); - return true; - + return students.remove(id) != null; } } \ No newline at end of file diff --git a/play-framework/student-api/app/util/Util.java b/play-framework/student-api/app/util/Util.java index 3718b50677..a853a4cb43 100644 --- a/play-framework/student-api/app/util/Util.java +++ b/play-framework/student-api/app/util/Util.java @@ -1,17 +1,17 @@ package util; -import com.fasterxml.jackson.databind.node.ObjectNode; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import play.libs.Json; -import play.libs.Json.*; -import com.fasterxml.jackson.databind.JsonNode; -public class Util{ - public static ObjectNode createResponse(Object response,boolean ok){ - ObjectNode result = Json.newObject(); - result.put("isSuccessfull", ok); - if(response instanceof String) - result.put("body",(String)response); - else result.put("body",(JsonNode)response); +public class Util { + public static ObjectNode createResponse(Object response, boolean ok) { + ObjectNode result = Json.newObject(); + result.put("isSuccessfull", ok); + if (response instanceof String) + result.put("body", (String) response); + else result.put("body", (JsonNode) response); - return result; - } + return result; + } } \ No newline at end of file diff --git a/pom.xml b/pom.xml index 33162777b7..5526c1e2a3 100644 --- a/pom.xml +++ b/pom.xml @@ -22,15 +22,14 @@ cdi core-java core-java-8 + couchbase-sdk - couchbase-sdk-intro - couchbase-sdk-spring-service dozer dependency-injection deltaspike - enterprise-patterns + patterns feign-client @@ -70,6 +69,7 @@ rest-assured rest-testing resteasy + okhttp spring-all spring-akka @@ -80,7 +80,6 @@ spring-cucumber spring-data-cassandra spring-data-couchbase-2 - spring-data-couchbase-2b spring-data-elasticsearch spring-data-neo4j spring-data-mongodb @@ -91,11 +90,13 @@ spring-hibernate3 spring-hibernate4 spring-jpa + spring-jms spring-katharsis spring-mockito spring-mvc-java spring-mvc-no-xml spring-mvc-xml + spring-mvc-tiles spring-openid spring-protobuf spring-quartz @@ -132,6 +133,7 @@ wicket xstream java-cassandra + annotations diff --git a/routing-in-play/.gitignore b/routing-in-play/.gitignore new file mode 100644 index 0000000000..eb372fc719 --- /dev/null +++ b/routing-in-play/.gitignore @@ -0,0 +1,8 @@ +logs +target +/.idea +/.idea_modules +/.classpath +/.project +/.settings +/RUNNING_PID diff --git a/routing-in-play/LICENSE b/routing-in-play/LICENSE new file mode 100644 index 0000000000..4baedcb95f --- /dev/null +++ b/routing-in-play/LICENSE @@ -0,0 +1,8 @@ +This software is licensed under the Apache 2 license, quoted below. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this project 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. \ No newline at end of file diff --git a/routing-in-play/README b/routing-in-play/README new file mode 100644 index 0000000000..f21d092edf --- /dev/null +++ b/routing-in-play/README @@ -0,0 +1,49 @@ +This is your new Play application +================================= + +This file will be packaged with your application when using `activator dist`. + +There are several demonstration files available in this template. + +Controllers +=========== + +- HomeController.java: + + Shows how to handle simple HTTP requests. + +- AsyncController.java: + + Shows how to do asynchronous programming when handling a request. + +- CountController.java: + + Shows how to inject a component into a controller and use the component when + handling requests. + +Components +========== + +- Module.java: + + Shows how to use Guice to bind all the components needed by your application. + +- Counter.java: + + An example of a component that contains state, in this case a simple counter. + +- ApplicationTimer.java: + + An example of a component that starts when the application starts and stops + when the application stops. + +Filters +======= + +- Filters.java: + + Creates the list of HTTP filters used by your application. + +- ExampleFilter.java + + A simple filter that adds a header to every response. \ No newline at end of file diff --git a/routing-in-play/app/Filters.java b/routing-in-play/app/Filters.java new file mode 100644 index 0000000000..255de8ca93 --- /dev/null +++ b/routing-in-play/app/Filters.java @@ -0,0 +1,46 @@ +import javax.inject.*; +import play.*; +import play.mvc.EssentialFilter; +import play.http.HttpFilters; +import play.mvc.*; + +import filters.ExampleFilter; + +/** + * This class configures filters that run on every request. This + * class is queried by Play to get a list of filters. + * + * Play will automatically use filters from any class called + * Filters that is placed the root package. You can load filters + * from a different class by adding a `play.http.filters` setting to + * the application.conf configuration file. + */ +@Singleton +public class Filters implements HttpFilters { + + private final Environment env; + private final EssentialFilter exampleFilter; + + /** + * @param env Basic environment settings for the current application. + * @param exampleFilter A demonstration filter that adds a header to + */ + @Inject + public Filters(Environment env, ExampleFilter exampleFilter) { + this.env = env; + this.exampleFilter = exampleFilter; + } + + @Override + public EssentialFilter[] filters() { + // Use the example filter if we're running development mode. If + // we're running in production or test mode then don't use any + // filters at all. + if (env.mode().equals(Mode.DEV)) { + return new EssentialFilter[] { exampleFilter }; + } else { + return new EssentialFilter[] {}; + } + } + +} diff --git a/routing-in-play/app/Module.java b/routing-in-play/app/Module.java new file mode 100644 index 0000000000..6e7d1766ef --- /dev/null +++ b/routing-in-play/app/Module.java @@ -0,0 +1,31 @@ +import com.google.inject.AbstractModule; +import java.time.Clock; + +import services.ApplicationTimer; +import services.AtomicCounter; +import services.Counter; + +/** + * This class is a Guice module that tells Guice how to bind several + * different types. This Guice module is created when the Play + * application starts. + * + * Play will automatically use any class called `Module` that is in + * the root package. You can create modules in other locations by + * adding `play.modules.enabled` settings to the `application.conf` + * configuration file. + */ +public class Module extends AbstractModule { + + @Override + public void configure() { + // Use the system clock as the default implementation of Clock + bind(Clock.class).toInstance(Clock.systemDefaultZone()); + // Ask Guice to create an instance of ApplicationTimer when the + // application starts. + bind(ApplicationTimer.class).asEagerSingleton(); + // Set AtomicCounter as the implementation for Counter. + bind(Counter.class).to(AtomicCounter.class); + } + +} diff --git a/routing-in-play/app/controllers/HomeController.java b/routing-in-play/app/controllers/HomeController.java new file mode 100644 index 0000000000..6e340d594f --- /dev/null +++ b/routing-in-play/app/controllers/HomeController.java @@ -0,0 +1,33 @@ +package controllers; + +import play.mvc.*; + +import views.html.*; + +/** + * This controller contains an action to handle HTTP requests + * to the application's home page. + */ +public class HomeController extends Controller { + + /** + * An action that renders an HTML page with a welcome message. + * The configuration in the routes file means that + * this method will be called when the application receives a + * GET request with a path of /. + */ + public Result index(String author,int id) { + return ok("Routing in Play by:"+author+" ID:"+id); + } + public Result greet(String name,int age) { + return ok("Hello "+name+", you are "+age+" years old"); + } + public Result introduceMe(String data) { + String[] clientData=data.split(","); + return ok("Your name is "+clientData[0]+", you are "+clientData[1]+" years old"); + } + public Result squareMe(Long num) { + return ok(num+" Squared is "+(num*num)); + } + +} diff --git a/routing-in-play/app/filters/ExampleFilter.java b/routing-in-play/app/filters/ExampleFilter.java new file mode 100644 index 0000000000..67a6a36cc3 --- /dev/null +++ b/routing-in-play/app/filters/ExampleFilter.java @@ -0,0 +1,45 @@ +package filters; + +import akka.stream.Materializer; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.Executor; +import java.util.function.Function; +import javax.inject.*; +import play.mvc.*; +import play.mvc.Http.RequestHeader; + + +/** + * This is a simple filter that adds a header to all requests. It's + * added to the application's list of filters by the + * {@link Filters} class. + */ +@Singleton +public class ExampleFilter extends Filter { + + private final Executor exec; + + /** + * @param mat This object is needed to handle streaming of requests + * and responses. + * @param exec This class is needed to execute code asynchronously. + * It is used below by the thenAsyncApply method. + */ + @Inject + public ExampleFilter(Materializer mat, Executor exec) { + super(mat); + this.exec = exec; + } + + @Override + public CompletionStage apply( + Function> next, + RequestHeader requestHeader) { + + return next.apply(requestHeader).thenApplyAsync( + result -> result.withHeader("X-ExampleFilter", "foo"), + exec + ); + } + +} diff --git a/routing-in-play/app/services/ApplicationTimer.java b/routing-in-play/app/services/ApplicationTimer.java new file mode 100644 index 0000000000..a951562b1d --- /dev/null +++ b/routing-in-play/app/services/ApplicationTimer.java @@ -0,0 +1,50 @@ +package services; + +import java.time.Clock; +import java.time.Instant; +import java.util.concurrent.CompletableFuture; +import javax.inject.*; +import play.Logger; +import play.inject.ApplicationLifecycle; + +/** + * This class demonstrates how to run code when the + * application starts and stops. It starts a timer when the + * application starts. When the application stops it prints out how + * long the application was running for. + * + * This class is registered for Guice dependency injection in the + * {@link Module} class. We want the class to start when the application + * starts, so it is registered as an "eager singleton". See the code + * in the {@link Module} class to see how this happens. + * + * This class needs to run code when the server stops. It uses the + * application's {@link ApplicationLifecycle} to register a stop hook. + */ +@Singleton +public class ApplicationTimer { + + private final Clock clock; + private final ApplicationLifecycle appLifecycle; + private final Instant start; + + @Inject + public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) { + this.clock = clock; + this.appLifecycle = appLifecycle; + // This code is called when the application starts. + start = clock.instant(); + Logger.info("ApplicationTimer demo: Starting application at " + start); + + // When the application starts, register a stop hook with the + // ApplicationLifecycle object. The code inside the stop hook will + // be run when the application stops. + appLifecycle.addStopHook(() -> { + Instant stop = clock.instant(); + Long runningTime = stop.getEpochSecond() - start.getEpochSecond(); + Logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s."); + return CompletableFuture.completedFuture(null); + }); + } + +} diff --git a/routing-in-play/app/services/AtomicCounter.java b/routing-in-play/app/services/AtomicCounter.java new file mode 100644 index 0000000000..41f741cbf7 --- /dev/null +++ b/routing-in-play/app/services/AtomicCounter.java @@ -0,0 +1,26 @@ +package services; + +import java.util.concurrent.atomic.AtomicInteger; +import javax.inject.*; + +/** + * This class is a concrete implementation of the {@link Counter} trait. + * It is configured for Guice dependency injection in the {@link Module} + * class. + * + * This class has a {@link Singleton} annotation because we need to make + * sure we only use one counter per application. Without this + * annotation we would get a new instance every time a {@link Counter} is + * injected. + */ +@Singleton +public class AtomicCounter implements Counter { + + private final AtomicInteger atomicCounter = new AtomicInteger(); + + @Override + public int nextCount() { + return atomicCounter.getAndIncrement(); + } + +} diff --git a/routing-in-play/app/services/Counter.java b/routing-in-play/app/services/Counter.java new file mode 100644 index 0000000000..dadad8b09d --- /dev/null +++ b/routing-in-play/app/services/Counter.java @@ -0,0 +1,13 @@ +package services; + +/** + * This interface demonstrates how to create a component that is injected + * into a controller. The interface represents a counter that returns a + * incremented number each time it is called. + * + * The {@link Modules} class binds this interface to the + * {@link AtomicCounter} implementation. + */ +public interface Counter { + int nextCount(); +} diff --git a/routing-in-play/app/views/index.scala.html b/routing-in-play/app/views/index.scala.html new file mode 100644 index 0000000000..4539f5a10b --- /dev/null +++ b/routing-in-play/app/views/index.scala.html @@ -0,0 +1,20 @@ +@* + * This template takes a single argument, a String containing a + * message to display. + *@ +@(message: String) + +@* + * Call the `main` template with two arguments. The first + * argument is a `String` with the title of the page, the second + * argument is an `Html` object containing the body of the page. + *@ +@main("Welcome to Play") { + + @* + * Get an `Html` object by calling the built-in Play welcome + * template and passing a `String` message. + *@ + @play20.welcome(message, style = "Java") + +} diff --git a/routing-in-play/app/views/main.scala.html b/routing-in-play/app/views/main.scala.html new file mode 100644 index 0000000000..9414f4be6e --- /dev/null +++ b/routing-in-play/app/views/main.scala.html @@ -0,0 +1,23 @@ +@* + * This template is called from the `index` template. This template + * handles the rendering of the page header and body tags. It takes + * two arguments, a `String` for the title of the page and an `Html` + * object to insert into the body of the page. + *@ +@(title: String)(content: Html) + + + + + @* Here's where we render the page title `String`. *@ + @title + + + + + + @* And here's where we render the `Html` object containing + * the page content. *@ + @content + + diff --git a/routing-in-play/bin/activator b/routing-in-play/bin/activator new file mode 100644 index 0000000000..a8b11d482f --- /dev/null +++ b/routing-in-play/bin/activator @@ -0,0 +1,397 @@ +#!/usr/bin/env bash + +### ------------------------------- ### +### Helper methods for BASH scripts ### +### ------------------------------- ### + +realpath () { +( + TARGET_FILE="$1" + FIX_CYGPATH="$2" + + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + + COUNT=0 + while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ] + do + TARGET_FILE=$(readlink "$TARGET_FILE") + cd "$(dirname "$TARGET_FILE")" + TARGET_FILE=$(basename "$TARGET_FILE") + COUNT=$(($COUNT + 1)) + done + + # make sure we grab the actual windows path, instead of cygwin's path. + if [[ "x$FIX_CYGPATH" != "x" ]]; then + echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")" + else + echo "$(pwd -P)/$TARGET_FILE" + fi +) +} + + +# Uses uname to detect if we're in the odd cygwin environment. +is_cygwin() { + local os=$(uname -s) + case "$os" in + CYGWIN*) return 0 ;; + *) return 1 ;; + esac +} + +# TODO - Use nicer bash-isms here. +CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi) + + +# This can fix cygwin style /cygdrive paths so we get the +# windows style paths. +cygwinpath() { + local file="$1" + if [[ "$CYGWIN_FLAG" == "true" ]]; then + echo $(cygpath -w $file) + else + echo $file + fi +} + +# Make something URI friendly +make_url() { + url="$1" + local nospaces=${url// /%20} + if is_cygwin; then + echo "/${nospaces//\\//}" + else + echo "$nospaces" + fi +} + +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands +declare java_cmd=java +declare java_version +declare -r real_script_path="$(realpath "$0")" +declare -r sbt_home="$(realpath "$(dirname "$(dirname "$real_script_path")")")" +declare -r sbt_bin_dir="$(dirname "$real_script_path")" +declare -r app_version="1.3.10" + +declare -r script_name=activator +declare -r java_opts=( "${ACTIVATOR_OPTS[@]}" "${SBT_OPTS[@]}" "${JAVA_OPTS[@]}" "${java_opts[@]}" ) +userhome="$HOME" +if is_cygwin; then + # cygwin sets home to something f-d up, set to real windows homedir + userhome="$USERPROFILE" +fi +declare -r activator_user_home_dir="${userhome}/.activator" +declare -r java_opts_config_home="${activator_user_home_dir}/activatorconfig.txt" +declare -r java_opts_config_version="${activator_user_home_dir}/${app_version}/activatorconfig.txt" + +echoerr () { + echo 1>&2 "$@" +} +vlog () { + [[ $verbose || $debug ]] && echoerr "$@" +} +dlog () { + [[ $debug ]] && echoerr "$@" +} + +jar_file () { + echo "$(cygwinpath "${sbt_home}/libexec/activator-launch-${app_version}.jar")" +} + +acquire_sbt_jar () { + sbt_jar="$(jar_file)" + + if [[ ! -f "$sbt_jar" ]]; then + echoerr "Could not find launcher jar: $sbt_jar" + exit 2 + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + [[ $verbose || $debug ]] && echo "# Executing command line:" && { + for arg; do + if printf "%s\n" "$arg" | grep -q ' '; then + printf "\"%s\"\n" "$arg" + else + printf "%s\n" "$arg" + fi + done + echo "" + } + + # THis used to be exec, but we loose the ability to re-hook stty then + # for cygwin... Maybe we should flag the feature here... + "$@" +} + +addJava () { + dlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + dlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +addResidual () { + dlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addDebugger () { + addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1" +} + +get_mem_opts () { + # if we detect any of these settings in ${JAVA_OPTS} we need to NOT output our settings. + # The reason is the Xms/Xmx, if they don't line up, cause errors. + if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then + echo "" + else + # a ham-fisted attempt to move some memory settings in concert + # so they need not be messed around with individually. + local mem=${1:-1024} + local codecache=$(( $mem / 8 )) + (( $codecache > 128 )) || codecache=128 + (( $codecache < 512 )) || codecache=512 + local class_metadata_size=$(( $codecache * 2 )) + local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize") + + echo "-Xms${mem}m -Xmx${mem}m -XX:ReservedCodeCacheSize=${codecache}m -XX:${class_metadata_opt}=${class_metadata_size}m" + fi +} + +require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + echo "$opt requires <$type> argument" + exit 1 + fi +} + +is_function_defined() { + declare -f "$1" > /dev/null +} + +# If we're *not* running in a terminal, and we don't have any arguments, then we need to add the 'ui' parameter +detect_terminal_for_ui() { + [[ ! -t 0 ]] && [[ "${#residual_args}" == "0" ]] && { + addResidual "ui" + } + # SPECIAL TEST FOR MAC + [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]] && [[ "${#residual_args}" == "0" ]] && { + echo "Detected MAC OSX launched script...." + echo "Swapping to UI" + addResidual "ui" + } +} + +process_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v|-verbose) verbose=1 && shift ;; + -d|-debug) debug=1 && shift ;; + + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; + -batch) exec &1 | awk -F '"' '/version/ {print $2}') + vlog "[process_args] java_version = '$java_version'" +} + +# Detect that we have java installed. +checkJava() { + local required_version="$1" + # Now check to see if it's a good enough version + if [[ "$java_version" == "" ]]; then + echo + echo No java installations was detected. + echo Please go to http://www.java.com/getjava/ and download + echo + exit 1 + elif [[ ! "$java_version" > "$required_version" ]]; then + echo + echo The java installation you have is not up to date + echo $script_name requires at least version $required_version+, you have + echo version $java_version + echo + echo Please go to http://www.java.com/getjava/ and download + echo a valid Java Runtime and install before running $script_name. + echo + exit 1 + fi +} + + +run() { + # no jar? download it. + [[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || { + # still no jar? uh-oh. + echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar" + exit 1 + } + + # process the combined args, then reset "$@" to the residuals + process_args "$@" + detect_terminal_for_ui + set -- "${residual_args[@]}" + argumentCount=$# + + # TODO - java check should be configurable... + checkJava "1.6" + + #If we're in cygwin, we should use the windows config, and terminal hacks + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty -icanon min 1 -echo > /dev/null 2>&1 + addJava "-Djline.terminal=jline.UnixTerminal" + addJava "-Dsbt.cygwin=true" + fi + + # run sbt + execRunner "$java_cmd" \ + "-Dactivator.home=$(make_url "$sbt_home")" \ + ${SBT_OPTS:-$default_sbt_opts} \ + $(get_mem_opts $sbt_mem) \ + ${JAVA_OPTS} \ + ${java_args[@]} \ + -jar "$sbt_jar" \ + "${sbt_commands[@]}" \ + "${residual_args[@]}" + + exit_code=$? + + # Clean up the terminal from cygwin hacks. + if [[ "$CYGWIN_FLAG" == "true" ]]; then + stty icanon echo > /dev/null 2>&1 + fi + exit $exit_code +} + + +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r sbt_opts_file=".sbtopts" +declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts" +declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt" + +usage() { + cat < path to global settings/plugins directory (default: ~/.sbt) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11 series) + -ivy path to local Ivy repository (default: ~/.ivy2) + -mem set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem)) + -no-share use all local caches; no sharing + -no-global uses global caches, but does not use global ~/.sbt directory. + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + + # sbt version (default: from project/build.properties if present, else latest release) + -sbt-version use the specified version of sbt + -sbt-jar use the specified jar as the sbt launcher + -sbt-rc use an RC version of sbt + -sbt-snapshot use a snapshot version of sbt + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # jvm options and output control + JAVA_OPTS environment variable, if unset uses "$java_opts" + SBT_OPTS environment variable, if unset uses "$default_sbt_opts" + ACTIVATOR_OPTS Environment variable, if unset uses "" + .sbtopts if this file exists in the current directory, it is + prepended to the runner args + /etc/sbt/sbtopts if this file exists, it is prepended to the runner args + -Dkey=val pass -Dkey=val directly to the java runtime + -J-X pass option -X directly to the java runtime + (-J is stripped) + -S-X add -X to sbt's scalacOptions (-S is stripped) + +In the case of duplicated or conflicting options, the order above +shows precedence: JAVA_OPTS lowest, command line options highest. +EOM +} + + + +process_my_args () { + while [[ $# -gt 0 ]]; do + case "$1" in + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) addJava "$noshare_opts" && shift ;; + -no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -batch) exec ^&1') do ( + if %%~j==java set JAVAINSTALLED=1 + if %%~j==openjdk set JAVAINSTALLED=1 +) + +rem Detect the same thing about javac +if "%_JAVACCMD%"=="" ( + if not "%JAVA_HOME%"=="" ( + if exist "%JAVA_HOME%\bin\javac.exe" set "_JAVACCMD=%JAVA_HOME%\bin\javac.exe" + ) +) +if "%_JAVACCMD%"=="" set _JAVACCMD=javac +for /F %%j in ('"%_JAVACCMD%" -version 2^>^&1') do ( + if %%~j==javac set JAVACINSTALLED=1 +) + +rem BAT has no logical or, so we do it OLD SCHOOL! Oppan Redmond Style +set JAVAOK=true +if not defined JAVAINSTALLED set JAVAOK=false +if not defined JAVACINSTALLED set JAVAOK=false + +if "%JAVAOK%"=="false" ( + echo. + echo A Java JDK is not installed or can't be found. + if not "%JAVA_HOME%"=="" ( + echo JAVA_HOME = "%JAVA_HOME%" + ) + echo. + echo Please go to + echo http://www.oracle.com/technetwork/java/javase/downloads/index.html + echo and download a valid Java JDK and install before running Activator. + echo. + echo If you think this message is in error, please check + echo your environment variables to see if "java.exe" and "javac.exe" are + echo available via JAVA_HOME or PATH. + echo. + if defined DOUBLECLICKED pause + exit /B 1 +) + +rem Check what Java version is being used to determine what memory options to use +for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( + set JAVA_VERSION=%%g +) + +rem Strips away the " characters +set JAVA_VERSION=%JAVA_VERSION:"=% + +rem TODO Check if there are existing mem settings in JAVA_OPTS/CFG_OPTS and use those instead of the below +for /f "delims=. tokens=1-3" %%v in ("%JAVA_VERSION%") do ( + set MAJOR=%%v + set MINOR=%%w + set BUILD=%%x + + set META_SIZE=-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=256M + if "!MINOR!" LSS "8" ( + set META_SIZE=-XX:PermSize=64M -XX:MaxPermSize=256M + ) + + set MEM_OPTS=!META_SIZE! + ) + +rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config. +set _JAVA_OPTS=%JAVA_OPTS% +if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS% + +set DEBUG_OPTS= + +rem Loop through the arguments, building remaining args in args variable +set args= +:argsloop +if not "%~1"=="" ( + rem Checks if the argument contains "-D" and if true, adds argument 1 with 2 and puts an equal sign between them. + rem This is done since batch considers "=" to be a delimiter so we need to circumvent this behavior with a small hack. + set arg1=%~1 + if "!arg1:~0,2!"=="-D" ( + set "args=%args% "%~1"="%~2"" + shift + shift + goto argsloop + ) + + if "%~1"=="-jvm-debug" ( + if not "%~2"=="" ( + rem This piece of magic somehow checks that an argument is a number + for /F "delims=0123456789" %%i in ("%~2") do ( + set var="%%i" + ) + if defined var ( + rem Not a number, assume no argument given and default to 9999 + set JPDA_PORT=9999 + ) else ( + rem Port was given, shift arguments + set JPDA_PORT=%~2 + shift + ) + ) else ( + set JPDA_PORT=9999 + ) + shift + + set DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=!JPDA_PORT! + goto argsloop + ) + rem else + set "args=%args% "%~1"" + shift + goto argsloop +) + +:run + +if "!args!"=="" ( + if defined DOUBLECLICKED ( + set CMDS="ui" + ) else set CMDS=!args! +) else set CMDS=!args! + +rem We add a / in front, so we get file:///C: instead of file://C: +rem Java considers the later a UNC path. +rem We also attempt a solid effort at making it URI friendly. +rem We don't even bother with UNC paths. +set JAVA_FRIENDLY_HOME_1=/!ACTIVATOR_HOME:\=/! +set JAVA_FRIENDLY_HOME=/!JAVA_FRIENDLY_HOME_1: =%%20! + +rem Checks if the command contains spaces to know if it should be wrapped in quotes or not +set NON_SPACED_CMD=%_JAVACMD: =% +if "%_JAVACMD%"=="%NON_SPACED_CMD%" %_JAVACMD% %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% +if NOT "%_JAVACMD%"=="%NON_SPACED_CMD%" "%_JAVACMD%" %DEBUG_OPTS% %MEM_OPTS% %ACTIVATOR_OPTS% %SBT_OPTS% %_JAVA_OPTS% "-Dactivator.home=%JAVA_FRIENDLY_HOME%" -jar "%ACTIVATOR_HOME%\libexec\%ACTIVATOR_LAUNCH_JAR%" %CMDS% + +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end + +@endlocal + +exit /B %ERROR_CODE% diff --git a/routing-in-play/build.sbt b/routing-in-play/build.sbt new file mode 100644 index 0000000000..083d071676 --- /dev/null +++ b/routing-in-play/build.sbt @@ -0,0 +1,13 @@ +name := """webapp""" + +version := "1.0-SNAPSHOT" + +lazy val root = (project in file(".")).enablePlugins(PlayJava) + +scalaVersion := "2.11.7" + +libraryDependencies ++= Seq( + javaJdbc, + cache, + javaWs +) diff --git a/routing-in-play/conf/application.conf b/routing-in-play/conf/application.conf new file mode 100644 index 0000000000..489d3f9b3e --- /dev/null +++ b/routing-in-play/conf/application.conf @@ -0,0 +1,353 @@ +# This is the main configuration file for the application. +# https://www.playframework.com/documentation/latest/ConfigFile +# ~~~~~ +# Play uses HOCON as its configuration file format. HOCON has a number +# of advantages over other config formats, but there are two things that +# can be used when modifying settings. +# +# You can include other configuration files in this main application.conf file: +#include "extra-config.conf" +# +# You can declare variables and substitute for them: +#mykey = ${some.value} +# +# And if an environment variable exists when there is no other subsitution, then +# HOCON will fall back to substituting environment variable: +#mykey = ${JAVA_HOME} + +## Akka +# https://www.playframework.com/documentation/latest/ScalaAkka#Configuration +# https://www.playframework.com/documentation/latest/JavaAkka#Configuration +# ~~~~~ +# Play uses Akka internally and exposes Akka Streams and actors in Websockets and +# other streaming HTTP responses. +akka { + # "akka.log-config-on-start" is extraordinarly useful because it log the complete + # configuration at INFO level, including defaults and overrides, so it s worth + # putting at the very top. + # + # Put the following in your conf/logback.xml file: + # + # + # + # And then uncomment this line to debug the configuration. + # + #log-config-on-start = true +} + +## Secret key +# http://www.playframework.com/documentation/latest/ApplicationSecret +# ~~~~~ +# The secret key is used to sign Play's session cookie. +# This must be changed for production, but we don't recommend you change it in this file. +play.crypto.secret = "changeme" + +## Modules +# https://www.playframework.com/documentation/latest/Modules +# ~~~~~ +# Control which modules are loaded when Play starts. Note that modules are +# the replacement for "GlobalSettings", which are deprecated in 2.5.x. +# Please see https://www.playframework.com/documentation/latest/GlobalSettings +# for more information. +# +# You can also extend Play functionality by using one of the publically available +# Play modules: https://playframework.com/documentation/latest/ModuleDirectory +play.modules { + # By default, Play will load any class called Module that is defined + # in the root package (the "app" directory), or you can define them + # explicitly below. + # If there are any built-in modules that you want to disable, you can list them here. + #enabled += my.application.Module + + # If there are any built-in modules that you want to disable, you can list them here. + #disabled += "" +} + +## IDE +# https://www.playframework.com/documentation/latest/IDE +# ~~~~~ +# Depending on your IDE, you can add a hyperlink for errors that will jump you +# directly to the code location in the IDE in dev mode. The following line makes +# use of the IntelliJ IDEA REST interface: +#play.editor="http://localhost:63342/api/file/?file=%s&line=%s" + +## Internationalisation +# https://www.playframework.com/documentation/latest/JavaI18N +# https://www.playframework.com/documentation/latest/ScalaI18N +# ~~~~~ +# Play comes with its own i18n settings, which allow the user's preferred language +# to map through to internal messages, or allow the language to be stored in a cookie. +play.i18n { + # The application languages + langs = [ "en" ] + + # Whether the language cookie should be secure or not + #langCookieSecure = true + + # Whether the HTTP only attribute of the cookie should be set to true + #langCookieHttpOnly = true +} + +## Play HTTP settings +# ~~~~~ +play.http { + ## Router + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # Define the Router object to use for this application. + # This router will be looked up first when the application is starting up, + # so make sure this is the entry point. + # Furthermore, it's assumed your route file is named properly. + # So for an application router like `my.application.Router`, + # you may need to define a router file `conf/my.application.routes`. + # Default to Routes in the root package (aka "apps" folder) (and conf/routes) + #router = my.application.Router + + ## Action Creator + # https://www.playframework.com/documentation/latest/JavaActionCreator + # ~~~~~ + #actionCreator = null + + ## ErrorHandler + # https://www.playframework.com/documentation/latest/JavaRouting + # https://www.playframework.com/documentation/latest/ScalaRouting + # ~~~~~ + # If null, will attempt to load a class called ErrorHandler in the root package, + #errorHandler = null + + ## Filters + # https://www.playframework.com/documentation/latest/ScalaHttpFilters + # https://www.playframework.com/documentation/latest/JavaHttpFilters + # ~~~~~ + # Filters run code on every request. They can be used to perform + # common logic for all your actions, e.g. adding common headers. + # Defaults to "Filters" in the root package (aka "apps" folder) + # Alternatively you can explicitly register a class here. + #filters = my.application.Filters + + ## Session & Flash + # https://www.playframework.com/documentation/latest/JavaSessionFlash + # https://www.playframework.com/documentation/latest/ScalaSessionFlash + # ~~~~~ + session { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + + # Sets the max-age field of the cookie to 5 minutes. + # NOTE: this only sets when the browser will discard the cookie. Play will consider any + # cookie value with a valid signature to be a valid session forever. To implement a server side session timeout, + # you need to put a timestamp in the session and check it at regular intervals to possibly expire it. + #maxAge = 300 + + # Sets the domain on the session cookie. + #domain = "example.com" + } + + flash { + # Sets the cookie to be sent only over HTTPS. + #secure = true + + # Sets the cookie to be accessed only by the server. + #httpOnly = true + } +} + +## Netty Provider +# https://www.playframework.com/documentation/latest/SettingsNetty +# ~~~~~ +play.server.netty { + # Whether the Netty wire should be logged + #log.wire = true + + # If you run Play on Linux, you can use Netty's native socket transport + # for higher performance with less garbage. + #transport = "native" +} + +## WS (HTTP Client) +# https://www.playframework.com/documentation/latest/ScalaWS#Configuring-WS +# ~~~~~ +# The HTTP client primarily used for REST APIs. The default client can be +# configured directly, but you can also create different client instances +# with customized settings. You must enable this by adding to build.sbt: +# +# libraryDependencies += ws // or javaWs if using java +# +play.ws { + # Sets HTTP requests not to follow 302 requests + #followRedirects = false + + # Sets the maximum number of open HTTP connections for the client. + #ahc.maxConnectionsTotal = 50 + + ## WS SSL + # https://www.playframework.com/documentation/latest/WsSSL + # ~~~~~ + ssl { + # Configuring HTTPS with Play WS does not require programming. You can + # set up both trustManager and keyManager for mutual authentication, and + # turn on JSSE debugging in development with a reload. + #debug.handshake = true + #trustManager = { + # stores = [ + # { type = "JKS", path = "exampletrust.jks" } + # ] + #} + } +} + +## Cache +# https://www.playframework.com/documentation/latest/JavaCache +# https://www.playframework.com/documentation/latest/ScalaCache +# ~~~~~ +# Play comes with an integrated cache API that can reduce the operational +# overhead of repeated requests. You must enable this by adding to build.sbt: +# +# libraryDependencies += cache +# +play.cache { + # If you want to bind several caches, you can bind the individually + #bindCaches = ["db-cache", "user-cache", "session-cache"] +} + +## Filters +# https://www.playframework.com/documentation/latest/Filters +# ~~~~~ +# There are a number of built-in filters that can be enabled and configured +# to give Play greater security. You must enable this by adding to build.sbt: +# +# libraryDependencies += filters +# +play.filters { + ## CORS filter configuration + # https://www.playframework.com/documentation/latest/CorsFilter + # ~~~~~ + # CORS is a protocol that allows web applications to make requests from the browser + # across different domains. + # NOTE: You MUST apply the CORS configuration before the CSRF filter, as CSRF has + # dependencies on CORS settings. + cors { + # Filter paths by a whitelist of path prefixes + #pathPrefixes = ["/some/path", ...] + + # The allowed origins. If null, all origins are allowed. + #allowedOrigins = ["http://www.example.com"] + + # The allowed HTTP methods. If null, all methods are allowed + #allowedHttpMethods = ["GET", "POST"] + } + + ## CSRF Filter + # https://www.playframework.com/documentation/latest/ScalaCsrf#Applying-a-global-CSRF-filter + # https://www.playframework.com/documentation/latest/JavaCsrf#Applying-a-global-CSRF-filter + # ~~~~~ + # Play supports multiple methods for verifying that a request is not a CSRF request. + # The primary mechanism is a CSRF token. This token gets placed either in the query string + # or body of every form submitted, and also gets placed in the users session. + # Play then verifies that both tokens are present and match. + csrf { + # Sets the cookie to be sent only over HTTPS + #cookie.secure = true + + # Defaults to CSRFErrorHandler in the root package. + #errorHandler = MyCSRFErrorHandler + } + + ## Security headers filter configuration + # https://www.playframework.com/documentation/latest/SecurityHeaders + # ~~~~~ + # Defines security headers that prevent XSS attacks. + # If enabled, then all options are set to the below configuration by default: + headers { + # The X-Frame-Options header. If null, the header is not set. + #frameOptions = "DENY" + + # The X-XSS-Protection header. If null, the header is not set. + #xssProtection = "1; mode=block" + + # The X-Content-Type-Options header. If null, the header is not set. + #contentTypeOptions = "nosniff" + + # The X-Permitted-Cross-Domain-Policies header. If null, the header is not set. + #permittedCrossDomainPolicies = "master-only" + + # The Content-Security-Policy header. If null, the header is not set. + #contentSecurityPolicy = "default-src 'self'" + } + + ## Allowed hosts filter configuration + # https://www.playframework.com/documentation/latest/AllowedHostsFilter + # ~~~~~ + # Play provides a filter that lets you configure which hosts can access your application. + # This is useful to prevent cache poisoning attacks. + hosts { + # Allow requests to example.com, its subdomains, and localhost:9000. + #allowed = [".example.com", "localhost:9000"] + } +} + +## Evolutions +# https://www.playframework.com/documentation/latest/Evolutions +# ~~~~~ +# Evolutions allows database scripts to be automatically run on startup in dev mode +# for database migrations. You must enable this by adding to build.sbt: +# +# libraryDependencies += evolutions +# +play.evolutions { + # You can disable evolutions for a specific datasource if necessary + #db.default.enabled = false +} + +## Database Connection Pool +# https://www.playframework.com/documentation/latest/SettingsJDBC +# ~~~~~ +# Play doesn't require a JDBC database to run, but you can easily enable one. +# +# libraryDependencies += jdbc +# +play.db { + # The combination of these two settings results in "db.default" as the + # default JDBC pool: + #config = "db" + #default = "default" + + # Play uses HikariCP as the default connection pool. You can override + # settings by changing the prototype: + prototype { + # Sets a fixed JDBC connection pool size of 50 + #hikaricp.minimumIdle = 50 + #hikaricp.maximumPoolSize = 50 + } +} + +## JDBC Datasource +# https://www.playframework.com/documentation/latest/JavaDatabase +# https://www.playframework.com/documentation/latest/ScalaDatabase +# ~~~~~ +# Once JDBC datasource is set up, you can work with several different +# database options: +# +# Slick (Scala preferred option): https://www.playframework.com/documentation/latest/PlaySlick +# JPA (Java preferred option): https://playframework.com/documentation/latest/JavaJPA +# EBean: https://playframework.com/documentation/latest/JavaEbean +# Anorm: https://www.playframework.com/documentation/latest/ScalaAnorm +# +db { + # You can declare as many datasources as you want. + # By convention, the default datasource is named `default` + + # https://www.playframework.com/documentation/latest/Developing-with-the-H2-Database + #default.driver = org.h2.Driver + #default.url = "jdbc:h2:mem:play" + #default.username = sa + #default.password = "" + + # You can turn on SQL logging for any datasource + # https://www.playframework.com/documentation/latest/Highlights25#Logging-SQL-statements + #default.logSql=true +} diff --git a/routing-in-play/conf/logback.xml b/routing-in-play/conf/logback.xml new file mode 100644 index 0000000000..86ec12c0af --- /dev/null +++ b/routing-in-play/conf/logback.xml @@ -0,0 +1,41 @@ + + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/routing-in-play/conf/routes b/routing-in-play/conf/routes new file mode 100644 index 0000000000..f72d8a1a14 --- /dev/null +++ b/routing-in-play/conf/routes @@ -0,0 +1,7 @@ +GET / controllers.HomeController.index(author="Baeldung",id:Int?=1) +GET /:author controllers.HomeController.index(author,id:Int?=1) +GET /greet/:name/:age controllers.HomeController.greet(name,age:Integer) +GET /square/$num<[0-9]+> controllers.HomeController.squareMe(num:Long) +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) +GET /*data controllers.HomeController.introduceMe(data) diff --git a/routing-in-play/libexec/activator-launch-1.3.10.jar b/routing-in-play/libexec/activator-launch-1.3.10.jar new file mode 100644 index 0000000000..69050e7dec Binary files /dev/null and b/routing-in-play/libexec/activator-launch-1.3.10.jar differ diff --git a/routing-in-play/project/build.properties b/routing-in-play/project/build.properties new file mode 100644 index 0000000000..6d22e3f2d1 --- /dev/null +++ b/routing-in-play/project/build.properties @@ -0,0 +1,4 @@ +#Activator-generated Properties +#Fri Sep 30 14:25:10 EAT 2016 +template.uuid=26c759a5-daf0-4e02-bcfa-ac69725267c0 +sbt.version=0.13.11 diff --git a/routing-in-play/project/plugins.sbt b/routing-in-play/project/plugins.sbt new file mode 100644 index 0000000000..e8e7f602f7 --- /dev/null +++ b/routing-in-play/project/plugins.sbt @@ -0,0 +1,21 @@ +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.8") + +// Web plugins +addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.1.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.4") +addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.8") +addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.1") +addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0") +addSbtPlugin("org.irundaia.sbt" % "sbt-sassify" % "1.4.6") + +// Play enhancer - this automatically generates getters/setters for public fields +// and rewrites accessors of these fields to use the getters/setters. Remove this +// plugin if you prefer not to have this feature, or disable on a per project +// basis using disablePlugins(PlayEnhancer) in your build.sbt +addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.1.0") + +// Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using +// enablePlugins(PlayEbean). +// addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "3.0.2") diff --git a/routing-in-play/public/images/favicon.png b/routing-in-play/public/images/favicon.png new file mode 100644 index 0000000000..c7d92d2ae4 Binary files /dev/null and b/routing-in-play/public/images/favicon.png differ diff --git a/routing-in-play/public/javascripts/hello.js b/routing-in-play/public/javascripts/hello.js new file mode 100644 index 0000000000..02ee13c7ca --- /dev/null +++ b/routing-in-play/public/javascripts/hello.js @@ -0,0 +1,3 @@ +if (window.console) { + console.log("Welcome to your Play application's JavaScript!"); +} diff --git a/couchbase-sdk-spring-service/src/main/resources/application.properties b/routing-in-play/public/stylesheets/main.css similarity index 100% rename from couchbase-sdk-spring-service/src/main/resources/application.properties rename to routing-in-play/public/stylesheets/main.css diff --git a/routing-in-play/test/ApplicationTest.java b/routing-in-play/test/ApplicationTest.java new file mode 100644 index 0000000000..3d7c4875aa --- /dev/null +++ b/routing-in-play/test/ApplicationTest.java @@ -0,0 +1,45 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.*; + +import play.mvc.*; +import play.test.*; +import play.data.DynamicForm; +import play.data.validation.ValidationError; +import play.data.validation.Constraints.RequiredValidator; +import play.i18n.Lang; +import play.libs.F; +import play.libs.F.*; +import play.twirl.api.Content; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + + +/** + * + * Simple (JUnit) tests that can call all parts of a play app. + * If you are interested in mocking a whole application, see the wiki for more details. + * + */ +public class ApplicationTest { + + @Test + public void simpleCheck() { + int a = 1 + 1; + assertEquals(2, a); + } + + @Test + public void renderTemplate() { + Content html = views.html.index.render("Your new application is ready."); + assertEquals("text/html", html.contentType()); + assertTrue(html.body().contains("Your new application is ready.")); + } + + +} diff --git a/routing-in-play/test/IntegrationTest.java b/routing-in-play/test/IntegrationTest.java new file mode 100644 index 0000000000..c53c71e124 --- /dev/null +++ b/routing-in-play/test/IntegrationTest.java @@ -0,0 +1,25 @@ +import org.junit.*; + +import play.mvc.*; +import play.test.*; + +import static play.test.Helpers.*; +import static org.junit.Assert.*; + +import static org.fluentlenium.core.filter.FilterConstructor.*; + +public class IntegrationTest { + + /** + * add your integration test here + * in this example we just check if the welcome page is being shown + */ + @Test + public void test() { + running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { + browser.goTo("http://localhost:3333"); + assertTrue(browser.pageSource().contains("Your new application is ready.")); + }); + } + +} diff --git a/selenium-junit-testng/pom.xml b/selenium-junit-testng/pom.xml index c6bd2b042c..bf5a082fba 100644 --- a/selenium-junit-testng/pom.xml +++ b/selenium-junit-testng/pom.xml @@ -1,36 +1,48 @@ - - 4.0.0 - com.baeldung - selenium-junit-testng - 0.0.1-SNAPSHOT - - src - - - maven-compiler-plugin - 3.1 - - 1.8 - 1.8 - - - - - - - org.seleniumhq.selenium - selenium-java - 2.53.1 - - - junit - junit - 4.8.1 - - - org.testng - testng - 6.9.10 - - + + 4.0.0 + com.baeldung + selenium-junit-testng + 0.0.1-SNAPSHOT + + src + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + + + Test*.java + + + + + + + + org.seleniumhq.selenium + selenium-java + 2.53.1 + + + junit + junit + 4.8.1 + + + org.testng + testng + 6.9.10 + + \ No newline at end of file diff --git a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java index 6020b6bd2c..d8b248df81 100644 --- a/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java +++ b/selenium-junit-testng/src/main/java/com/baeldung/selenium/SeleniumExample.java @@ -6,9 +6,8 @@ import org.openqa.selenium.firefox.FirefoxDriver; public class SeleniumExample { private WebDriver webDriver; - private final String url = "http://www.baeldung.com/"; - private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; - + private String url = "http://www.baeldung.com/"; + public SeleniumExample() { webDriver = new FirefoxDriver(); webDriver.get(url); @@ -18,12 +17,8 @@ public class SeleniumExample { webDriver.close(); } - public String getActualTitle() { + public String getTitle() { return webDriver.getTitle(); } - public String getExpectedTitle() { - return expectedTitle; - } - } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java index 371f730eb9..f183a613e7 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java @@ -1,6 +1,7 @@ package test.java.com.baeldung.selenium.junit; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import main.java.com.baeldung.selenium.SeleniumExample; import org.junit.After; @@ -10,6 +11,7 @@ import org.junit.Test; public class TestSeleniumWithJUnit { private SeleniumExample seleniumExample; + private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; @Before public void setUp() { @@ -23,8 +25,8 @@ public class TestSeleniumWithJUnit { @Test public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String expectedTitle = seleniumExample.getExpectedTitle(); - String actualTitle = seleniumExample.getActualTitle(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); assertEquals(actualTitle, expectedTitle); } } diff --git a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java index ec10f9ca82..3c94f3d440 100644 --- a/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java +++ b/selenium-junit-testng/src/test/java/com/baeldung/selenium/testng/TestSeleniumWithTestNG.java @@ -1,6 +1,7 @@ package test.java.com.baeldung.selenium.testng; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import main.java.com.baeldung.selenium.SeleniumExample; import org.testng.annotations.AfterSuite; @@ -10,6 +11,7 @@ import org.testng.annotations.Test; public class TestSeleniumWithTestNG { private SeleniumExample seleniumExample; + private String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; @BeforeSuite public void setUp() { @@ -23,8 +25,8 @@ public class TestSeleniumWithTestNG { @Test public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String expectedTitle = seleniumExample.getExpectedTitle(); - String actualTitle = seleniumExample.getActualTitle(); + String actualTitle = seleniumExample.getTitle(); + assertNotNull(actualTitle); assertEquals(actualTitle, expectedTitle); } } diff --git a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java b/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java deleted file mode 100644 index dcdfafc4f1..0000000000 --- a/selenium-junit-testng/test/com/baeldun/selenium/testng/TestSeleniumWithTestNG.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldun.selenium.testng; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.firefox.FirefoxDriver; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; - -public class TestSeleniumWithTestNG { - - private WebDriver webDriver; - private final String url = "http://www.baeldung.com/"; - private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; - - @BeforeSuite - public void setUp() { - webDriver = new FirefoxDriver(); - webDriver.get(url); - } - - @AfterSuite - public void tearDown() { - webDriver.close(); - } - - @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitleReturned = webDriver.getTitle(); - assertNotNull(actualTitleReturned); - assertEquals(expectedTitle, actualTitleReturned); - } -} diff --git a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java b/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java deleted file mode 100644 index a7b36c4e4e..0000000000 --- a/selenium-junit-testng/test/com/baeldung/selenium/junit/TestSeleniumWithJUnit.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.selenium.junit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openqa.selenium.WebDriver; -import org.openqa.selenium.firefox.FirefoxDriver; - -public class TestSeleniumWithJUnit { - - private WebDriver webDriver; - private final String url = "http://www.baeldung.com/"; - private final String expectedTitle = "Baeldung | Java, Spring and Web Development tutorials"; - - @Before - public void setUp() { - webDriver = new FirefoxDriver(); - webDriver.get(url); - } - - @After - public void tearDown() { - webDriver.close(); - } - - @Test - public void whenPageIsLoaded_thenTitleIsAsPerExpectation() { - String actualTitleReturned = webDriver.getTitle(); - assertNotNull(actualTitleReturned); - assertEquals(expectedTitle, actualTitleReturned); - } -} diff --git a/spring-cloud-data-flow/README.MD b/spring-cloud-data-flow/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud-data-flow/README.MD @@ -0,0 +1 @@ + diff --git a/spring-cloud/README.md b/spring-cloud/README.md index 86f67cf26e..3e8cd21b82 100644 --- a/spring-cloud/README.md +++ b/spring-cloud/README.md @@ -1,8 +1,18 @@ ## The Module Holds Sources for the Following Articles - [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration) -- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) + + Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments. + + In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values. + - [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka) + + In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“. + + Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register. + - [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix) +- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 340923cbdf..2349613def 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -10,7 +10,7 @@ spring-cloud-config spring-cloud-eureka spring-cloud-hystrix - spring-cloud-integration + spring-cloud-bootstrap pom diff --git a/spring-cloud/spring-cloud-bootstrap/README.MD b/spring-cloud/spring-cloud-bootstrap/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud/spring-cloud-bootstrap/README.MD @@ -0,0 +1 @@ + diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties b/spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/discovery.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/discovery.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties b/spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/gateway.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/gateway.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties b/spring-cloud/spring-cloud-bootstrap/application-config/resource.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/application-config/resource.properties rename to spring-cloud/spring-cloud-bootstrap/application-config/resource.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/config/pom.xml b/spring-cloud/spring-cloud-bootstrap/config/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/pom.xml rename to spring-cloud/spring-cloud-bootstrap/config/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java b/spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java rename to spring-cloud/spring-cloud-bootstrap/config/src/main/java/com/baeldung/spring/cloud/integration/config/ConfigApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties b/spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/config/src/main/resources/application.properties rename to spring-cloud/spring-cloud-bootstrap/config/src/main/resources/application.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml b/spring-cloud/spring-cloud-bootstrap/discovery/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/pom.xml rename to spring-cloud/spring-cloud-bootstrap/discovery/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java rename to spring-cloud/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/integration/discovery/DiscoveryApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/discovery/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/discovery/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml b/spring-cloud/spring-cloud-bootstrap/gateway/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/pom.xml rename to spring-cloud/spring-cloud-bootstrap/gateway/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java rename to spring-cloud/spring-cloud-bootstrap/gateway/src/main/java/com/baeldung/spring/cloud/integration/resource/GatewayApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/gateway/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/gateway/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-integration/part-1/pom.xml b/spring-cloud/spring-cloud-bootstrap/pom.xml similarity index 85% rename from spring-cloud/spring-cloud-integration/part-1/pom.xml rename to spring-cloud/spring-cloud-bootstrap/pom.xml index 770e26bca2..c14c277d7f 100644 --- a/spring-cloud/spring-cloud-integration/part-1/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/pom.xml @@ -6,7 +6,7 @@ com.baeldung.spring.cloud - spring-cloud-integration + spring-cloud 1.0.0-SNAPSHOT @@ -17,9 +17,9 @@ resource - part-1 + + spring-cloud-integration 1.0.0-SNAPSHOT pom - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/pom.xml b/spring-cloud/spring-cloud-bootstrap/resource/pom.xml similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/pom.xml rename to spring-cloud/spring-cloud-bootstrap/resource/pom.xml diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java b/spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java rename to spring-cloud/spring-cloud-bootstrap/resource/src/main/java/com/baeldung/spring/cloud/integration/resource/ResourceApplication.java diff --git a/spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties b/spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties similarity index 100% rename from spring-cloud/spring-cloud-integration/part-1/resource/src/main/resources/bootstrap.properties rename to spring-cloud/spring-cloud-bootstrap/resource/src/main/resources/bootstrap.properties diff --git a/spring-cloud/spring-cloud-hystrix/README.MD b/spring-cloud/spring-cloud-hystrix/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-cloud/spring-cloud-hystrix/README.MD @@ -0,0 +1 @@ + diff --git a/spring-data-couchbase-2/README.md b/spring-data-couchbase-2/README.md index 3ed226fb33..2e56b25fef 100644 --- a/spring-data-couchbase-2/README.md +++ b/spring-data-couchbase-2/README.md @@ -3,6 +3,7 @@ ### Relevant Articles: - [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) - [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) +- [Multiple Buckets and Spatial View Queries in Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase-buckets-and-spatial-view-queries) ### Overview This Maven project contains the Java code for Spring Data Couchbase @@ -11,7 +12,7 @@ as described in the tutorials, as well as a unit/integration test for each service implementation. ### Working with the Code -The project was developed and tested using Java 7 nad 8 in the Eclipse-based +The project was developed and tested using Java 7 and 8 in the Eclipse-based Spring Source Toolkit (STS) and therefore should run fine in any recent version of Eclipse or another IDE of your choice that supports Java 7 or later. @@ -22,8 +23,15 @@ You can also build the project using Maven outside of any IDE: mvn clean install ``` +### Package Organization +Java classes for the first two tutorials listed above are in src/main/java in the package hierarchy +org.baeldung.spring.data.couchbase + +Java classes for the multiple-bucket tutorials are in src/main/java in the package hierarchy +org.baeldung.spring.data.couchbase2b + ### Running the tests -The following test classes are in src/test/java in the package +The test classes for the single-bucket tutorials are in src/test/java in the package org.baeldung.spring.data.couchbase.service: - PersonServiceTest (abstract) - PersonRepositoryTest (concrete) @@ -32,6 +40,12 @@ org.baeldung.spring.data.couchbase.service: - StudentRepositoryTest (concrete) - StudentTemplateServiceTest (concrete) +The concrete test classes for the multiple-bucket tutorial are in src/test/java in the package +org.baeldung.spring.data.couchbase2b.service: +- CampusRepositoryServiceImplTest +- PersonRepositoryServiceImplTest +- StudentRepositoryServiceImplTest + The concrete test classes may be run as JUnit tests from your IDE or using the Maven command line: ``` diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java similarity index 100% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/model/Campus.java diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java similarity index 92% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java index 22b2fb2735..2cf388f518 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/CampusRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/CampusRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.Set; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java similarity index 86% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java index 14b77759e3..e441bec6e4 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/PersonRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/PersonRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java similarity index 86% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java index 433964c872..2a960d37de 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/repos/StudentRepository.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/repos/StudentRepository.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.repos; +package org.baeldung.spring.data.couchbase2b.repos; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java similarity index 88% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java index e82c14cb87..d098c39011 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.Set; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java similarity index 80% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java index d12e59ba1f..612774fec9 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImpl.java @@ -1,20 +1,18 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase.repos.CampusRepository; +import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; import org.springframework.stereotype.Service; @Service -@Qualifier("CampusRepositoryService") -public class CampusRepositoryService implements CampusService { +public class CampusServiceImpl implements CampusService { private CampusRepository repo; @Autowired diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java similarity index 87% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java index a823908b01..c2c96ffb9c 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java similarity index 81% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java index 90cc36780a..f1ff513bff 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImpl.java @@ -1,20 +1,18 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.baeldung.spring.data.couchbase.model.Person; -import org.baeldung.spring.data.couchbase.repos.PersonRepository; +import org.baeldung.spring.data.couchbase2b.repos.PersonRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -@Qualifier("PersonRepositoryService") -public class PersonRepositoryService implements PersonService { - +public class PersonServiceImpl implements PersonService { + private PersonRepository repo; @Autowired public void setPersonRepository(PersonRepository repo) { diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java similarity index 87% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java index f483ef0fb6..5b83b403bb 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentService.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.List; diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java similarity index 81% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java rename to spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java index 58304afc1c..65400636cf 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryService.java +++ b/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImpl.java @@ -1,20 +1,18 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.baeldung.spring.data.couchbase.model.Student; -import org.baeldung.spring.data.couchbase.repos.StudentRepository; +import org.baeldung.spring.data.couchbase2b.repos.StudentRepository; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @Service -@Qualifier("StudentRepositoryService") -public class StudentRepositoryService implements StudentService { - +public class StudentServiceImpl implements StudentService { + private StudentRepository repo; @Autowired public void setStudentRepository(StudentRepository repo) { diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java similarity index 50% rename from spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java index c298ef0a61..0e2e8d5dd3 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/CustomTypeKeyCouchbaseConfig.java @@ -1,17 +1,11 @@ package org.baeldung.spring.data.couchbase; import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; -import org.springframework.data.couchbase.core.query.Consistency; -public class TestCouchbaseConfig extends MyCouchbaseConfig { +public class CustomTypeKeyCouchbaseConfig extends MyCouchbaseConfig { @Override public String typeKey() { return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE; } - - @Override - public Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; - } } diff --git a/spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java similarity index 100% rename from spring-data-couchbase-2/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java new file mode 100644 index 0000000000..b4a372487e --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/ReadYourOwnWritesCouchbaseConfig.java @@ -0,0 +1,11 @@ +package org.baeldung.spring.data.couchbase; + +import org.springframework.data.couchbase.core.query.Consistency; + +public class ReadYourOwnWritesCouchbaseConfig extends MyCouchbaseConfig { + + @Override + public Consistency getDefaultConsistency() { + return Consistency.READ_YOUR_OWN_WRITES; + } +} diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java index 3fabf7a11e..c3bf9f2138 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java @@ -83,13 +83,6 @@ public abstract class PersonServiceTest extends IntegrationTest { assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - @Test - public void whenFindingByFirstNameJohn_thenReturnsOnePersonNamedJohn() { - final String expectedFirstName = john; - final List resultList = personService.findByFirstName(expectedFirstName); - assertTrue(resultList.size() == 1); - } - private boolean resultContains(List resultList, Person person) { boolean found = false; for (final Person p : resultList) { diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java similarity index 86% rename from spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java index 8eeda08455..f419ba3499 100644 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/MyCouchbaseConfig.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketCouchbaseConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package org.baeldung.spring.data.couchbase2b; import java.util.Arrays; import java.util.List; @@ -17,9 +17,9 @@ import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import com.couchbase.client.java.Bucket; @Configuration -@EnableCouchbaseRepositories(basePackages={"org.baeldung.spring.data.couchbase"}) -public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { - +@EnableCouchbaseRepositories(basePackages = { "org.baeldung.spring.data.couchbase2b" }) +public class MultiBucketCouchbaseConfig extends AbstractCouchbaseConfiguration { + public static final List NODE_LIST = Arrays.asList("localhost"); public static final String DEFAULT_BUCKET_NAME = "baeldung"; public static final String DEFAULT_BUCKET_PASSWORD = ""; @@ -44,11 +44,13 @@ public class MyCouchbaseConfig extends AbstractCouchbaseConfiguration { return couchbaseCluster().openBucket("baeldung2", ""); } - @Bean + @Bean(name = "campusTemplate") public CouchbaseTemplate campusTemplate() throws Exception { CouchbaseTemplate template = new CouchbaseTemplate( - couchbaseClusterInfo(), campusBucket(), - mappingCouchbaseConverter(), translationService()); + couchbaseClusterInfo(), + campusBucket(), + mappingCouchbaseConverter(), + translationService()); template.setDefaultConsistency(getDefaultConsistency()); return template; } diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java similarity index 68% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java index ce2daa92cd..cb671dc469 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegationTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase; +package org.baeldung.spring.data.couchbase2b; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -7,7 +7,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { MyCouchbaseConfig.class, IntegrationTestConfig.class }) +@ContextConfiguration(classes = { MultiBucketCouchbaseConfig.class, MultiBucketIntegrationTestConfig.class }) @TestExecutionListeners(listeners = { DependencyInjectionTestExecutionListener.class }) -public abstract class IntegrationTest { +public abstract class MultiBucketIntegationTest { + } diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java new file mode 100644 index 0000000000..94a95b06bb --- /dev/null +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/MultiBucketIntegrationTestConfig.java @@ -0,0 +1,10 @@ +package org.baeldung.spring.data.couchbase2b; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan(basePackages = { "org.baeldung.spring.data.couchbase2b" }) +public class MultiBucketIntegrationTestConfig { + +} diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java similarity index 90% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java index 5a718f0807..7e24952e32 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/CampusRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/CampusServiceImplTest.java @@ -1,26 +1,27 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Set; import javax.annotation.PostConstruct; -import org.baeldung.spring.data.couchbase.IntegrationTest; import org.baeldung.spring.data.couchbase.model.Campus; -import org.baeldung.spring.data.couchbase.repos.CampusRepository; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; +import org.baeldung.spring.data.couchbase2b.repos.CampusRepository; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Point; -public class CampusRepositoryServiceTest extends IntegrationTest { +public class CampusServiceImplTest extends MultiBucketIntegationTest { @Autowired - @Qualifier("CampusRepositoryService") - private CampusRepositoryService campusService; + private CampusServiceImpl campusService; @Autowired private CampusRepository campusRepo; diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java similarity index 54% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java index 84b6f75d56..e1a880d9da 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/PersonRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/PersonServiceImplTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,14 +7,13 @@ import static org.junit.Assert.assertTrue; import java.util.List; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; import org.baeldung.spring.data.couchbase.model.Person; +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; @@ -22,37 +21,28 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class PersonRepositoryServiceTest extends IntegrationTest { +public class PersonServiceImplTest extends MultiBucketIntegationTest { - private static final String typeField = "_class"; - private static final String john = "John"; - private static final String smith = "Smith"; - private static final String johnSmithId = "person:" + john + ":" + smith; - private static final Person johnSmith = new Person(johnSmithId, john, smith); - private static final JsonObject jsonJohnSmith = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", john) - .put("lastName", smith) - .put("created", DateTime.now().getMillis()); + static final String typeField = "_class"; + static final String john = "John"; + static final String smith = "Smith"; + static final String johnSmithId = "person:" + john + ":" + smith; + static final Person johnSmith = new Person(johnSmithId, john, smith); + static final JsonObject jsonJohnSmith = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); + + static final String foo = "Foo"; + static final String bar = "Bar"; + static final String foobarId = "person:" + foo + ":" + bar; + static final Person foobar = new Person(foobarId, foo, bar); + static final JsonObject jsonFooBar = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); - private static final String foo = "Foo"; - private static final String bar = "Bar"; - private static final String foobarId = "person:" + foo + ":" + bar; - private static final Person foobar = new Person(foobarId, foo, bar); - private static final JsonObject jsonFooBar = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", foo) - .put("lastName", bar) - .put("created", DateTime.now().getMillis()); - @Autowired - @Qualifier("PersonRepositoryService") - private PersonService personService; - + private PersonServiceImpl personService; + @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.DEFAULT_BUCKET_NAME, MyCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); + final Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); + final Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith)); bucket.upsert(JsonDocument.create(foobarId, jsonFooBar)); bucket.close(); @@ -61,7 +51,7 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingPersonByJohnSmithId_thenReturnsJohnSmith() { - Person actualPerson = personService.findOne(johnSmithId); + final Person actualPerson = personService.findOne(johnSmithId); assertNotNull(actualPerson); assertNotNull(actualPerson.getCreated()); assertEquals(johnSmith, actualPerson); @@ -69,7 +59,7 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingAllPersons_thenReturnsTwoOrMorePersonsIncludingJohnSmithAndFooBar() { - List resultList = personService.findAll(); + final List resultList = personService.findAll(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(resultContains(resultList, johnSmith)); @@ -79,8 +69,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingByFirstNameJohn_thenReturnsOnlyPersonsNamedJohn() { - String expectedFirstName = john; - List resultList = personService.findByFirstName(expectedFirstName); + final String expectedFirstName = john; + final List resultList = personService.findByFirstName(expectedFirstName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedFirstName(resultList, expectedFirstName)); @@ -88,17 +78,17 @@ public class PersonRepositoryServiceTest extends IntegrationTest { @Test public void whenFindingByLastNameSmith_thenReturnsOnlyPersonsNamedSmith() { - String expectedLastName = smith; - List resultList = personService.findByLastName(expectedLastName); + final String expectedLastName = smith; + final List resultList = personService.findByLastName(expectedLastName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Person person) { boolean found = false; - for(Person p : resultList) { - if(p.equals(person)) { + for (final Person p : resultList) { + if (p.equals(person)) { found = true; break; } @@ -108,8 +98,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Person p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (final Person p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -119,8 +109,8 @@ public class PersonRepositoryServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Person p : resultList) { - if(p.getLastName().equals(lastName)) { + for (final Person p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java similarity index 77% rename from spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java rename to spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java index 166f01d754..220c2c3b00 100644 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/service/StudentRepositoryServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase2b/service/StudentServiceImplTest.java @@ -1,4 +1,4 @@ -package org.baeldung.spring.data.couchbase.service; +package org.baeldung.spring.data.couchbase2b.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -9,14 +9,13 @@ import java.util.List; import javax.validation.ConstraintViolationException; -import org.baeldung.spring.data.couchbase.IntegrationTest; -import org.baeldung.spring.data.couchbase.MyCouchbaseConfig; import org.baeldung.spring.data.couchbase.model.Student; +import org.baeldung.spring.data.couchbase2b.MultiBucketCouchbaseConfig; +import org.baeldung.spring.data.couchbase2b.MultiBucketIntegationTest; import org.joda.time.DateTime; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.Cluster; @@ -24,47 +23,46 @@ import com.couchbase.client.java.CouchbaseCluster; import com.couchbase.client.java.document.JsonDocument; import com.couchbase.client.java.document.json.JsonObject; -public class StudentRepositoryServiceTest extends IntegrationTest { +public class StudentServiceImplTest extends MultiBucketIntegationTest { - private static final String typeField = "_class"; - private static final String joe = "Joe"; - private static final String college = "College"; - private static final String joeCollegeId = "student:" + joe + ":" + college; - private static final DateTime joeCollegeDob = DateTime.now().minusYears(21); - private static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); - private static final JsonObject jsonJoeCollege = JsonObject.empty() + static final String typeField = "_class"; + static final String joe = "Joe"; + static final String college = "College"; + static final String joeCollegeId = "student:" + joe + ":" + college; + static final DateTime joeCollegeDob = DateTime.now().minusYears(21); + static final Student joeCollege = new Student(joeCollegeId, joe, college, joeCollegeDob); + static final JsonObject jsonJoeCollege = JsonObject.empty() .put(typeField, Student.class.getName()) .put("firstName", joe) .put("lastName", college) .put("created", DateTime.now().getMillis()) .put("version", 1); - private static final String judy = "Judy"; - private static final String jetson = "Jetson"; - private static final String judyJetsonId = "student:" + judy + ":" + jetson; - private static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); - private static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); - private static final JsonObject jsonJudyJetson = JsonObject.empty() + static final String judy = "Judy"; + static final String jetson = "Jetson"; + static final String judyJetsonId = "student:" + judy + ":" + jetson; + static final DateTime judyJetsonDob = DateTime.now().minusYears(19).minusMonths(5).minusDays(3); + static final Student judyJetson = new Student(judyJetsonId, judy, jetson, judyJetsonDob); + static final JsonObject jsonJudyJetson = JsonObject.empty() .put(typeField, Student.class.getName()) .put("firstName", judy) .put("lastName", jetson) .put("created", DateTime.now().getMillis()) .put("version", 1); - + @Autowired - @Qualifier("StudentRepositoryService") - private StudentService studentService; - + StudentServiceImpl studentService; + @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.DEFAULT_BUCKET_NAME, MyCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); + Cluster cluster = CouchbaseCluster.create(MultiBucketCouchbaseConfig.NODE_LIST); + Bucket bucket = cluster.openBucket(MultiBucketCouchbaseConfig.DEFAULT_BUCKET_NAME, MultiBucketCouchbaseConfig.DEFAULT_BUCKET_PASSWORD); bucket.upsert(JsonDocument.create(joeCollegeId, jsonJoeCollege)); bucket.upsert(JsonDocument.create(judyJetsonId, jsonJudyJetson)); bucket.close(); cluster.disconnect(); } - + @Test public void whenCreatingStudent_thenDocumentIsPersisted() { String firstName = "Eric"; @@ -134,7 +132,7 @@ public class StudentRepositoryServiceTest extends IntegrationTest { assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + private boolean resultContains(List resultList, Student student) { boolean found = false; for(Student p : resultList) { diff --git a/spring-data-couchbase-2b/README.md b/spring-data-couchbase-2b/README.md deleted file mode 100644 index 262962f58a..0000000000 --- a/spring-data-couchbase-2b/README.md +++ /dev/null @@ -1,36 +0,0 @@ -## Spring Data Couchbase Tutorial Project - -### Relevant Articles: -- [Spring Data Couchbase](http://www.baeldung.com/spring-data-couchbase) -- [Entity Validation, Query Consistency, and Optimistic Locking in Spring Data Couchbase](http://www.baeldung.com/entity-validation-locking-and-query-consistency-in-spring-data-couchbase) - -### Overview -This Maven project contains the Java code for Spring Data Couchbase -entities, repositories, and repository-based services -as described in the tutorials, as well as a unit/integration test -for each service implementation. - -### Working with the Code -The project was developed and tested using Java 7 and 8 in the Eclipse-based -Spring Source Toolkit (STS) and therefore should run fine in any -recent version of Eclipse or another IDE of your choice -that supports Java 7 or later. - -### Building the Project -You can also build the project using Maven outside of any IDE: -``` -mvn clean install -``` - -### Running the tests -The following test classes are in src/test/java in the package -org.baeldung.spring.data.couchbase.service: -- CampusRepositoryServiceTest -- PersonRepositoryServiceTest -- StudentRepositoryServiceTest - -These may be run as JUnit tests from your IDE -or using the Maven command line: -``` -mvn test -``` diff --git a/spring-data-couchbase-2b/pom.xml b/spring-data-couchbase-2b/pom.xml deleted file mode 100644 index 7d58f78ce5..0000000000 --- a/spring-data-couchbase-2b/pom.xml +++ /dev/null @@ -1,105 +0,0 @@ - - 4.0.0 - org.baeldung - spring-data-couchbase-2b - 0.1-SNAPSHOT - spring-data-couchbase-2b - jar - - - - - - org.springframework - spring-context - ${spring-framework.version} - - - org.springframework - spring-context-support - ${spring-framework.version} - - - org.springframework.data - spring-data-couchbase - ${spring-data-couchbase.version} - - - - - org.hibernate - hibernate-validator - ${hibernate-validator.version} - - - - joda-time - joda-time - ${joda-time.version} - - - - - org.slf4j - slf4j-api - ${org.slf4j.version} - compile - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${org.slf4j.version} - - - - - org.springframework - spring-test - ${spring-framework.version} - test - - - junit - junit - ${junit.version} - test - - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - - - 1.7 - UTF-8 - 4.2.4.RELEASE - 2.1.1.RELEASE - 5.2.4.Final - 2.9.2 - 1.1.3 - 1.7.12 - 4.11 - - - - diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java b/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java deleted file mode 100644 index 9220e157ed..0000000000 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Person.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Person { - - @Id - private String id; - @Field - @NotNull - private String firstName; - @Field - @NotNull - private String lastName; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - - public Person(String id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public String getId() { - return id; - } - public void setId(String 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 DateTime getCreated() { - return created; - } - public void setCreated(DateTime created) { - this.created = created; - } - public DateTime getUpdated() { - return updated; - } - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if(id != null) { - hash = hash * 31 + id.hashCode(); - } - if(firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if(lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; - Person other = (Person) obj; - return this.hashCode() == other.hashCode(); - } -} diff --git a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java b/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java deleted file mode 100644 index 9c266c2c62..0000000000 --- a/spring-data-couchbase-2b/src/main/java/org/baeldung/spring/data/couchbase/model/Student.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.baeldung.spring.data.couchbase.model; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; - -import org.joda.time.DateTime; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.couchbase.core.mapping.Document; - -import com.couchbase.client.java.repository.annotation.Field; - -@Document -public class Student { - private static final String NAME_REGEX = "^[a-zA-Z .'-]+$"; - - @Id - private String id; - @Field - @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) - private String firstName; - @Field - @NotNull - @Size(min=1, max=20) - @Pattern(regexp=NAME_REGEX) - private String lastName; - @Field - @Past - private DateTime dateOfBirth; - @Field - @NotNull - private DateTime created; - @Field - private DateTime updated; - @Version - private long version; - - public Student() {} - - public Student(String id, String firstName, String lastName, DateTime dateOfBirth) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - this.dateOfBirth = dateOfBirth; - } - - public String getId() { - return id; - } - public void setId(String 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 DateTime getDateOfBirth() { - return dateOfBirth; - } - public void setDateOfBirth(DateTime dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - public DateTime getCreated() { - return created; - } - public void setCreated(DateTime created) { - this.created = created; - } - public DateTime getUpdated() { - return updated; - } - public void setUpdated(DateTime updated) { - this.updated = updated; - } - - @Override - public int hashCode() { - int hash = 1; - if(id != null) { - hash = hash * 31 + id.hashCode(); - } - if(firstName != null) { - hash = hash * 31 + firstName.hashCode(); - } - if(lastName != null) { - hash = hash * 31 + lastName.hashCode(); - } - if(dateOfBirth != null) { - hash = hash * 31 + dateOfBirth.hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object obj) { - if((obj == null) || (obj.getClass() != this.getClass())) return false; - if(obj == this) return true; - Student other = (Student) obj; - return this.hashCode() == other.hashCode(); - } -} \ No newline at end of file diff --git a/spring-data-couchbase-2b/src/main/resources/logback.xml b/spring-data-couchbase-2b/src/main/resources/logback.xml deleted file mode 100644 index d9067fd1da..0000000000 --- a/spring-data-couchbase-2b/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-data-couchbase-2b/src/site/site.xml b/spring-data-couchbase-2b/src/site/site.xml deleted file mode 100644 index dda96feecd..0000000000 --- a/spring-data-couchbase-2b/src/site/site.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - Spring Sample: ${project.name} - index.html - - - - org.springframework.maven.skins - maven-spring-skin - 1.0.5 - - - - - - - - -

- - - - diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java b/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java deleted file mode 100644 index 6f040c34db..0000000000 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/IntegrationTestConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.baeldung.spring.data.couchbase; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan(basePackages = "org.baeldung.spring.data.couchbase") -public class IntegrationTestConfig { -} diff --git a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java b/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java deleted file mode 100644 index c298ef0a61..0000000000 --- a/spring-data-couchbase-2b/src/test/java/org/baeldung/spring/data/couchbase/TestCouchbaseConfig.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.baeldung.spring.data.couchbase; - -import org.springframework.data.couchbase.core.convert.MappingCouchbaseConverter; -import org.springframework.data.couchbase.core.query.Consistency; - -public class TestCouchbaseConfig extends MyCouchbaseConfig { - - @Override - public String typeKey() { - return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE; - } - - @Override - public Consistency getDefaultConsistency() { - return Consistency.READ_YOUR_OWN_WRITES; - } -} diff --git a/spring-data-couchbase-2b/src/test/resources/logback.xml b/spring-data-couchbase-2b/src/test/resources/logback.xml deleted file mode 100644 index d9067fd1da..0000000000 --- a/spring-data-couchbase-2b/src/test/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-jms/pom.xml b/spring-jms/pom.xml new file mode 100644 index 0000000000..8f78469989 --- /dev/null +++ b/spring-jms/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + com.baeldung + spring-jms + 0.0.1-SNAPSHOT + war + spring-jms + Introduction to Spring JMS + + + 4.3.2.RELEASE + 5.12.0 + + + + + + org.springframework + spring-jms + ${springframework.version} + + + + org.apache.activemq + activemq-all + ${activemq.version} + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-jms + false + + + + + spring-jms + + \ No newline at end of file diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java new file mode 100644 index 0000000000..4da02907a9 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/Employee.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.jms; + +public class Employee { + private String name; + private Integer age; + + public Employee(String name, Integer age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public Integer getAge() { + return age; + } + + public String toString() { + return "Person: name(" + name + "), age(" + age + ")"; + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java new file mode 100644 index 0000000000..a243bc1390 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJMSExample.java @@ -0,0 +1,16 @@ +package com.baeldung.spring.jms; + +import org.apache.activemq.broker.BrokerFactory; +import org.apache.activemq.broker.BrokerService; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.net.URI; + +public class SampleJMSExample { + public static void main(String[] args) throws Exception { + BrokerService broker = BrokerFactory.createBroker(new URI("broker:(tcp://localhost:61616)")); + broker.start(); + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); + + } +} diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java new file mode 100644 index 0000000000..865a1d4747 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleJmsMessageSender.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.jms; + +import org.springframework.jms.core.JmsTemplate; +import org.springframework.jms.core.MessageCreator; + +import javax.jms.*; + +public class SampleJmsMessageSender { + + private JmsTemplate jmsTemplate; + private Queue queue; + + public void createJmsTemplate(ConnectionFactory cf) { + this.jmsTemplate = new JmsTemplate(cf); + } + + public void setQueue(Queue queue) { + this.queue = queue; + } + + public void simpleSend() { + this.jmsTemplate.send(this.queue, new MessageCreator() { + public Message createMessage(Session session) throws JMSException { + return session.createTextMessage("hello queue world"); + } + }); + } +} \ No newline at end of file diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java new file mode 100644 index 0000000000..0320870d88 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleListener.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.jms; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.MessageListener; +import javax.jms.TextMessage; + +public class SampleListener implements MessageListener { + + private String textMessage; + + public void onMessage(Message message) { + if (message instanceof TextMessage) { + try { + textMessage = ((TextMessage) message).getText(); + } catch (JMSException ex) { + throw new RuntimeException(ex); + } + } else { + throw new IllegalArgumentException("Message Error"); + } + } +} \ No newline at end of file diff --git a/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java new file mode 100644 index 0000000000..6cfc588f13 --- /dev/null +++ b/spring-jms/src/main/java/com/baeldung/spring/jms/SampleMessageConverter.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.jms; + +import org.springframework.jms.support.converter.MessageConversionException; +import org.springframework.jms.support.converter.MessageConverter; + +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.Session; + +public class SampleMessageConverter implements MessageConverter { + + public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { + Employee person = (Employee) object; + MapMessage message = session.createMapMessage(); + message.setString("name", person.getName()); + message.setInt("age", person.getAge()); + return message; + } + + public Object fromMessage(Message message) throws JMSException, MessageConversionException { + MapMessage mapMessage = (MapMessage) message; + return new Employee(mapMessage.getString("name"), mapMessage.getInt("age")); + } + +} diff --git a/spring-jms/src/main/resources/applicationContext.xml b/spring-jms/src/main/resources/applicationContext.xml new file mode 100644 index 0000000000..c15289763f --- /dev/null +++ b/spring-jms/src/main/resources/applicationContext.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index 098afffba4..7361d16b33 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -250,7 +250,7 @@ 1.7.21 1.1.5 - + 5.2.2.Final @@ -263,6 +263,7 @@ 4.4.1 4.5 2.9.0 + 2.23 3.5.1 2.6 @@ -274,4 +275,5 @@ 1.8.7 - \ No newline at end of file + + diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java new file mode 100644 index 0000000000..cfc73aeabe --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/MessageController.java @@ -0,0 +1,24 @@ +package com.baeldung.web.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/message") +public class MessageController { + + @RequestMapping(value = "/showForm", method = RequestMethod.GET) + public String showForm() { + return "message"; + } + + @RequestMapping(value = "/processForm", method = RequestMethod.POST) + public String processForm(@RequestParam("message") final String message, final Model model) { + model.addAttribute("message", message); + return "message"; + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java new file mode 100644 index 0000000000..58e5f9829b --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.htmlunit; + +import org.junit.Assert; +import org.junit.Test; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitAndJUnitTest { + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient webClient = new WebClient()) { + + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java new file mode 100644 index 0000000000..dcc7555ae2 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringTest.java @@ -0,0 +1,79 @@ +package com.baeldung.htmlunit; + +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +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 org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder; +import org.springframework.web.context.WebApplicationContext; + +import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlForm; +import com.gargoylesoftware.htmlunit.html.HtmlPage; +import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; +import com.gargoylesoftware.htmlunit.html.HtmlTextInput; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { TestConfig.class }) +public class HtmlUnitAndSpringTest { + + @Autowired + private WebApplicationContext wac; + + private WebClient webClient; + + @Before + public void setup() { + webClient = MockMvcWebClientBuilder.webAppContextSetup(wac).build(); + } + + @Test + @Ignore + public void givenAMessage_whenSent_thenItShows() { + final String text = "Hello world!"; + HtmlPage page; + + try { + + page = webClient.getPage("http://localhost/message/showForm"); + System.out.println(page.asXml()); + + final HtmlTextInput messageText = page.getHtmlElementById("message"); + messageText.setValueAttribute(text); + + final HtmlForm form = page.getForms().get(0); + final HtmlSubmitInput submit = form.getOneHtmlElementByAttribute("input", "type", "submit"); + final HtmlPage newPage = submit.click(); + + final String receivedText = newPage.getHtmlElementById("received").getTextContent(); + + Assert.assertEquals(receivedText, text); + System.out.println(newPage.asXml()); + + } catch (FailingHttpStatusCodeException | IOException e) { + e.printStackTrace(); + } + + } + + @Test + public void givenAClient_whenEnteringBaeldung_thenPageTitleIsCorrect() throws Exception { + try (final WebClient client = new WebClient()) { + + webClient.getOptions().setThrowExceptionOnScriptError(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/"); + Assert.assertEquals("Baeldung | Java, Spring and Web Development tutorials", page.getTitleText()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java new file mode 100644 index 0000000000..16d18717e6 --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScraping.java @@ -0,0 +1,40 @@ +package com.baeldung.htmlunit; + +import java.util.List; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.html.HtmlAnchor; +import com.gargoylesoftware.htmlunit.html.HtmlHeading1; +import com.gargoylesoftware.htmlunit.html.HtmlHeading2; +import com.gargoylesoftware.htmlunit.html.HtmlPage; + +public class HtmlUnitWebScraping { + + public static void main(final String[] args) throws Exception { + try (final WebClient webClient = new WebClient()) { + + webClient.getOptions().setCssEnabled(false); + webClient.getOptions().setJavaScriptEnabled(false); + + final HtmlPage page = webClient.getPage("http://www.baeldung.com/full_archive"); + final HtmlAnchor latestPostLink = (HtmlAnchor) page.getByXPath("(//ul[@class='car-monthlisting']/li)[1]/a").get(0); + + System.out.println("Entering: " + latestPostLink.getHrefAttribute()); + + final HtmlPage postPage = latestPostLink.click(); + + final HtmlHeading1 heading1 = (HtmlHeading1) postPage.getByXPath("//h1").get(0); + System.out.println("Title: " + heading1.getTextContent()); + + final List headings2 = (List) postPage.getByXPath("//h2"); + + final StringBuilder sb = new StringBuilder(heading1.getTextContent()); + for (final HtmlHeading2 h2 : headings2) { + sb.append("\n").append(h2.getTextContent()); + } + + System.out.println(sb.toString()); + } + } + +} diff --git a/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java new file mode 100644 index 0000000000..1357310b1f --- /dev/null +++ b/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.htmlunit; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.thymeleaf.spring4.SpringTemplateEngine; +import org.thymeleaf.spring4.view.ThymeleafViewResolver; +import org.thymeleaf.templateresolver.ServletContextTemplateResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = { "com.baeldung.web.controller" }) +public class TestConfig extends WebMvcConfigurerAdapter { + + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } + + @Bean + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } + + @Bean + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + return templateEngine; + } + +} diff --git a/spring-mvc-tiles/pom.xml b/spring-mvc-tiles/pom.xml new file mode 100644 index 0000000000..1a72549e70 --- /dev/null +++ b/spring-mvc-tiles/pom.xml @@ -0,0 +1,85 @@ + + 4.0.0 + com.baeldung + spring-mvc-tiles + 0.0.1-SNAPSHOT + war + spring-mvc-tiles + Integrating Spring MVC with Apache Tiles + + + 4.3.2.RELEASE + 3.0.5 + + + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + + org.apache.tiles + tiles-jsp + ${apachetiles.version} + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + javax.servlet.jsp + javax.servlet.jsp-api + 2.3.1 + + + javax.servlet + jstl + 1.2 + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + src/main/webapp + spring-mvc-tiles + false + + + + + spring-mvc-tiles + + diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java new file mode 100644 index 0000000000..d2e90a4f53 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationConfiguration.java @@ -0,0 +1,47 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.tiles3.TilesConfigurer; +import org.springframework.web.servlet.view.tiles3.TilesViewResolver; + +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "com.baeldung.tiles.springmvc") +public class ApplicationConfiguration extends WebMvcConfigurerAdapter { + + /** + * Configure TilesConfigurer. + */ + @Bean + public TilesConfigurer tilesConfigurer() { + TilesConfigurer tilesConfigurer = new TilesConfigurer(); + tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/views/**/tiles.xml" }); + tilesConfigurer.setCheckRefresh(true); + return tilesConfigurer; + } + + /** + * Configure ViewResolvers to deliver views. + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + TilesViewResolver viewResolver = new TilesViewResolver(); + registry.viewResolver(viewResolver); + } + + /** + * Configure ResourceHandlers to serve static resources + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/static/**").addResourceLocations("/static/"); + } + +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java new file mode 100644 index 0000000000..1a348d1c26 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationController.java @@ -0,0 +1,26 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +@RequestMapping("/") +public class ApplicationController { + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + public String homePage(ModelMap model) { + return "home"; + } + + @RequestMapping(value = { "/apachetiles" }, method = RequestMethod.GET) + public String productsPage(ModelMap model) { + return "apachetiles"; + } + + @RequestMapping(value = { "/springmvc" }, method = RequestMethod.GET) + public String contactUsPage(ModelMap model) { + return "springmvc"; + } +} diff --git a/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java new file mode 100644 index 0000000000..79583dbe83 --- /dev/null +++ b/spring-mvc-tiles/src/main/java/com/baeldung/tiles/springmvc/ApplicationInitializer.java @@ -0,0 +1,22 @@ +package com.baeldung.tiles.springmvc; + +import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; + +public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return new Class[] { ApplicationConfiguration.class }; + } + + @Override + protected Class[] getServletConfigClasses() { + return null; + } + + @Override + protected String[] getServletMappings() { + return new String[] { "/" }; + } + +} diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp new file mode 100644 index 0000000000..9936957c04 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/apachetiles.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Apache Tiles + + +

Tiles with Spring MVC Demo

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp new file mode 100644 index 0000000000..b501d4968e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/home.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Home + + +

Welcome to Apache Tiles integration with Spring MVC

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp new file mode 100644 index 0000000000..209b1004de --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/pages/springmvc.jsp @@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + +Spring MVC + + +

Spring MVC configured to work with Apache Tiles

+ + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp new file mode 100644 index 0000000000..2370ad4ab1 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/layouts/defaultLayout.jsp @@ -0,0 +1,25 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ page isELIgnored="false"%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> + + + + + +<tiles:getAsString name="title" /> + + + + +
+ + +
+ +
+ +
+ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp new file mode 100644 index 0000000000..3849cc5230 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultFooter.jsp @@ -0,0 +1,2 @@ + +
copyright © Baeldung
diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp new file mode 100644 index 0000000000..8a878c857d --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultHeader.jsp @@ -0,0 +1,3 @@ +
+

Welcome to Spring MVC integration with Apache Tiles

+
\ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp new file mode 100644 index 0000000000..2c91eace85 --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/templates/defaultMenu.jsp @@ -0,0 +1,8 @@ + diff --git a/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml new file mode 100644 index 0000000000..789fbd809a --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/WEB-INF/views/tiles/tiles.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-mvc-tiles/src/main/webapp/static/css/app.css b/spring-mvc-tiles/src/main/webapp/static/css/app.css new file mode 100644 index 0000000000..9976e5406e --- /dev/null +++ b/spring-mvc-tiles/src/main/webapp/static/css/app.css @@ -0,0 +1,36 @@ +.flex-container { + display: -webkit-flex; + display: flex; + -webkit-flex-flow: row wrap; + flex-flow: row wrap; + text-align: center; +} + +.flex-container > * { + padding: 15px; + -webkit-flex: 1 100%; + flex: 1 100%; +} + +.article { + text-align: left; +} + +header {background: black;color:white;} +footer {background: #aaa;color:white;} +.nav {background:#eee;} + +.nav ul { + list-style-type: none; + padding: 0; +} + +.nav ul a { + text-decoration: none; +} + +@media all and (min-width: 768px) { + .nav {text-align:left;-webkit-flex: 1 auto;flex:1 auto;-webkit-order:1;order:1;} + .article {-webkit-flex:5 0px;flex:5 0px;-webkit-order:2;order:2;} + footer {-webkit-order:3;order:3;} +} \ No newline at end of file diff --git a/spring-mvc-web-vs-initializer/README.MD b/spring-mvc-web-vs-initializer/README.MD new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-mvc-web-vs-initializer/README.MD @@ -0,0 +1 @@ + diff --git a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java index cfde4b23b1..f3e3738bfe 100644 --- a/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java +++ b/spring-rest/src/main/java/org/baeldung/web/controller/ItemController.java @@ -14,20 +14,26 @@ import com.fasterxml.jackson.annotation.JsonView; @RestController public class ItemController { - @JsonView(Views.Public.class) - @RequestMapping("/items/{id}") - public Item getItemPublic(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Public.class) + @RequestMapping("/items/{id}") + public Item getItemPublic(@PathVariable final int id) { + return ItemManager.getById(id); + } - @JsonView(Views.Internal.class) - @RequestMapping("/items/internal/{id}") - public Item getItemInternal(@PathVariable final int id) { - return ItemManager.getById(id); - } + @JsonView(Views.Internal.class) + @RequestMapping("/items/internal/{id}") + public Item getItemInternal(@PathVariable final int id) { + return ItemManager.getById(id); + } - @RequestMapping("/date") - public Date getCurrentDate() { - return new Date(); - } + @RequestMapping("/date") + public Date getCurrentDate() throws Exception { + return new Date(); + } + + @RequestMapping("/delay/{seconds}") + public void getCurrentTime(@PathVariable final int seconds) throws Exception { + + Thread.sleep(seconds * 1000); + } } \ No newline at end of file diff --git a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java index 2baf88a62d..c662c32738 100644 --- a/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java +++ b/spring-security-mvc-persisted-remember-me/src/main/java/org/baeldung/service/MyUserDetailsService.java @@ -1,11 +1,5 @@ package org.baeldung.service; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.baeldung.security.SecurityRole; @@ -17,9 +11,9 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -/** - * User Details Service - hard coded to two users for the example. - */ +import java.util.*; +import java.util.stream.Collectors; + @Service public class MyUserDetailsService implements UserDetailsService { @@ -28,24 +22,19 @@ public class MyUserDetailsService implements UserDetailsService { private final Map availableUsers = new HashMap(); public MyUserDetailsService() { - populateDemoUsers(); - } - // - @Override public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { logger.info("Load user by username " + username); final UserDetails user = availableUsers.get(username); if (user == null) { - throw new UsernameNotFoundException("Username not found"); - } else { - return availableUsers.get(username); + throw new UsernameNotFoundException(username); } + return user; } /** @@ -59,24 +48,13 @@ public class MyUserDetailsService implements UserDetailsService { availableUsers.put("admin", createUser("admin", "password", Arrays.asList(SecurityRole.ROLE_ADMIN))); } - /** - * Create a demo User. - * - * @param username - * Username - * @param password - * Password - * @param roles - * Role names user is assigned to - * @return User - */ private User createUser(final String username, final String password, final List roles) { logger.info("Create user " + username); - final List authorities = new ArrayList(); - for (final SecurityRole role : roles) { - authorities.add(new SimpleGrantedAuthority(role.toString())); - } + final List authorities = roles.stream() + .map(role -> new SimpleGrantedAuthority(role.toString())) + .collect(Collectors.toList()); + return new User(username, password, true, true, true, true, authorities); } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java index 547d6deee9..444b780673 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/config/WebMVCConfig.java @@ -20,6 +20,8 @@ import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ITemplateResolver; import com.baeldung.thymeleaf.formatter.NameFormatter; +import com.baeldung.thymeleaf.utils.ArrayUtil; + @Configuration @EnableWebMvc @@ -37,30 +39,67 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application } @Bean - public ViewResolver viewResolver() { + public ViewResolver htmlViewResolver() { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); - resolver.setTemplateEngine(templateEngine()); + resolver.setTemplateEngine(templateEngine(htmlTemplateResolver())); + resolver.setContentType("text/html"); resolver.setCharacterEncoding("UTF-8"); - resolver.setOrder(1); + resolver.setViewNames(ArrayUtil.array("*.html")); return resolver; } - + @Bean - public TemplateEngine templateEngine() { - SpringTemplateEngine engine = new SpringTemplateEngine(); - engine.setEnableSpringELCompiler(true); - engine.setTemplateResolver(templateResolver()); - return engine; - } + public ViewResolver javascriptViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver())); + resolver.setContentType("application/javascript"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.js")); + return resolver; + } + + @Bean + public ViewResolver plainViewResolver() { + ThymeleafViewResolver resolver = new ThymeleafViewResolver(); + resolver.setTemplateEngine(templateEngine(plainTemplateResolver())); + resolver.setContentType("text/plain"); + resolver.setCharacterEncoding("UTF-8"); + resolver.setViewNames(ArrayUtil.array("*.txt")); + return resolver; + } - private ITemplateResolver templateResolver() { - SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); - resolver.setApplicationContext(applicationContext); - resolver.setPrefix("/WEB-INF/views/"); - resolver.setSuffix(".html"); - resolver.setTemplateMode(TemplateMode.HTML); - return resolver; - } + private TemplateEngine templateEngine(ITemplateResolver templateResolver) { + SpringTemplateEngine engine = new SpringTemplateEngine(); + engine.setTemplateResolver(templateResolver); + return engine; + } + + private ITemplateResolver htmlTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/views/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.HTML); + return resolver; + } + + private ITemplateResolver javascriptTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/js/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.JAVASCRIPT); + return resolver; + } + + private ITemplateResolver plainTemplateResolver() { + SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); + resolver.setApplicationContext(applicationContext); + resolver.setPrefix("/WEB-INF/txt/"); + resolver.setCacheable(false); + resolver.setTemplateMode(TemplateMode.TEXT); + return resolver; + } @Bean @Description("Spring Message Resolver") diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java new file mode 100644 index 0000000000..f30b9b2078 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsController.java @@ -0,0 +1,33 @@ +package com.baeldung.thymeleaf.controller; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashSet; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * Controller to test expression utility objects: dates, + * + */ +@Controller +public class ExpressionUtilityObjectsController { + + @RequestMapping(value = "/objects", method = RequestMethod.GET) + public String getDates(Model model) { + model.addAttribute("date", new Date()); + model.addAttribute("calendar", Calendar.getInstance()); + model.addAttribute("num", Math.random() * 10); + model.addAttribute("string", "new text"); + model.addAttribute("emptyString", ""); + model.addAttribute("nullString", null); + model.addAttribute("array", new int[] { 1, 3, 4, 5 }); + model.addAttribute("set", new HashSet(Arrays.asList(1, 3, 8))); + return "objects.html"; + } + +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java index a28d059acc..f1a394cac4 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/HomeController.java @@ -21,7 +21,7 @@ public class HomeController { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault()); model.addAttribute("serverTime", dateFormat.format(new Date())); - return "home"; + return "home.html"; } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java new file mode 100644 index 0000000000..9e3f14ac8e --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/InliningController.java @@ -0,0 +1,33 @@ +package com.baeldung.thymeleaf.controller; + +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.baeldung.thymeleaf.utils.StudentUtils; + +@Controller +public class InliningController { + + @RequestMapping(value = "/html", method = RequestMethod.GET) + public String getExampleHTML(Model model) { + model.addAttribute("title", "Baeldung"); + model.addAttribute("description", "Thymeleaf tutorial"); + return "inliningExample.html"; + } + + @RequestMapping(value = "/js", method = RequestMethod.GET) + public String getExampleJS(Model model) { + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentCheck.js"; + } + + @RequestMapping(value = "/plain", method = RequestMethod.GET) + public String getExamplePlain(Model model) { + model.addAttribute("username", SecurityContextHolder.getContext().getAuthentication().getName()); + model.addAttribute("students", StudentUtils.buildStudents()); + return "studentsList.txt"; + } +} diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java index da34b2d7b0..1f40046caa 100644 --- a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/controller/StudentController.java @@ -1,11 +1,9 @@ package com.baeldung.thymeleaf.controller; -import java.util.ArrayList; import java.util.List; import javax.validation.Valid; -import com.baeldung.thymeleaf.model.Student; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; @@ -13,6 +11,9 @@ import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import com.baeldung.thymeleaf.model.Student; +import com.baeldung.thymeleaf.utils.StudentUtils; + /** * Handles requests for the student model. * @@ -20,50 +21,30 @@ import org.springframework.web.bind.annotation.RequestMethod; @Controller public class StudentController { - @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) - public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { - if (!errors.hasErrors()) { - // get mock objects - List students = buildStudents(); - // add current student - students.add(student); - model.addAttribute("students", students); - } - return ((errors.hasErrors()) ? "addStudent" : "listStudents"); - } + @RequestMapping(value = "/saveStudent", method = RequestMethod.POST) + public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) { + if (!errors.hasErrors()) { + // get mock objects + List students = StudentUtils.buildStudents(); + // add current student + students.add(student); + model.addAttribute("students", students); + } + return ((errors.hasErrors()) ? "addStudent.html" : "listStudents.html"); + } - @RequestMapping(value = "/addStudent", method = RequestMethod.GET) - public String addStudent(Model model) { - model.addAttribute("student", new Student()); - return "addStudent"; - } + @RequestMapping(value = "/addStudent", method = RequestMethod.GET) + public String addStudent(Model model) { + model.addAttribute("student", new Student()); + return "addStudent.html"; + } - @RequestMapping(value = "/listStudents", method = RequestMethod.GET) - public String listStudent(Model model) { + @RequestMapping(value = "/listStudents", method = RequestMethod.GET) + public String listStudent(Model model) { - model.addAttribute("students", buildStudents()); + model.addAttribute("students", StudentUtils.buildStudents()); - return "listStudents"; - } + return "listStudents.html"; + } - private List buildStudents() { - List students = new ArrayList(); - - Student student1 = new Student(); - student1.setId(1001); - student1.setName("John Smith"); - student1.setGender('M'); - student1.setPercentage(Float.valueOf("80.45")); - - students.add(student1); - - Student student2 = new Student(); - student2.setId(1002); - student2.setName("Jane Williams"); - student2.setGender('F'); - student2.setPercentage(Float.valueOf("60.25")); - - students.add(student2); - return students; - } } diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java new file mode 100644 index 0000000000..d85c70c1b7 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/ArrayUtil.java @@ -0,0 +1,8 @@ +package com.baeldung.thymeleaf.utils; + +public class ArrayUtil { + + public static String[] array(String... args) { + return args; + } +} \ No newline at end of file diff --git a/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java new file mode 100644 index 0000000000..f7ed254641 --- /dev/null +++ b/spring-thymeleaf/src/main/java/com/baeldung/thymeleaf/utils/StudentUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.thymeleaf.utils; + +import java.util.ArrayList; +import java.util.List; + +import com.baeldung.thymeleaf.model.Student; + +public class StudentUtils { + + private static List students = new ArrayList(); + + public static List buildStudents() { + if (students.isEmpty()){ + Student student1 = new Student(); + student1.setId(1001); + student1.setName("John Smith"); + student1.setGender('M'); + student1.setPercentage(Float.valueOf("80.45")); + + students.add(student1); + + Student student2 = new Student(); + student2.setId(1002); + student2.setName("Jane Williams"); + student2.setGender('F'); + student2.setPercentage(Float.valueOf("60.25")); + + students.add(student2); + } + + return students; + } + +} diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js new file mode 100644 index 0000000000..625e0b37e5 --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/js/studentCheck.js @@ -0,0 +1,2 @@ +var count = [[${students.size()}]]; +alert("Number of students in group: " + count); diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt new file mode 100644 index 0000000000..b27796c6ab --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/txt/studentsList.txt @@ -0,0 +1,8 @@ +Dear [(${username})], + +This is the list of our students: +[# th:each="s : ${students}"] + - [(${s.name})]. ID: [(${s.id})] +[/] +Thanks, +The Baeldung University \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html new file mode 100644 index 0000000000..cd20746c3a --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/inliningExample.html @@ -0,0 +1,12 @@ + + + + +Inlining example + + +

Title of tutorial: [[${title}]]

+

Description: [(${description})]

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html index c25de9eb17..a894e41e88 100644 --- a/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/listStudents.html @@ -4,6 +4,15 @@ Student List + +

Student List

diff --git a/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html b/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html new file mode 100644 index 0000000000..b2a23a7c0f --- /dev/null +++ b/spring-thymeleaf/src/main/webapp/WEB-INF/views/objects.html @@ -0,0 +1,47 @@ + + + + +Expression utility objects + + +

Date expression utility

+

+

+

+

+

+ +

Calendar expression utility

+

+

+

+

+

+ +

Numbers expression utility

+

+

+

+ +

+

+ +

+ +

Calendar expression utility

+

+

+

+

+

+

+ +

Aggregates expression utility

+

+

+

+

+ + \ No newline at end of file diff --git a/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java new file mode 100644 index 0000000000..f6a79b7570 --- /dev/null +++ b/spring-thymeleaf/src/test/java/com/baeldung/thymeleaf/controller/ExpressionUtilityObjectsControllerTest.java @@ -0,0 +1,58 @@ +package com.baeldung.thymeleaf.controller; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import javax.servlet.Filter; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.RequestPostProcessor; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import com.baeldung.thymeleaf.config.InitSecurity; +import com.baeldung.thymeleaf.config.WebApp; +import com.baeldung.thymeleaf.config.WebMVCConfig; +import com.baeldung.thymeleaf.config.WebMVCSecurity; + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class }) +public class ExpressionUtilityObjectsControllerTest { + + @Autowired + WebApplicationContext wac; + @Autowired + MockHttpSession session; + + private MockMvc mockMvc; + + @Autowired + private Filter springSecurityFilterChain; + + protected RequestPostProcessor testUser() { + return user("user1").password("user1Pass").roles("USER"); + } + + @Before + public void setup() { + mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build(); + } + + @Test + public void testGetDates() throws Exception{ + mockMvc.perform(get("/objects").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("objects.html")); + } + +} diff --git a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java index 46a28c3c74..3542571bbc 100644 --- a/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java +++ b/spring-thymeleaf/src/test/java/org/baeldung/security/csrf/CsrfEnabledIntegrationTest.java @@ -2,8 +2,8 @@ package org.baeldung.security.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import javax.servlet.Filter; @@ -59,5 +59,20 @@ public class CsrfEnabledIntegrationTest { public void addStudentWithCSRF() throws Exception { mockMvc.perform(post("/saveStudent").contentType(MediaType.APPLICATION_JSON).param("id", "1234567").param("name", "Joe").param("gender", "M").with(testUser()).with(csrf())).andExpect(status().isOk()); } + + @Test + public void htmlInliningTest() throws Exception { + mockMvc.perform(get("/html").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("inliningExample.html")); + } + + @Test + public void jsInliningTest() throws Exception { + mockMvc.perform(get("/js").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentCheck.js")); + } + + @Test + public void plainInliningTest() throws Exception { + mockMvc.perform(get("/plain").with(testUser()).with(csrf())).andExpect(status().isOk()).andExpect(view().name("studentsList.txt")); + } } diff --git a/couchbase-sdk-async/.springBeans b/spring-userservice/.springBeans similarity index 100% rename from couchbase-sdk-async/.springBeans rename to spring-userservice/.springBeans diff --git a/spring-userservice/README.md b/spring-userservice/README.md new file mode 100644 index 0000000000..097afc5fc1 --- /dev/null +++ b/spring-userservice/README.md @@ -0,0 +1 @@ +spring-userservice is using a in memory derby db. Right click -> run on server to run the project \ No newline at end of file diff --git a/spring-userservice/pom.xml b/spring-userservice/pom.xml new file mode 100644 index 0000000000..93b01ee49c --- /dev/null +++ b/spring-userservice/pom.xml @@ -0,0 +1,320 @@ + + 4.0.0 + spring-userservice + spring-userservice + 0.0.1-SNAPSHOT + war + + + + + + + org.springframework + spring-orm + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + + + + org.hibernate + hibernate-entitymanager + ${hibernate.version} + + + org.hibernate + hibernate-ehcache + ${hibernate.version} + + + xml-apis + xml-apis + 1.4.01 + + + org.javassist + javassist + ${javassist.version} + + + mysql + mysql-connector-java + ${mysql-connector-java.version} + runtime + + + org.springframework.data + spring-data-jpa + ${spring-data-jpa.version} + + + com.h2database + h2 + ${h2.version} + + + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + javax.el + javax.el-api + 2.2.5 + + + + + + com.google.guava + guava + ${guava.version} + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + junit + junit + ${junit.version} + test + + + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + + + + org.mockito + mockito-core + ${mockito.version} + test + + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + + org.springframework.security + spring-security-core + ${org.springframework.security.version} + + + org.springframework.security + spring-security-web + ${org.springframework.security.version} + + + org.springframework.security + spring-security-config + ${org.springframework.security.version} + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + org.apache.derby + derbynet + 10.12.1.1 + + + org.apache.derby + derbytools + 10.12.1.1 + + + taglibs + standard + 1.1.2 + + + org.springframework.security + spring-security-taglibs + 4.1.3.RELEASE + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + + + org.springframework.boot + spring-boot-test + 1.4.1.RELEASE + + + org.springframework.boot + spring-boot + 1.4.1.RELEASE + + + javax.servlet + javax.servlet-api + 3.1.0 + + + + + spring-userservice + + + src/main/resources + true + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + + + + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + + + 4.1.3.RELEASE + 4.3.2.RELEASE + 3.20.0-GA + + + 5.2.2.Final + 5.1.38 + 1.10.2.RELEASE + 1.4.192 + + + 1.7.13 + 1.1.3 + + + 5.2.2.Final + + + 19.0 + 3.4 + + + 1.3 + 4.12 + 1.10.19 + + 4.4.1 + 4.5 + + 2.9.0 + + + 3.5.1 + 2.6 + 2.19.1 + 2.7 + 1.4.18 + + + + + + \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java new file mode 100644 index 0000000000..4a9e737a92 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/MvcConfig.java @@ -0,0 +1,42 @@ +package org.baeldung.custom.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.view.InternalResourceViewResolver; +import org.springframework.web.servlet.view.JstlView; + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "org.baeldung.security" }) +public class MvcConfig extends WebMvcConfigurerAdapter { + + public MvcConfig() { + super(); + } + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); + + registry.addViewController("/"); + registry.addViewController("/index"); + registry.addViewController("/login"); + registry.addViewController("/register"); + } + + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + + return bean; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java new file mode 100644 index 0000000000..6be7053b78 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/PersistenceDerbyJPAConfig.java @@ -0,0 +1,89 @@ +package org.baeldung.custom.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@EnableTransactionManagement +@PropertySource({ "classpath:persistence-derby.properties" }) +public class PersistenceDerbyJPAConfig { + + @Autowired + private Environment env; + + public PersistenceDerbyJPAConfig() { + super(); + } + + // beans + + @Bean + public LocalContainerEntityManagerFactoryBean myEmf() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" }); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); + return hibernateProperties; + } + + @Bean + public MyUserDAO myUserDAO() { + final MyUserDAO myUserDAO = new MyUserDAO(); + return myUserDAO; + } +} \ No newline at end of file diff --git a/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java new file mode 100644 index 0000000000..44df02980f --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/custom/config/SecSecurityConfig.java @@ -0,0 +1,75 @@ +package org.baeldung.custom.config; + +import org.baeldung.security.MyUserDetailsService; +import org.baeldung.user.service.MyUserService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +@Profile("!https") +public class SecSecurityConfig extends WebSecurityConfigurerAdapter { + + public SecSecurityConfig() { + super(); + } + + @Override + protected void configure(final AuthenticationManagerBuilder auth) throws Exception { + // @formatter:off + auth.authenticationProvider(authenticationProvider()); + // @formatter:on + } + + @Override + protected void configure(final HttpSecurity http) throws Exception { + // @formatter:off + http + .csrf().disable() + .authorizeRequests() + .antMatchers("/*").permitAll() + .and() + .formLogin() + .loginPage("/login") + .loginProcessingUrl("/login") + .defaultSuccessUrl("/",true) + .failureUrl("/login?error=true") + .and() + .logout() + .logoutUrl("/logout") + .deleteCookies("JSESSIONID") + .logoutSuccessUrl("/"); + // @formatter:on + } + + @Bean + public DaoAuthenticationProvider authenticationProvider() { + final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); + authProvider.setUserDetailsService(myUserDetailsService()); + authProvider.setPasswordEncoder(encoder()); + return authProvider; + } + + @Bean + public PasswordEncoder encoder() { + return new BCryptPasswordEncoder(11); + } + + @Bean + public MyUserDetailsService myUserDetailsService() { + return new MyUserDetailsService(); + } + + @Bean + public MyUserService myUserService() { + return new MyUserService(); + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java new file mode 100644 index 0000000000..804d391641 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/persistence/model/MyUser.java @@ -0,0 +1,50 @@ +package org.baeldung.persistence.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "spring_custom_user_service") +public class MyUser { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(unique = true, nullable = false) + private String username; + + @Column(nullable = false) + private String password; + + public MyUser() { + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java new file mode 100644 index 0000000000..fe97984af8 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/MyUserDetailsService.java @@ -0,0 +1,35 @@ +package org.baeldung.security; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +@Service("userDetailsService") +public class MyUserDetailsService implements UserDetailsService { + + @Autowired + MyUserDAO myUserDAO; + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + final MyUser user = myUserDAO.findByUsername(username); + + if (user == null) { + throw new UsernameNotFoundException("No user found with username: " + username); + } + return new User(user.getUsername(), user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); + + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/security/UserController.java b/spring-userservice/src/main/java/org/baeldung/security/UserController.java new file mode 100644 index 0000000000..b1c96e72c0 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/security/UserController.java @@ -0,0 +1,52 @@ +package org.baeldung.security; + +import javax.annotation.Resource; + +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +@Controller +public class UserController { + + @Resource + MyUserService myUserService; + + @RequestMapping(value = "/register", method = RequestMethod.POST) + public String registerUserAccount(final MyUserDto accountDto, final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + try { + myUserService.registerNewUserAccount(accountDto); + model.addAttribute("message", "Registration successful"); + return "index"; + } + catch(final Exception exc){ + model.addAttribute("message", "Registration failed"); + + return "index"; + } + } + + @RequestMapping(value = "/", method = RequestMethod.GET) + public String getHomepage(final Model model) { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + model.addAttribute("name", auth.getName()); + return "index"; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + public String getRegister() { + return "register"; + } + + @RequestMapping(value = "/login", method = RequestMethod.GET) + public String getLogin() { + return "login"; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java new file mode 100644 index 0000000000..4cc9f61b4a --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/dao/MyUserDAO.java @@ -0,0 +1,46 @@ +package org.baeldung.user.dao; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.baeldung.persistence.model.MyUser; +import org.springframework.stereotype.Repository; + +@Repository +public class MyUserDAO { + + @PersistenceContext + private EntityManager entityManager; + + public MyUser findByUsername(final String username) { + final Query query = entityManager.createQuery("from MyUser where username=:username", MyUser.class); + query.setParameter("username", username); + final List result = query.getResultList(); + if (result != null && result.size() > 0) { + return result.get(0); + } else + return null; + } + + public MyUser save(final MyUser user) { + entityManager.persist(user); + return user; + } + + public void removeUserByUsername(String username) { + final Query query = entityManager.createQuery("delete from MyUser where username=:username"); + query.setParameter("username", username); + query.executeUpdate(); + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void setEntityManager(final EntityManager entityManager) { + this.entityManager = entityManager; + } +} diff --git a/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java new file mode 100644 index 0000000000..1e05541998 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/user/service/MyUserService.java @@ -0,0 +1,49 @@ +package org.baeldung.user.service; + +import org.baeldung.persistence.model.MyUser; +import org.baeldung.user.dao.MyUserDAO; +import org.baeldung.web.MyUserDto; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class MyUserService { + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + MyUserDAO myUserDAO; + + public MyUser registerNewUserAccount(final MyUserDto accountDto) throws Exception { + if (usernameExists(accountDto.getUsername())) { + throw new Exception("There is an account with that username: " + accountDto.getUsername()); + } + final MyUser user = new MyUser(); + + user.setUsername(accountDto.getUsername()); + user.setPassword(passwordEncoder.encode(accountDto.getPassword())); + return myUserDAO.save(user); + } + + public MyUser getUserByUsername(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + return user; + } + + public void removeUserByUsername(String username){ + myUserDAO.removeUserByUsername(username); + } + + private boolean usernameExists(final String username) { + final MyUser user = myUserDAO.findByUsername(username); + if (user != null) { + return true; + } + return false; + } + +} diff --git a/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java new file mode 100644 index 0000000000..c572208913 --- /dev/null +++ b/spring-userservice/src/main/java/org/baeldung/web/MyUserDto.java @@ -0,0 +1,29 @@ +package org.baeldung.web; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +public class MyUserDto { + @NotNull + @Size(min = 1) + private String username; + + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(final String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(final String password) { + this.password = password; + } + +} diff --git a/spring-userservice/src/main/resources/persistence-derby.properties b/spring-userservice/src/main/resources/persistence-derby.properties new file mode 100644 index 0000000000..e808fdc288 --- /dev/null +++ b/spring-userservice/src/main/resources/persistence-derby.properties @@ -0,0 +1,12 @@ +# jdbc.X +jdbc.driverClassName=org.apache.derby.jdbc.EmbeddedDriver +jdbc.url=jdbc:derby:memory:spring_custom_user_service;create=true +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.DerbyDialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..254272e1c0 --- /dev/null +++ b/spring-userservice/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml new file mode 100644 index 0000000000..25d1d4d22f --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /WEB-INF/views/ + + + .jsp + + + + + + + + + + + + + + + ${hibernate.hbm2ddl.auto} + ${hibernate.dialect} + ${hibernate.cache.use_second_level_cache} + ${hibernate.cache.use_query_cache} + + + + + + + + + + + + + + + + + + + diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp new file mode 100644 index 0000000000..0c89257cd2 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/index.jsp @@ -0,0 +1,35 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> + + + + + +Welcome! + + + + + + + +Register +

+ +Login + +

+${message } +

+ +Hello, ${name }! +
+
+Logout +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp new file mode 100644 index 0000000000..29431f426d --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/login.jsp @@ -0,0 +1,29 @@ +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + + +

Login

+ +
+ +
+ + + + + + + + + + + +
User:
Password:
+ + + Username or password invalid! + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp new file mode 100644 index 0000000000..e6e9d373a0 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/views/register.jsp @@ -0,0 +1,23 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> +<%@ taglib prefix="c" + uri="http://java.sun.com/jsp/jstl/core" %> + + + + +Welcome! + + + + + +Register here:

+
+Username:
+Password:
+ +
+ + + \ No newline at end of file diff --git a/spring-userservice/src/main/webapp/WEB-INF/web.xml b/spring-userservice/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..b526774179 --- /dev/null +++ b/spring-userservice/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,51 @@ + + + + Spring MVC Application + + + + + + mvc-dispatcher + org.springframework.web.servlet.DispatcherServlet + 1 + + + mvc-dispatcher + / + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + + index.jsp + + + \ No newline at end of file diff --git a/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java new file mode 100644 index 0000000000..6e1cd67e06 --- /dev/null +++ b/spring-userservice/src/test/java/org/baeldung/userservice/CustomUserDetailsServiceTest.java @@ -0,0 +1,85 @@ +package org.baeldung.userservice; + +import org.baeldung.custom.config.MvcConfig; +import org.baeldung.custom.config.PersistenceDerbyJPAConfig; +import org.baeldung.custom.config.SecSecurityConfig; +import org.baeldung.user.service.MyUserService; +import org.baeldung.web.MyUserDto; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.security.authentication.AuthenticationProvider; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.Logger; + +@RunWith(SpringJUnit4ClassRunner.class) +@SpringApplicationConfiguration(classes = { MvcConfig.class, PersistenceDerbyJPAConfig.class, SecSecurityConfig.class }) +@WebAppConfiguration +public class CustomUserDetailsServiceTest { + + private static final Logger LOG = Logger.getLogger("CustomUserDetailsServiceTest"); + + public static final String USERNAME = "user"; + public static final String PASSWORD = "pass"; + public static final String USERNAME2 = "user2"; + + @Autowired + MyUserService myUserService; + + @Autowired + AuthenticationProvider authenticationProvider; + + @Test + public void givenExistingUser_whenAuthenticate_thenRetrieveFromDb() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + myUserService.registerNewUserAccount(userDTO); + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + + assertEquals(authentication.getName(), USERNAME); + + } catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } finally { + myUserService.removeUserByUsername(USERNAME); + } + } + + @Test (expected = BadCredentialsException.class) + public void givenIncorrectUser_whenAuthenticate_thenBadCredentialsException() { + try { + MyUserDto userDTO = new MyUserDto(); + userDTO.setUsername(USERNAME); + userDTO.setPassword(PASSWORD); + + try { + myUserService.registerNewUserAccount(userDTO); + } + catch (Exception exc) { + LOG.log(Level.SEVERE, "Error creating account"); + } + + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(USERNAME2, PASSWORD); + Authentication authentication = authenticationProvider.authenticate(auth); + } + finally { + myUserService.removeUserByUsername(USERNAME); + } + } + +}