Merge branch 'master' into craedel-log4j2

This commit is contained in:
Christian Rädel 2016-10-02 18:53:29 +02:00
commit 746e28de40
221 changed files with 4981 additions and 1636 deletions

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>annotations</artifactId>
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-processing</artifactId>
<properties>
<auto-service.version>1.0-rc2</auto-service.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>${auto-service.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
.collect(Collectors.partitioningBy(element ->
((ExecutableType) element.asType()).getParameterTypes().size() == 1
&& element.getSimpleName().toString().startsWith("set")));
List<Element> setters = annotatedMethods.get(true);
List<Element> 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<String, String> 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<String, String> 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("}");
}
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.annotation.processor;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface BuilderProperty {
}

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>annotations</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<artifactId>annotation-user</artifactId>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>annotation-processing</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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;
}
}

View File

@ -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());
}
}

20
annotations/pom.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>annotations</artifactId>
<packaging>pom</packaging>
<modules>
<module>annotation-processing</module>
<module>annotation-user</module>
</modules>
</project>

View File

@ -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)
- [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 8s 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)

View File

@ -1,9 +1,10 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>core-java8</artifactId>
<version>0.1-SNAPSHOT</version>
<name>core-java8</name>
@ -111,6 +112,9 @@
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.0.13</logback.version>

View File

@ -0,0 +1 @@
Hello World from fileTest.txt!!!

View File

@ -0,0 +1,78 @@
package com.baeldung.file;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import static org.hamcrest.CoreMatchers.containsString;
public class FileOperationsTest {
@Test
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("fileTest.txt");
String data = readFromInputStream(inputStream);
Assert.assertThat(data, containsString(expectedData));
}
@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.assertThat(data, 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, containsString(expectedData));
}
@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, containsString(expectedData));
}
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();
}
}

View File

@ -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<File> 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;

View File

@ -0,0 +1,47 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
public class CurrentDateTimeTest {
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now();
final Calendar calendar = GregorianCalendar.getInstance();
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));
}
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now();
final Calendar calendar = GregorianCalendar.getInstance();
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));
}
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now();
final Calendar calendar = GregorianCalendar.getInstance();
assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
}
}

View File

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

View File

@ -0,0 +1 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat.

View File

@ -60,12 +60,8 @@
<configuration>
<source>1.9</source>
<target>1.9</target>
<verbose>true</verbose>
<!-- <executable>C:\develop\jdks\jdk-9_ea122\bin\javac</executable>
<compilerVersion>1.9</compilerVersion> -->
</configuration>
</plugin>
<plugin>
@ -85,12 +81,7 @@
<!-- maven plugins -->
<!--
<maven-war-plugin.version>2.6</maven-war-plugin.version>
maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version> -->
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.6-jigsaw-SNAPSHOT</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- testing -->

View File

@ -0,0 +1,71 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class Java9OptionalsStreamTest {
private static List<Optional<String>> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
@Test
public void filterOutPresentOptionalsWithFilter() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap() {
assertEquals(4, listOfOptionals.size());
List<String> filteredList = listOfOptionals.stream()
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
@Test
public void filterOutPresentOptionalsWithFlatMap2() {
assertEquals(4, listOfOptionals.size());
List<String> 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());
List<String> filteredList = listOfOptionals.stream()
.flatMap(Optional::stream)
.collect(Collectors.toList());
assertEquals(2, filteredList.size());
assertEquals("foo", filteredList.get(0));
assertEquals("bar", filteredList.get(1));
}
}

View File

@ -1,6 +1,5 @@
package com.baeldung.java9;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

View File

@ -0,0 +1,21 @@
package com.baeldung.java9;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class OptionalToStreamTest {
@Test
public void testOptionalToStream() {
Optional<String> op = Optional.ofNullable("String value");
Stream<String> strOptionalStream = op.stream();
Stream<String> filteredStream = strOptionalStream.filter((str) -> {
return str != null && str.startsWith("String");
});
assertEquals(1, filteredStream.count());
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.java9;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SetExamplesTest {
@Test
public void testUnmutableSet() {
Set<String> strKeySet = Set.of("key1", "key2", "key3");
try {
strKeySet.add("newKey");
} catch (UnsupportedOperationException uoe) {
}
assertEquals(strKeySet.size(), 3);
}
@Test
public void testArrayToSet() {
Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
Set<Integer> intSet = Set.of(intArray);
assertEquals(intSet.size(), intArray.length);
}
}

View File

@ -123,6 +123,12 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,20 @@
package com.baeldung.core.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileNotFoundExceptionExample {
public static void main(String[] args) throws IOException {
BufferedReader rd = null;
try {
rd = new BufferedReader(new FileReader(new File("notExisting")));
rd.readLine();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.java.regex;
public class Result {
private boolean found = false;
private int count = 0;
public Result() {
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}

View File

@ -0,0 +1,65 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@ -11,13 +11,11 @@ public class Rectangle extends Shape {
@Override
public double area() {
// A = w * l
return width * length;
}
@Override
public double perimeter() {
// P = 2(w + l)
return 2 * (width + length);
}

View File

@ -0,0 +1,503 @@
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() {
Result result = runTest("foo", "foo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
Result result = runTest("foo", "foofoo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenText_whenMatchesWithDotMetach_thenCorrect() {
Result result = runTest(".", "foo");
assertTrue(result.isFound());
}
@Test
public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
Result result = runTest("foo.", "foofoo");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenORSet_whenMatchesAny_thenCorrect() {
Result result = runTest("[abc]", "b");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
Result result = runTest("[abc]", "cab");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
Result result = runTest("[bcr]at", "bat cat rat");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenNORSet_whenMatchesNon_thenCorrect() {
Result result = runTest("[^abc]", "g");
assertTrue(result.isFound());
}
@Test
public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
Result result = runTest("[^bcr]at", "sat mat eat");
assertTrue(result.isFound());
}
@Test
public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
Result result = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
Result result = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 26);
}
@Test
public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
Result result = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 28);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
Result result = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
Result result = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenTwoSets_whenMatchesUnion_thenCorrect() {
Result result = runTest("[1-3[7-9]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 6);
}
@Test
public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
Result result = runTest("[1-6&&[3-9]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 4);
}
@Test
public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
Result result = runTest("[0-9&&[^2468]]", "123456789");
assertTrue(result.isFound());
assertEquals(result.getCount(), 5);
}
@Test
public void givenDigits_whenMatches_thenCorrect() {
Result result = runTest("\\d", "123");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenNonDigits_whenMatches_thenCorrect() {
Result result = runTest("\\D", "a6c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenWhiteSpace_whenMatches_thenCorrect() {
Result result = runTest("\\s", "a c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenNonWhiteSpace_whenMatches_thenCorrect() {
Result result = runTest("\\S", "a c");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenWordCharacter_whenMatches_thenCorrect() {
Result result = runTest("\\w", "hi!");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenNonWordCharacter_whenMatches_thenCorrect() {
Result result = runTest("\\W", "hi!");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a?", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{0,1}", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a*", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{0,}", "hi");
assertTrue(result.isFound());
assertEquals(result.getCount(), 3);
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
Result result = runTest("\\a+", "hi");
assertFalse(result.isFound());
}
@Test
public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
Result result = runTest("\\a{1,}", "hi");
assertFalse(result.isFound());
}
@Test
public void givenBraceQuantifier_whenMatches_thenCorrect() {
Result result = runTest("a{3}", "aaaaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
Result result = runTest("a{3}", "aa");
assertFalse(result.isFound());
}
@Test
public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
Result result = runTest("a{2,3}", "aaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
Result result = runTest("a{2,3}?", "aaaa");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect() {
Result result = runTest("(\\d\\d)", "12");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect2() {
Result result = runTest("(\\d\\d)", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 2);
}
@Test
public void givenCapturingGroup_whenMatches_thenCorrect3() {
Result result = runTest("(\\d\\d)(\\d\\d)", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
Result result = runTest("(\\d\\d)\\1", "1212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
Result result = runTest("(\\d\\d)\\1\\1\\1", "12121212");
assertTrue(result.isFound());
assertEquals(result.getCount(), 1);
}
@Test
public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
Result result = runTest("(\\d\\d)\\1", "1213");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtBeginning_thenCorrect() {
Result result = runTest("^dog", "dogs are friendly");
assertTrue(result.isFound());
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
Result result = runTest("^dog", "are dogs are friendly?");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtEnd_thenCorrect() {
Result result = runTest("dog$", "Man's best friend is a dog");
assertTrue(result.isFound());
}
@Test
public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
Result result = runTest("dog$", "is a dog man's best friend?");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
Result result = runTest("\\bdog\\b", "a dog is friendly");
assertTrue(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
Result result = runTest("\\bdog\\b", "dog is man's best friend");
assertTrue(result.isFound());
}
@Test
public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
Result result = runTest("\\bdog\\b", "snoop dogg is a rapper");
assertFalse(result.isFound());
}
@Test
public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
Result result = runTest("\\bdog\\B", "snoop dogg is a rapper");
assertTrue(result.isFound());
}
@Test
public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
Result result = runTest("\u00E9", "\u0065\u0301");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
Result result = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
Result result = runTest("dog", "This is a Dog");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
Result result = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
Result result = runTest("(?i)dog", "This is a Dog");
assertTrue(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog");
assertFalse(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
Result result = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
assertTrue(result.isFound());
}
@Test
public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
Result result = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
assertTrue(result.isFound());
}
@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() {
Result result = runTest("(.*)", "text");
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
Result result = runTest("(.*)", "text", Pattern.LITERAL);
assertFalse(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
Result result = runTest("(.*)", "text(.*)", Pattern.LITERAL);
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertFalse(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
Result result = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
assertTrue(result.isFound());
}
@Test
public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
Result result = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
assertTrue(result.isFound());
}
@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 Result runTest(String regex, String text) {
pattern = Pattern.compile(regex);
matcher = pattern.matcher(text);
Result result = new Result();
while (matcher.find())
result.setCount(result.getCount() + 1);
if (result.getCount() > 0)
result.setFound(true);
return result;
}
public synchronized static Result runTest(String regex, String text, int flags) {
pattern = Pattern.compile(regex, flags);
matcher = pattern.matcher(text);
Result result = new Result();
while (matcher.find())
result.setCount(result.getCount() + 1);
if (result.getCount() > 0)
result.setFound(true);
return result;
}
}

View File

@ -22,11 +22,10 @@ public class ComplexClassTest {
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -12,11 +12,10 @@ public class PrimitiveClassTest {
PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -15,11 +15,10 @@ public class SquareClassTest {
Square dObject = new Square(20, Color.BLUE);
// equals()
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
// hashCode()
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
// non-equal objects are not equals() and have different hashCode()
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}

View File

@ -18,18 +18,18 @@ public class ArrayListTest {
@Before
public void setUp() {
List<String> xs = LongStream.range(0, 16)
List<String> list = LongStream.range(0, 16)
.boxed()
.map(Long::toHexString)
.collect(toCollection(ArrayList::new));
stringsToSearch = new ArrayList<>(xs);
stringsToSearch.addAll(xs);
stringsToSearch = new ArrayList<>(list);
stringsToSearch.addAll(list);
}
@Test
public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
List<String> xs = new ArrayList<>();
assertTrue(xs.isEmpty());
List<String> list = new ArrayList<>();
assertTrue(list.isEmpty());
}
@Test
@ -37,29 +37,29 @@ public class ArrayListTest {
Collection<Integer> numbers =
IntStream.range(0, 10).boxed().collect(toSet());
List<Integer> xs = new ArrayList<>(numbers);
assertEquals(10, xs.size());
assertTrue(numbers.containsAll(xs));
List<Integer> list = new ArrayList<>(numbers);
assertEquals(10, list.size());
assertTrue(numbers.containsAll(list));
}
@Test
public void givenElement_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>();
List<Long> list = new ArrayList<>();
xs.add(1L);
xs.add(2L);
xs.add(1, 3L);
list.add(1L);
list.add(2L);
list.add(1, 3L);
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(xs));
assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
}
@Test
public void givenCollection_whenAddToArrayList_thenIsAdded() {
List<Long> xs = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
LongStream.range(4, 10).boxed()
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> xs.addAll(0, ys)));
.collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(xs));
assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
}
@Test
@ -106,27 +106,27 @@ public class ArrayListTest {
@Test
public void givenIndex_whenRemove_thenCorrectElementRemoved() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(xs);
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
Collections.reverse(list);
xs.remove(0);
assertThat(xs.get(0), equalTo(8));
list.remove(0);
assertThat(list.get(0), equalTo(8));
xs.remove(Integer.valueOf(0));
assertFalse(xs.contains(0));
list.remove(Integer.valueOf(0));
assertFalse(list.contains(0));
}
@Test
public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
List<Integer> xs = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = xs.listIterator(xs.size());
List<Integer> result = new ArrayList<>(xs.size());
List<Integer> list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
ListIterator<Integer> it = list.listIterator(list.size());
List<Integer> result = new ArrayList<>(list.size());
while (it.hasPrevious()) {
result.add(it.previous());
}
Collections.reverse(xs);
assertThat(result, equalTo(xs));
Collections.reverse(list);
assertThat(result, equalTo(list));
}
@Test

View File

@ -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();
}
}

View File

@ -1,63 +0,0 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
public class ComplexClass {
private ArrayList<?> genericArrayList;
private HashSet<Integer> integerHashSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
super();
this.genericArrayList = genericArrayList;
this.integerHashSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericArrayList == null) ? 0 : genericArrayList.hashCode());
result = prime * result + ((integerHashSet == null) ? 0 : integerHashSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericArrayList == null) {
if (other.genericArrayList != null)
return false;
} else if (!genericArrayList.equals(other.genericArrayList))
return false;
if (integerHashSet == null) {
if (other.integerHashSet != null)
return false;
} else if (!integerHashSet.equals(other.integerHashSet))
return false;
return true;
}
protected ArrayList<?> getGenericArrayList() {
return genericArrayList;
}
protected void setGenericArrayList(ArrayList<?> genericArrayList) {
this.genericArrayList = genericArrayList;
}
protected HashSet<Integer> getIntegerHashSet() {
return integerHashSet;
}
protected void setIntegerHashSet(HashSet<Integer> integerHashSet) {
this.integerHashSet = integerHashSet;
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.enterprise.patterns</groupId>
<artifactId>enterprise-patterns-parent</artifactId>
<packaging>pom</packaging>
<modules>
<module>front-controller-pattern</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

5
feign-client/README.md Normal file
View File

@ -0,0 +1,5 @@
## Feign Hypermedia Client ##
This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api

99
feign-client/pom.xml Normal file
View File

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.feign</groupId>
<artifactId>feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>9.3.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.feign;
import com.baeldung.feign.clients.BookClient;
import feign.Feign;
import feign.Logger;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.okhttp.OkHttpClient;
import feign.slf4j.Slf4jLogger;
import lombok.Getter;
@Getter
public class BookControllerFeignClientBuilder {
private BookClient bookClient = createClient(BookClient.class,
"http://localhost:8081/api/books");
private static <T> T createClient(Class<T> type, String uri) {
return Feign.builder()
.client(new OkHttpClient())
.encoder(new GsonEncoder())
.decoder(new GsonDecoder())
.logger(new Slf4jLogger(type))
.logLevel(Logger.Level.FULL)
.target(type, uri);
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.feign.clients;
import com.baeldung.feign.models.Book;
import com.baeldung.feign.models.BookResource;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
import java.util.List;
public interface BookClient {
@RequestLine("GET /{isbn}")
BookResource findByIsbn(@Param("isbn") String isbn);
@RequestLine("GET")
List<BookResource> findAll();
@RequestLine("POST")
@Headers("Content-Type: application/json")
void create(Book book);
}

View File

@ -0,0 +1,18 @@
package com.baeldung.feign.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private String isbn;
private String author;
private String title;
private String synopsis;
private String language;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.feign.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BookResource {
private Book book;
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}:%n[+] %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,58 @@
package com.baeldung.feign.clients;
import com.baeldung.feign.BookControllerFeignClientBuilder;
import com.baeldung.feign.models.Book;
import com.baeldung.feign.models.BookResource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@Slf4j
@RunWith(JUnit4.class)
public class BookClientTest {
private BookClient bookClient;
@Before
public void setup() {
BookControllerFeignClientBuilder feignClientBuilder = new BookControllerFeignClientBuilder();
bookClient = feignClientBuilder.getBookClient();
}
@Test
public void givenBookClient_shouldRunSuccessfully() throws Exception {
List<Book> books = bookClient.findAll().stream()
.map(BookResource::getBook)
.collect(Collectors.toList());
assertTrue(books.size() > 2);
log.info("{}", books);
}
@Test
public void givenBookClient_shouldFindOneBook() throws Exception {
Book book = bookClient.findByIsbn("0151072558").getBook();
assertThat(book.getAuthor(), containsString("Orwell"));
log.info("{}", book);
}
@Test
public void givenBookClient_shouldPostBook() throws Exception {
String isbn = UUID.randomUUID().toString();
Book book = new Book(isbn, "Me", "It's me!", null, null);
bookClient.create(book);
book = bookClient.findByIsbn(isbn).getBook();
assertThat(book.getAuthor(), is("Me"));
log.info("{}", book);
}
}

View File

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `department` (
`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=UTF8;
ALTER TABLE `employee` ADD `dept_id` int AFTER `email`;

View File

@ -23,6 +23,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>

View File

@ -15,7 +15,13 @@
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- SLF4J - Log4J dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
-->
<!--log4j2 dependencies-->
<dependency>
@ -28,22 +34,34 @@
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<!--disruptor for log4j2 async logging-->
<!--disruptor for log4j2 async logging-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.4</version>
</dependency>
<!-- SLF4J - Log4J2 dependency
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.6.2</version>
</dependency>
-->
<!--logback dependencies-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
<!-- SLF4J - JCL dependency
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jcl</artifactId>
<version>1.7.21</version>
</dependency>
-->
</dependencies>
<build>
<plugins>

View File

@ -0,0 +1,20 @@
package com.baeldung.slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* To switch between logging frameworks you need only to uncomment needed framework dependencies in pom.xml
*/
public class Slf4jExample {
private static Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
public static void main(String[] args) {
logger.debug("Debug log message");
logger.info("Info log message");
logger.error("Error log message");
String variable = "Hello John";
logger.debug("Printing variable value {} ", variable);
}
}

View File

@ -4,15 +4,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>front-controller-pattern</artifactId>
<groupId>com.baeldung.enterprise.patterns</groupId>
<artifactId>patterns</artifactId>
<packaging>war</packaging>
<parent>
<artifactId>enterprise-patterns-parent</artifactId>
<groupId>com.baeldung.enterprise.patterns</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
@ -22,11 +17,22 @@
</dependency>
</dependencies>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>

View File

@ -22,24 +22,17 @@ public class FrontControllerServlet extends HttpServlet {
private FrontCommand getCommand(HttpServletRequest request) {
try {
return (FrontCommand) getCommandClass(request)
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to get command!", e);
}
}
private Class getCommandClass(HttpServletRequest request) {
try {
return Class.forName(
Class type = Class.forName(
String.format(
"com.baeldung.enterprise.patterns.front.controller.commands.%sCommand",
request.getParameter("command")
)
);
} catch (ClassNotFoundException e) {
return UnknownCommand.class;
return (FrontCommand) type
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
return new UnknownCommand();
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

@ -30,7 +30,8 @@
<module>dependency-injection</module>
<module>deltaspike</module>
<module>enterprise-patterns</module>
<module>patterns</module>
<module>feign-client</module>
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>gson</module>
@ -90,12 +91,12 @@
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-jpa</module>
<module>spring-jpa-jndi</module>
<module>spring-katharsis</module>
<module>spring-mockito</module>
<module>spring-mvc-java</module>
<module>spring-mvc-no-xml</module>
<module>spring-mvc-xml</module>
<module>spring-mvc-tiles</module>
<module>spring-openid</module>
<module>spring-protobuf</module>
<module>spring-quartz</module>
@ -129,8 +130,10 @@
<module>lombok</module>
<module>redis</module>
<module>wicket</module>
<module>xstream</module>
<module>java-cassandra</module>
<module>annotations</module>
</modules>
</project>

View File

@ -0,0 +1,36 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>selenium-junit-testng</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.10</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,29 @@
package main.java.com.baeldung.selenium;
import org.openqa.selenium.WebDriver;
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";
public SeleniumExample() {
webDriver = new FirefoxDriver();
webDriver.get(url);
}
public void closeWindow() {
webDriver.close();
}
public String getActualTitle() {
return webDriver.getTitle();
}
public String getExpectedTitle() {
return expectedTitle;
}
}

View File

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.junit;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestSeleniumWithJUnit {
private SeleniumExample seleniumExample;
@Before
public void setUp() {
seleniumExample = new SeleniumExample();
}
@After
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -0,0 +1,30 @@
package test.java.com.baeldung.selenium.testng;
import static org.testng.Assert.assertEquals;
import main.java.com.baeldung.selenium.SeleniumExample;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
public class TestSeleniumWithTestNG {
private SeleniumExample seleniumExample;
@BeforeSuite
public void setUp() {
seleniumExample = new SeleniumExample();
}
@AfterSuite
public void tearDown() {
seleniumExample.closeWindow();
}
@Test
public void whenPageIsLoaded_thenTitleIsAsPerExpectation() {
String expectedTitle = seleniumExample.getExpectedTitle();
String actualTitle = seleniumExample.getActualTitle();
assertEquals(actualTitle, expectedTitle);
}
}

View File

@ -0,0 +1,34 @@
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);
}
}

View File

@ -0,0 +1,34 @@
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);
}
}

View File

@ -1,2 +0,0 @@
user.role=Developer
user.password=pass

View File

@ -1,4 +0,0 @@
FROM alpine:edge
MAINTAINER baeldung.com
RUN apk add --no-cache openjdk8
COPY files/UnlimitedJCEPolicyJDK8/* /usr/lib/jvm/java-1.8-openjdk/jre/lib/security/

View File

@ -1,41 +0,0 @@
version: '2'
services:
config-server:
build:
context: .
dockerfile: Dockerfile.server
image: config-server:latest
expose:
- 8888
networks:
- spring-cloud-network
volumes:
- spring-cloud-config-repo:/var/lib/spring-cloud/config-repo
logging:
driver: json-file
config-client:
build:
context: .
dockerfile: Dockerfile.client
image: config-client:latest
entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh
environment:
SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}'
expose:
- 8080
ports:
- 8080
networks:
- spring-cloud-network
links:
- config-server:config-server
depends_on:
- config-server
logging:
driver: json-file
networks:
spring-cloud-network:
driver: bridge
volumes:
spring-cloud-config-repo:
external: true

View File

@ -1,43 +0,0 @@
version: '2'
services:
config-server:
container_name: config-server
build:
context: .
dockerfile: Dockerfile.server
image: config-server:latest
expose:
- 8888
networks:
- spring-cloud-network
volumes:
- spring-cloud-config-repo:/var/lib/spring-cloud/config-repo
logging:
driver: json-file
config-client:
container_name: config-client
build:
context: .
dockerfile: Dockerfile.client
image: config-client:latest
entrypoint: /opt/spring-cloud/bin/config-client-entrypoint.sh
environment:
SPRING_APPLICATION_JSON: '{"spring": {"cloud": {"config": {"uri": "http://config-server:8888"}}}}'
expose:
- 8080
ports:
- 8080:8080
networks:
- spring-cloud-network
links:
- config-server:config-server
depends_on:
- config-server
logging:
driver: json-file
networks:
spring-cloud-network:
driver: bridge
volumes:
spring-cloud-config-repo:
external: true

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-config-client</artifactId>
<packaging>jar</packaging>
<name>spring-cloud-config-client</name>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
<version>1.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>../docker/files</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,29 +0,0 @@
package com.baeldung.spring.cloud.config.client;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class ConfigClient {
@Value("${user.role}")
private String role;
@Value("${user.password}")
private String password;
public static void main(String[] args) {
SpringApplication.run(ConfigClient.class, args);
}
@RequestMapping(value = "/whoami/{username}", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN_VALUE)
public String whoami(@PathVariable("username") String username) {
return String.format("Hello %s! You are a(n) %s and your password is '%s'.\n", username, role, password);
}
}

View File

@ -1,5 +0,0 @@
spring.application.name=config-client
spring.profiles.active=development
spring.cloud.config.uri=http://localhost:${PORT:8888}
spring.cloud.config.username=root
spring.cloud.config.password=s3cr3t

View File

@ -1,44 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-config</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>spring-cloud-config-server</artifactId>
<name>spring-cloud-config-server</name>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>1.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<outputDirectory>../docker/files</outputDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,10 +0,0 @@
server.port=${PORT:8888}
spring.cloud.config.server.git.uri=${CONFIG_REPO}
spring.cloud.config.server.git.clone-on-start=false
spring.cloud.config.fail-fast=true
security.user.name=root
security.user.password=s3cr3t
encrypt.key-store.location=classpath:/config-server.jks
encrypt.key-store.password=my-s70r3-s3cr3t
encrypt.key-store.alias=config-server-key
encrypt.key-store.secret=my-k34-s3cr3t

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>spring-cloud-eureka-server</module>
<module>spring-cloud-eureka-client</module>
<module>spring-cloud-eureka-feign-client</module>
</modules>
<packaging>pom</packaging>
<name>Spring Cloud Eureka</name>
<description>Spring Cloud Eureka Server and Sample Clients</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -1,32 +0,0 @@
package com.baeldung.spring.cloud.eureka.client;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
@RestController
public class EurekaClientApplication implements GreetingController {
@Autowired
@Lazy
private EurekaClient eurekaClient;
@Value("${spring.application.name}")
private String appName;
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
@Override
public String greeting() {
return String.format("Hello from '%s'!", eurekaClient.getApplication(appName).getName());
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.spring.cloud.eureka.client;
import org.springframework.web.bind.annotation.RequestMapping;
public interface GreetingController {
@RequestMapping("/greeting")
String greeting();
}

View File

@ -1,13 +0,0 @@
spring:
application:
name: spring-cloud-eureka-client
server:
port: 0
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
instance:
preferIpAddress: true

View File

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-eureka-feign-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Eureka Feign Client</name>
<description>Spring Cloud Eureka - Sample Feign Client</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-eureka-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,29 +0,0 @@
package com.baeldung.spring.cloud.feign.client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@Controller
public class FeignClientApplication {
@Autowired
private GreetingClient greetingClient;
public static void main(String[] args) {
SpringApplication.run(FeignClientApplication.class, args);
}
@RequestMapping("/get-greeting")
public String greeting(Model model) {
model.addAttribute("greeting", greetingClient.greeting());
return "greeting-view";
}
}

View File

@ -1,8 +0,0 @@
package com.baeldung.spring.cloud.feign.client;
import com.baeldung.spring.cloud.eureka.client.GreetingController;
import org.springframework.cloud.netflix.feign.FeignClient;
@FeignClient("spring-cloud-eureka-client")
public interface GreetingClient extends GreetingController {
}

View File

@ -1,11 +0,0 @@
spring:
application:
name: spring-cloud-eureka-feign-client
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}

View File

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greeting Page</title>
</head>
<body>
<h2 th:text="${greeting}"/>
</body>
</html>

View File

@ -1,7 +0,0 @@
server:
port: 8761
eureka:
client:
registerWithEureka: false
fetchRegistry: false

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<modules>
<module>spring-cloud-hystrix-rest-producer</module>
<module>spring-cloud-hystrix-rest-consumer</module>
<module>spring-cloud-hystrix-feign-rest-consumer</module>
</modules>
<packaging>pom</packaging>
<name>Spring Cloud Hystrix</name>
<description>Spring Cloud Hystrix Demo</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.0.RELEASE</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -1,82 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-hystrix-feign-rest-consumer</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Hystrix Feign REST Consumer</name>
<description>Spring Cloud Hystrix Feign Sample Implementation</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix-rest-producer</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,21 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import com.baeldung.spring.cloud.hystrix.rest.producer.GreetingController;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(
name = "rest-producer",
url = "http://localhost:9090",
fallback = GreetingClient.GreetingClientFallback.class
)
public interface GreetingClient extends GreetingController {
@Component
public static class GreetingClientFallback implements GreetingClient {
@Override
public String greeting(@PathVariable("username") String username) {
return "Hello User!";
}
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableFeignClients
@Controller
public class RestConsumerFeignApplication {
@Autowired
private GreetingClient greetingClient;
public static void main(String[] args) {
SpringApplication.run(RestConsumerFeignApplication.class, args);
}
@RequestMapping("/get-greeting/{username}")
public String getGreeting(Model model, @PathVariable("username") String username) {
model.addAttribute("greeting", greetingClient.greeting(username));
return "greeting-view";
}
}

View File

@ -1,9 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Greetings from Hystrix</title>
</head>
<body>
<h2 th:text="${greeting}"/>
</body>
</html>

View File

@ -1,72 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-hystrix-rest-consumer</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Spring Cloud Hystrix REST Consumer</name>
<description>Spring Cloud Hystrix Sample Implementation</description>
<parent>
<groupId>com.baeldung.spring.cloud</groupId>
<artifactId>spring-cloud-hystrix</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,18 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class GreetingService {
@HystrixCommand(fallbackMethod = "defaultGreeting")
public String getGreeting(String username) {
return new RestTemplate().getForObject("http://localhost:9090/greeting/{username}", String.class, username);
}
private String defaultGreeting(String username) {
return "Hello User!";
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung.spring.cloud.hystrix.rest.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableCircuitBreaker
@EnableHystrixDashboard
@Controller
public class RestConsumerApplication {
@Autowired
private GreetingService greetingService;
public static void main(String[] args) {
SpringApplication.run(RestConsumerApplication.class, args);
}
@RequestMapping("/get-greeting/{username}")
public String getGreeting(Model model, @PathVariable("username") String username) {
model.addAttribute("greeting", greetingService.getGreeting(username));
return "greeting-view";
}
}

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