Merge remote-tracking branch 'origin/master'
This commit is contained in:
commit
4ecead4432
|
@ -0,0 +1,47 @@
|
|||
<?xml version="1.0"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>groovy-spock</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Spock Framework - Example Project</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
</properties>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.5</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
<goal>testCompile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>1.0-groovy-2.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.4.7</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,89 @@
|
|||
import spock.lang.Specification
|
||||
|
||||
class FirstSpecification extends Specification {
|
||||
|
||||
def "one plus one should equal two"() {
|
||||
expect:
|
||||
1 + 1 == 2
|
||||
}
|
||||
|
||||
def "two plus two should equal four"() {
|
||||
given:
|
||||
int left = 2
|
||||
int right = 2
|
||||
|
||||
when:
|
||||
int result = left + right
|
||||
|
||||
then:
|
||||
result == 4
|
||||
}
|
||||
|
||||
def "Should be able to remove from list"() {
|
||||
given:
|
||||
def list = [1, 2, 3, 4]
|
||||
|
||||
when:
|
||||
list.remove(0)
|
||||
|
||||
then:
|
||||
list == [2, 3, 4]
|
||||
}
|
||||
|
||||
def "Should get an index out of bounds when removing a non-existent item"() {
|
||||
given:
|
||||
def list = [1, 2, 3, 4]
|
||||
|
||||
when:
|
||||
list.remove(20)
|
||||
|
||||
then:
|
||||
thrown(IndexOutOfBoundsException)
|
||||
list.size() == 4
|
||||
}
|
||||
|
||||
def "numbers to the power of two"(int a, int b, int c) {
|
||||
expect:
|
||||
Math.pow(a, b) == c
|
||||
|
||||
where:
|
||||
a | b | c
|
||||
1 | 2 | 1
|
||||
2 | 2 | 4
|
||||
3 | 2 | 9
|
||||
}
|
||||
|
||||
def "Should return default value for mock"() {
|
||||
given:
|
||||
def paymentGateway = Mock(PaymentGateway)
|
||||
|
||||
when:
|
||||
def result = paymentGateway.makePayment(12.99)
|
||||
|
||||
then:
|
||||
!result
|
||||
}
|
||||
|
||||
def "Should return true value for mock"() {
|
||||
given:
|
||||
def paymentGateway = Mock(PaymentGateway)
|
||||
paymentGateway.makePayment(20) >> true
|
||||
|
||||
when:
|
||||
def result = paymentGateway.makePayment(20)
|
||||
|
||||
then:
|
||||
result
|
||||
}
|
||||
|
||||
def "Should verify notify was called"() {
|
||||
given:
|
||||
def notifier = Mock(Notifier)
|
||||
|
||||
when:
|
||||
notifier.notify('foo')
|
||||
|
||||
then:
|
||||
1 * notifier.notify('foo')
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
interface Notifier {
|
||||
void notify(String message)
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
interface PaymentGateway {
|
||||
boolean makePayment(BigDecimal amount)
|
||||
}
|
|
@ -0,0 +1,192 @@
|
|||
package org.baeldung.guava;
|
||||
|
||||
import com.google.common.math.DoubleMath;
|
||||
import com.google.common.math.IntMath;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.ExpectedException;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
import static org.hamcrest.core.IsEqual.equalTo;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class GuavaMathTest {
|
||||
@Test
|
||||
public void testIntMathAdd() {
|
||||
try {
|
||||
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.checkedAdd(2, 1);
|
||||
assertThat(result1, equalTo(3));
|
||||
|
||||
int result2 = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathSubtract() {
|
||||
try {
|
||||
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
};
|
||||
|
||||
int result1 = IntMath.checkedSubtract(200, 100);
|
||||
assertThat(result1, equalTo(100));
|
||||
|
||||
int result2 = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
|
||||
assertThat(result2, equalTo(Integer.MIN_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
|
||||
assertThat(result3, equalTo(Integer.MAX_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathMultiply() {
|
||||
try {
|
||||
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.checkedMultiply(21, 3);
|
||||
assertThat(result1, equalTo(63));
|
||||
|
||||
int result2 = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathPow() {
|
||||
try {
|
||||
IntMath.checkedPow(Integer.MAX_VALUE, 2);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
try {
|
||||
IntMath.checkedPow(Integer.MIN_VALUE, 3);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
int result1 = IntMath.saturatedPow(3, 3);
|
||||
assertThat(result1, equalTo(27));
|
||||
|
||||
int result2 = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
|
||||
assertThat(result2, equalTo(Integer.MAX_VALUE));
|
||||
|
||||
int result3 = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
|
||||
assertThat(result3, equalTo(Integer.MIN_VALUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathRound() {
|
||||
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
|
||||
assertThat(result1, equalTo(1));
|
||||
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
|
||||
assertThat(result2, equalTo(2));
|
||||
|
||||
int result3 = IntMath.log2(5, RoundingMode.FLOOR);
|
||||
assertThat(result3, equalTo(2));
|
||||
int result4 = IntMath.log2(5, RoundingMode.CEILING);
|
||||
assertThat(result4, equalTo(3));
|
||||
|
||||
int result5 = IntMath.log10(11, RoundingMode.HALF_UP);
|
||||
assertThat(result5, equalTo(1));
|
||||
|
||||
int result6 = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
|
||||
assertThat(result6, equalTo(2));
|
||||
try {
|
||||
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
|
||||
assertTrue(false);
|
||||
} catch (ArithmeticException e) {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIntMathAdditionalFunctions() {
|
||||
int result1 = IntMath.gcd(15, 20);
|
||||
assertThat(result1, equalTo(5));
|
||||
|
||||
int result2 = IntMath.mod(8, 3);
|
||||
assertThat(result2, equalTo(2));
|
||||
|
||||
boolean result3 = IntMath.isPowerOfTwo(8);
|
||||
assertTrue(result3);
|
||||
boolean result4 = IntMath.isPowerOfTwo(9);
|
||||
assertFalse(result4);
|
||||
|
||||
int result5 = IntMath.factorial(4);
|
||||
assertThat(result5, equalTo(24));
|
||||
|
||||
int result6 = IntMath.binomial(7, 3);
|
||||
assertThat(result6, equalTo(35));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_detect_integer() {
|
||||
boolean result1 = DoubleMath.isMathematicalInteger(2.0);
|
||||
assertThat(result1, equalTo(true));
|
||||
boolean result2 = DoubleMath.isMathematicalInteger(2.1);
|
||||
assertThat(result2, equalTo(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_round_to_integer_types() {
|
||||
int result3 = DoubleMath.roundToInt(2.5, RoundingMode.DOWN);
|
||||
assertThat(result3, equalTo(2));
|
||||
|
||||
long result4 = DoubleMath.roundToLong(2.5, RoundingMode.HALF_UP);
|
||||
assertThat(result4, equalTo(3L));
|
||||
|
||||
BigInteger result5 = DoubleMath.roundToBigInteger(2.5, RoundingMode.UP);
|
||||
assertThat(result5, equalTo(new BigInteger("3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void should_calculate_log_2() {
|
||||
int result6 = DoubleMath.log2(10, RoundingMode.UP);
|
||||
assertThat(result6, equalTo(4));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
About the application
|
||||
---------------------
|
||||
This application demonstrates the usage of JavaEE Web Annotations.
|
||||
|
||||
|
||||
Contents of the application
|
||||
---------------------------
|
||||
1. AccountServlet.java - Demonstrates the @WebServlet and @ServletSecurity annotation.
|
||||
|
||||
NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet component.
|
||||
The usage of its parameters 'urlPatterns' & 'initParams' can be observed.
|
||||
An initialization parameter 'type' is being set to denote the type of the bank account.
|
||||
|
||||
@ServletSecurity annotation imposes security constraints on the AccountServlet based on
|
||||
the tomcat-users.xml (this code assumes there is a role 'admin' in your tomcat-users.xml)
|
||||
|
||||
N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
|
||||
for @ServletSecurity.
|
||||
|
||||
|
||||
2. BankAppServletContextListener.java - Demonstrates the @WebListener annotation for denoting a class as a ServletContextListener.
|
||||
|
||||
NOTES: Sets a Servlet context attribute ATTR_DEFAULT_LANGUAGE to 'english' on web application start up,
|
||||
which can then be used throughout the application.
|
||||
|
||||
|
||||
3. LogInFilter.java - Demonstrates the @WebFilter annotation.
|
||||
|
||||
NOTES: @WebFilter annotation designates the LogInFilter class as a Filter component.
|
||||
It filters all requests to the bank account servlet and redirects them to
|
||||
the login page.
|
||||
|
||||
N.B : To see @WebFilter annotation in action, please uncomment the annotation code for @WebFilter.
|
||||
|
||||
|
||||
4. UploadCustomerDocumentsServlet.java - Demonstrates the @MultipartConfig annotation.
|
||||
|
||||
NOTES: @MultipartConfig anotation designates the UploadCustomerDocumentsServlet Servlet component,
|
||||
to handle multipart/form-data requests.
|
||||
To see it in action, deploy the web application an access the url: http://<your host>:<your port>/JavaEEAnnotationsSample/upload.jsp
|
||||
Once you upload a file from here, it will get uploaded to D:/custDocs (assuming such a folder exists).
|
||||
|
||||
|
||||
5. index.jsp - This is the welcome page.
|
||||
|
||||
NOTES: You can enter a deposit amount here and click on the 'Deposit' button to see the AccountServlet in action.
|
||||
|
||||
6. login.jsp - All requests to the AccountServlet are redirected to this page, if the LogInFilter is imposed.
|
||||
|
||||
7. upload.jsp - Demonstrates the usage of handling multipart/form-data requests by the UploadCustomerDocumentsServlet.
|
||||
|
||||
|
||||
Building and Running the application
|
||||
------------------------------------
|
||||
To build the application:
|
||||
|
||||
1. Open the project in eclipse
|
||||
2. Right click on it in eclispe and choose Run As > Maven build
|
||||
3. Give 'clean install' under Goals
|
||||
4. This should build the WAR file of the application
|
||||
|
||||
To run the application:
|
||||
|
||||
1. Right click on the project
|
||||
2. Run as > Run on Server
|
||||
3. This will start you Tomcat server and deploy the application (Provided that you have configured Tomcat in your eclipse)
|
||||
4. You should now be able to access the url : http://<your host>:<your port>/JavaEEAnnotationsSample
|
|
@ -36,19 +36,15 @@ public class AccountServlet extends javax.servlet.http.HttpServlet {
|
|||
}
|
||||
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
|
||||
double accountBalance = 1000d;
|
||||
double interestRate = Double.parseDouble(request.getAttribute("interest").toString());
|
||||
|
||||
String paramDepositAmt = request.getParameter("dep");
|
||||
double depositAmt = Double.parseDouble(paramDepositAmt);
|
||||
|
||||
accountBalance = accountBalance + depositAmt;
|
||||
|
||||
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html> Balance of " + accountType + " account is: " +
|
||||
accountBalance + "<br> This account bares an interest rate of " + interestRate +
|
||||
" % </html>");
|
||||
writer.println("<html> Balance of " + accountType + " account is: " + accountBalance + "</html>");
|
||||
writer.flush();
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,20 +0,0 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import javax.servlet.ServletRequestEvent;
|
||||
import javax.servlet.ServletRequestListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@WebListener
|
||||
public class DepositRequestListener implements ServletRequestListener {
|
||||
|
||||
public void requestDestroyed(ServletRequestEvent event) {
|
||||
|
||||
}
|
||||
|
||||
public void requestInitialized(ServletRequestEvent evet) {
|
||||
HttpServletRequest req = (HttpServletRequest)evet.getServletRequest();
|
||||
req.setAttribute("interest", new Double(10));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.javaeeannotations;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.MultipartConfig;
|
||||
|
@ -24,6 +25,10 @@ public class UploadCustomerDocumentsServlet extends HttpServlet {
|
|||
for (Part part : request.getParts()) {
|
||||
part.write("myFile");
|
||||
}
|
||||
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.println("<html>File uploaded successfully!</html>");
|
||||
writer.flush();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
organization in ThisBuild := "org.baeldung"
|
||||
|
||||
// the Scala version that will be used for cross-compiled libraries
|
||||
scalaVersion in ThisBuild := "2.11.7"
|
||||
scalaVersion in ThisBuild := "2.11.8"
|
||||
|
||||
lagomKafkaEnabled in ThisBuild := false
|
||||
|
||||
|
@ -38,4 +38,4 @@ lazy val weatherImpl = project("weather-impl")
|
|||
)
|
||||
.dependsOn(weatherApi)
|
||||
|
||||
def project(id: String) = Project(id, base = file(id))
|
||||
def project(id: String) = Project(id, base = file(id))
|
||||
|
|
|
@ -67,6 +67,11 @@
|
|||
<artifactId>jsonassert</artifactId>
|
||||
<version>${jsonassert.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.javers</groupId>
|
||||
<artifactId>javers-core</artifactId>
|
||||
<version>${javers.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
|
@ -78,6 +83,7 @@
|
|||
<javaassist.version>3.21.0-GA</javaassist.version>
|
||||
<assertj.version>3.6.2</assertj.version>
|
||||
<jsonassert.version>1.5.0</jsonassert.version>
|
||||
<javers.version>3.1.0</javers.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.javers;
|
||||
|
||||
|
||||
public class Address {
|
||||
private String country;
|
||||
|
||||
public Address(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.javers;
|
||||
|
||||
public class Person {
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public Person(Integer id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package com.baeldung.javers;
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PersonWithAddress {
|
||||
private Integer id;
|
||||
private String name;
|
||||
private List<Address> address;
|
||||
|
||||
public PersonWithAddress(Integer id, String name, List<Address> address) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<Address> getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(List<Address> address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,113 @@
|
|||
package com.baeldung.javers;
|
||||
|
||||
|
||||
import org.javers.common.collections.Lists;
|
||||
import org.javers.core.Javers;
|
||||
import org.javers.core.JaversBuilder;
|
||||
import org.javers.core.diff.Diff;
|
||||
import org.javers.core.diff.changetype.NewObject;
|
||||
import org.javers.core.diff.changetype.ObjectRemoved;
|
||||
import org.javers.core.diff.changetype.ValueChange;
|
||||
import org.javers.core.diff.changetype.container.ListChange;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class JaversTest {
|
||||
|
||||
@Test
|
||||
public void givenPersonObject_whenApplyModificationOnIt_thenShouldDetectChange() {
|
||||
//given
|
||||
Javers javers = JaversBuilder.javers().build();
|
||||
|
||||
Person person = new Person(1, "Michael Program");
|
||||
Person personAfterModification = new Person(1, "Michael Java");
|
||||
|
||||
//when
|
||||
Diff diff = javers.compare(person, personAfterModification);
|
||||
|
||||
//then
|
||||
ValueChange change = diff.getChangesByType(ValueChange.class).get(0);
|
||||
|
||||
assertThat(diff.getChanges()).hasSize(1);
|
||||
assertThat(change.getPropertyName()).isEqualTo("name");
|
||||
assertThat(change.getLeft()).isEqualTo("Michael Program");
|
||||
assertThat(change.getRight()).isEqualTo("Michael Java");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenListOfPersons_whenCompare_ThenShouldDetectChanges() {
|
||||
//given
|
||||
Javers javers = JaversBuilder.javers().build();
|
||||
Person personThatWillBeRemoved = new Person(2, "Thomas Link");
|
||||
List<Person> oldList = Lists.asList(new Person(1, "Michael Program"), personThatWillBeRemoved);
|
||||
List<Person> newList = Lists.asList(new Person(1, "Michael Not Program"));
|
||||
|
||||
//when
|
||||
Diff diff = javers.compareCollections(oldList, newList, Person.class);
|
||||
|
||||
//then
|
||||
assertThat(diff.getChanges()).hasSize(3);
|
||||
|
||||
|
||||
ValueChange valueChange = diff.getChangesByType(ValueChange.class).get(0);
|
||||
assertThat(valueChange.getPropertyName()).isEqualTo("name");
|
||||
assertThat(valueChange.getLeft()).isEqualTo("Michael Program");
|
||||
assertThat(valueChange.getRight()).isEqualTo("Michael Not Program");
|
||||
|
||||
ObjectRemoved objectRemoved = diff.getChangesByType(ObjectRemoved.class).get(0);
|
||||
assertThat(objectRemoved.getAffectedObject().get().equals(personThatWillBeRemoved)).isTrue();
|
||||
|
||||
ListChange listChange = diff.getChangesByType(ListChange.class).get(0);
|
||||
assertThat(listChange.getValueRemovedChanges().size()).isEqualTo(1);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfPerson_whenPersonHasNewAddress_thenDetectThatChange() {
|
||||
//given
|
||||
Javers javers = JaversBuilder.javers().build();
|
||||
|
||||
PersonWithAddress person =
|
||||
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
|
||||
|
||||
PersonWithAddress personWithNewAddress =
|
||||
new PersonWithAddress(1, "Tom",
|
||||
Arrays.asList(new Address("England"), new Address("USA")));
|
||||
|
||||
|
||||
//when
|
||||
Diff diff = javers.compare(person, personWithNewAddress);
|
||||
List objectsByChangeType = diff.getObjectsByChangeType(NewObject.class);
|
||||
|
||||
//then
|
||||
assertThat(objectsByChangeType).hasSize(1);
|
||||
assertThat(objectsByChangeType.get(0).equals(new Address("USA")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListOfPerson_whenPersonRemovedAddress_thenDetectThatChange() {
|
||||
//given
|
||||
Javers javers = JaversBuilder.javers().build();
|
||||
|
||||
PersonWithAddress person =
|
||||
new PersonWithAddress(1, "Tom", Arrays.asList(new Address("England")));
|
||||
|
||||
PersonWithAddress personWithNewAddress =
|
||||
new PersonWithAddress(1, "Tom", Collections.emptyList());
|
||||
|
||||
|
||||
//when
|
||||
Diff diff = javers.compare(person, personWithNewAddress);
|
||||
List objectsByChangeType = diff.getObjectsByChangeType(ObjectRemoved.class);
|
||||
|
||||
//then
|
||||
assertThat(objectsByChangeType).hasSize(1);
|
||||
assertThat(objectsByChangeType.get(0).equals(new Address("England")));
|
||||
}
|
||||
}
|
1
pom.xml
1
pom.xml
|
@ -43,6 +43,7 @@
|
|||
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
|
||||
|
||||
|
||||
<module>groovy-spock</module>
|
||||
<module>gson</module>
|
||||
<module>guava</module>
|
||||
<module>guava18</module>
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class FailureAnalyzerApplication {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(FailureAnalyzerApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
|
||||
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
||||
import org.springframework.boot.diagnostics.FailureAnalysis;
|
||||
|
||||
public class MyBeanNotOfRequiredTypeFailureAnalyzer extends AbstractFailureAnalyzer<BeanNotOfRequiredTypeException> {
|
||||
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, BeanNotOfRequiredTypeException cause) {
|
||||
return new FailureAnalysis(getDescription(cause), getAction(cause), cause);
|
||||
}
|
||||
|
||||
private String getDescription(BeanNotOfRequiredTypeException ex) {
|
||||
return "The bean " + ex.getBeanName() //
|
||||
+ " could not be injected as " + ex.getRequiredType().getName() //
|
||||
+ " because it is of type " + ex.getActualType().getName();
|
||||
}
|
||||
|
||||
private String getAction(BeanNotOfRequiredTypeException ex) {
|
||||
return "Consider creating a bean with name "+ ex.getBeanName() //
|
||||
+ " of type " + ex.getRequiredType().getName();
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
public class MyDAO {
|
||||
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository("myDAO")
|
||||
public class MySecondDAO {
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.failureanalyzer;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class MyService {
|
||||
|
||||
@Resource(name = "myDAO")
|
||||
private MyDAO myDAO;
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
org.springframework.boot.diagnostics.FailureAnalyzer=com.baeldung.failureanalyzer.MyBeanNotOfRequiredTypeFailureAnalyzer
|
|
@ -0,0 +1,4 @@
|
|||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
|
@ -0,0 +1,13 @@
|
|||
###The Course
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
###Relevant Articles:
|
||||
- [Quick Guide to @RestClientTest in Spring Boot](http://www.baeldung.com/restclienttest-in-spring-boot)
|
||||
- [Intro to Spring Boot Starters](http://www.baeldung.com/spring-boot-starters)
|
||||
- [A Guide to Spring in Eclipse STS](http://www.baeldung.com/eclipse-sts-spring)
|
||||
- [Introduction to WebJars](http://www.baeldung.com/maven-webjars)
|
||||
- [Create a Fat Jar App with Spring Boot](http://www.baeldung.com/deployable-fat-jar-spring-boot)
|
||||
- [The @ServletComponentScan Annotation in Spring Boot](http://www.baeldung.com/spring-servletcomponentscan)
|
||||
- [A Custom Data Binder in Spring MVC](http://www.baeldung.com/spring-mvc-custom-data-binder)
|
||||
- [Intro to Building an Application with Spring Boot](http://www.baeldung.com/intro-to-spring-boot)
|
||||
- [How to Register a Servlet in a Java Web Application](http://www.baeldung.com/register-servlet)
|
|
@ -0,0 +1,224 @@
|
|||
<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>spring-boot</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>spring-boot</name>
|
||||
<description>This is simple boot application for Spring boot actuator test</description>
|
||||
|
||||
<!-- Inherit defaults from Spring Boot -->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.5.2.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-core</artifactId>
|
||||
<version>${tomcat.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat.embed</groupId>
|
||||
<artifactId>tomcat-embed-jasper</artifactId>
|
||||
<version>${tomcat.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>io.dropwizard.metrics</groupId>
|
||||
<artifactId>metrics-core</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.jayway.jsonpath</groupId>
|
||||
<artifactId>json-path</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.subethamail</groupId>
|
||||
<artifactId>subethasmtp</artifactId>
|
||||
<version>${subethasmtp.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>bootstrap</artifactId>
|
||||
<version>${bootstrap.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.webjars</groupId>
|
||||
<artifactId>jquery</artifactId>
|
||||
<version>${jquery.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>18.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.tomcat</groupId>
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
<version>${tomee-servlet-api.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>spring-boot</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>pl.project13.maven</groupId>
|
||||
<artifactId>git-commit-id-plugin</artifactId>
|
||||
<version>${git-commit-id-plugin.version}</version>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*IntegrationTest.java</exclude>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>integration-test</phase>
|
||||
<goals>
|
||||
<goal>test</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/*LiveTest.java</exclude>
|
||||
</excludes>
|
||||
<includes>
|
||||
<include>**/*IntegrationTest.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<test.mime>json</test.mime>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
|
||||
<properties>
|
||||
<!-- The main class to start by executing java -jar -->
|
||||
<start-class>org.baeldung.boot.DemoApplication</start-class>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<spring.version>4.3.4.RELEASE</spring.version>
|
||||
<git-commit-id-plugin.version>2.2.1</git-commit-id-plugin.version>
|
||||
<jquery.version>3.1.1</jquery.version>
|
||||
<bootstrap.version>3.3.7-1</bootstrap.version>
|
||||
<subethasmtp.version>3.1.7</subethasmtp.version>
|
||||
<tomee-servlet-api.version>8.5.11</tomee-servlet-api.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,25 @@
|
|||
package com.baeldung.annotation.servletcomponentscan;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
|
||||
/**
|
||||
* using the following annotations are equivalent:
|
||||
* <ul><li>
|
||||
* <code>@ServletComponentScan</code>
|
||||
* </li><li>
|
||||
* <code>@ServletComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")</code>
|
||||
* </li><li>
|
||||
* <code>@ServletComponentScan(basePackageClasses = {AttrListener.class, HelloFilter.class, HelloServlet.class, EchoServlet.class})</code>
|
||||
* </li></ul>
|
||||
*/
|
||||
@SpringBootApplication
|
||||
@ServletComponentScan("com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootAnnotatedApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringBootAnnotatedApp.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.annotation.servletcomponentscan;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = "com.baeldung.annotation.servletcomponentscan.components")
|
||||
public class SpringBootPlainApp {
|
||||
|
||||
public static void main(String[] args) {
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
import javax.servlet.ServletContextListener;
|
||||
import javax.servlet.annotation.WebListener;
|
||||
|
||||
@WebListener
|
||||
public class AttrListener implements ServletContextListener {
|
||||
|
||||
@Override
|
||||
public void contextInitialized(ServletContextEvent servletContextEvent) {
|
||||
servletContextEvent
|
||||
.getServletContext()
|
||||
.setAttribute("servlet-context-attr", "test");
|
||||
System.out.println("context init");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent servletContextEvent) {
|
||||
System.out.println("context destroy");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
@WebServlet(name = "echo servlet", urlPatterns = "/echo")
|
||||
public class EchoServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
public void doPost(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
Path path = File
|
||||
.createTempFile("echo", "tmp")
|
||||
.toPath();
|
||||
Files.copy(request.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.copy(path, response.getOutputStream());
|
||||
Files.delete(path);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.annotation.WebFilter;
|
||||
import javax.servlet.annotation.WebInitParam;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebFilter(urlPatterns = "/hello", description = "a filter for hello servlet", initParams = { @WebInitParam(name = "msg", value = "filtering ") }, filterName = "hello filter", servletNames = { "echo servlet" })
|
||||
public class HelloFilter implements Filter {
|
||||
|
||||
private FilterConfig filterConfig;
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
System.out.println("filter init");
|
||||
this.filterConfig = filterConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
servletResponse
|
||||
.getOutputStream()
|
||||
.print(filterConfig.getInitParameter("msg"));
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
System.out.println("filter destroy");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.annotation.servletcomponentscan.components;
|
||||
|
||||
import javax.servlet.ServletConfig;
|
||||
import javax.servlet.annotation.WebInitParam;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(urlPatterns = "/hello", initParams = { @WebInitParam(name = "msg", value = "hello")})
|
||||
public class HelloServlet extends HttpServlet {
|
||||
|
||||
private ServletConfig servletConfig;
|
||||
|
||||
@Override
|
||||
public void init(ServletConfig servletConfig){
|
||||
this.servletConfig = servletConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doGet(HttpServletRequest request, HttpServletResponse response) {
|
||||
try {
|
||||
response
|
||||
.getOutputStream()
|
||||
.write(servletConfig.getInitParameter("msg").getBytes());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.git;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
@SpringBootApplication(scanBasePackages = { "com.baeldung.git" })
|
||||
public class CommitIdApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CommitIdApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
|
||||
PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
|
||||
c.setLocation(new ClassPathResource("git.properties"));
|
||||
c.setIgnoreResourceNotFound(true);
|
||||
c.setIgnoreUnresolvablePlaceholders(true);
|
||||
return c;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package com.baeldung.git;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class CommitInfoController {
|
||||
|
||||
@Value("${git.commit.message.short}")
|
||||
private String commitMessage;
|
||||
|
||||
@Value("${git.branch}")
|
||||
private String branch;
|
||||
|
||||
@Value("${git.commit.id}")
|
||||
private String commitId;
|
||||
|
||||
@RequestMapping("/commitId")
|
||||
public Map<String, String> getCommitId() {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
result.put("Commit message", commitMessage);
|
||||
result.put("Commit branch", branch);
|
||||
result.put("Commit id", commitId);
|
||||
return result;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Injecting Git Information Into Spring](http://www.baeldung.com/spring-git-information)
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.internationalization;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class InternationalizationApp {
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("security.basic.enabled", "false");
|
||||
SpringApplication.run(InternationalizationApp.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package com.baeldung.internationalization.config;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
|
||||
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan(basePackages = "com.baeldung.internationalization.config")
|
||||
public class MvcConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
SessionLocaleResolver slr = new SessionLocaleResolver();
|
||||
slr.setDefaultLocale(Locale.US);
|
||||
return slr;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public LocaleChangeInterceptor localeChangeInterceptor() {
|
||||
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
|
||||
lci.setParamName("lang");
|
||||
return lci;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.internationalization.config;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class PageController {
|
||||
|
||||
@GetMapping("/international")
|
||||
public String getInternationalPage() {
|
||||
return "international";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.intro;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
SpringApplication.run(App.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.intro.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class HomeController {
|
||||
|
||||
@RequestMapping("/")
|
||||
public String root(){
|
||||
return "Index Page";
|
||||
}
|
||||
|
||||
@RequestMapping("/local")
|
||||
public String local(){
|
||||
return "/local";
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.servlets;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
||||
|
||||
@SpringBootApplication
|
||||
public class ApplicationMain extends SpringBootServletInitializer {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ApplicationMain.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||
return application.sources(ApplicationMain.class);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package com.baeldung.servlets.configuration;
|
||||
|
||||
import org.springframework.web.WebApplicationInitializer;
|
||||
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
||||
import org.springframework.web.context.support.XmlWebApplicationContext;
|
||||
import org.springframework.web.servlet.DispatcherServlet;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRegistration;
|
||||
|
||||
public class WebAppInitializer implements WebApplicationInitializer {
|
||||
|
||||
public void onStartup(ServletContext container) throws ServletException {
|
||||
|
||||
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
|
||||
ctx.register(WebMvcConfigure.class);
|
||||
ctx.setServletContext(container);
|
||||
|
||||
ServletRegistration.Dynamic servletOne = container.addServlet("SpringProgrammaticDispatcherServlet", new DispatcherServlet(ctx));
|
||||
servletOne.setLoadOnStartup(1);
|
||||
servletOne.addMapping("/");
|
||||
|
||||
XmlWebApplicationContext xctx = new XmlWebApplicationContext();
|
||||
xctx.setConfigLocation("/WEB-INF/context.xml");
|
||||
xctx.setServletContext(container);
|
||||
|
||||
ServletRegistration.Dynamic servletTwo = container.addServlet("SpringProgrammaticXMLDispatcherServlet", new DispatcherServlet(xctx));
|
||||
servletTwo.setLoadOnStartup(1);
|
||||
servletTwo.addMapping("/");
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.servlets.configuration;
|
||||
|
||||
import org.springframework.boot.web.support.ErrorPageFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
import org.springframework.web.servlet.resource.PathResourceResolver;
|
||||
import org.springframework.web.servlet.view.InternalResourceViewResolver;
|
||||
|
||||
@Configuration
|
||||
public class WebMvcConfigure extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Bean
|
||||
public ViewResolver getViewResolver() {
|
||||
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
|
||||
resolver.setPrefix("/WEB-INF/");
|
||||
resolver.setSuffix(".jsp");
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
|
||||
configurer.enable();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(3600).resourceChain(true).addResolver(new PathResourceResolver());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ErrorPageFilter errorPageFilter() {
|
||||
return new ErrorPageFilter();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.servlets.props;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
public final class Constants {
|
||||
|
||||
@Autowired
|
||||
PropertySourcesLoader psl;
|
||||
|
||||
public static final String breakLine = System.getProperty("line.separator");
|
||||
private static final PropertyLoader pl = new PropertyLoader();
|
||||
private static final Properties mainProps = pl.getProperties("custom.properties");
|
||||
public static final String DISPATCHER_SERVLET_NAME = mainProps.getProperty("dispatcher.servlet.name");
|
||||
public static final String DISPATCHER_SERVLET_MAPPING = mainProps.getProperty("dispatcher.servlet.mapping");
|
||||
private final String EXAMPLE_SERVLET_NAME = psl.getProperty("example.servlet.name");
|
||||
private final String EXAMPLE_SERVLET_MAPPING = psl.getProperty("example.servlet.mapping");
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.servlets.props;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
public class PropertyLoader {
|
||||
private static final Logger log = LoggerFactory.getLogger(PropertyLoader.class);
|
||||
|
||||
public Properties getProperties(String file) {
|
||||
Properties prop = new Properties();
|
||||
InputStream input = null;
|
||||
try {
|
||||
input = getClass().getResourceAsStream(file);
|
||||
prop.load(input);
|
||||
if (input != null) {
|
||||
input.close();
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
log.error("IOException: " + ex);
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.servlets.props;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.PropertySource;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan(basePackages = { "com.baeldung.*" })
|
||||
@PropertySource("classpath:custom.properties") public class PropertySourcesLoader {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PropertySourcesLoader.class);
|
||||
|
||||
@Autowired
|
||||
ConfigurableEnvironment env;
|
||||
|
||||
public String getProperty(String key) {
|
||||
return env.getProperty(key);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.servlets.servlets;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class GenericCustomServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
response.setContentType("text/html");
|
||||
PrintWriter out = response.getWriter();
|
||||
out.println("<p>Hello World</p>");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.servlets.servlets.javaee;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.annotation.WebServlet;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@WebServlet(name = "AnnotationServlet",
|
||||
description = "Example Servlet Using Annotations",
|
||||
urlPatterns = { "/annotationservlet" })
|
||||
public class AnnotationServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
request.getRequestDispatcher("/annotationservlet.jsp").forward(request, response);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.servlets.servlets.javaee;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class EEWebXmlServlet extends HttpServlet {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
response.setContentType("text/html");
|
||||
PrintWriter out = response.getWriter();
|
||||
out.println("<p>Hello World</p>");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.servlets.servlets.springboot;
|
||||
|
||||
import com.baeldung.servlets.servlets.GenericCustomServlet;
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class SpringRegistrationBeanServlet {
|
||||
|
||||
@Bean
|
||||
public ServletRegistrationBean genericCustomServlet() {
|
||||
ServletRegistrationBean bean = new ServletRegistrationBean(new GenericCustomServlet(), "/springregistrationbeanservlet/*");
|
||||
bean.setLoadOnStartup(1);
|
||||
return bean;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.servlets.servlets.springboot.embedded;
|
||||
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
|
||||
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class EmbeddedTomcatExample {
|
||||
|
||||
@Bean
|
||||
public EmbeddedServletContainerFactory servletContainer() {
|
||||
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
|
||||
return tomcat;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.utils;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages="com.baeldung.utils")
|
||||
public class Application {
|
||||
|
||||
@RolesAllowed("*")
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.utils.controller;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.ServletRequestBindingException;
|
||||
import org.springframework.web.bind.ServletRequestUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.util.WebUtils;
|
||||
|
||||
@Controller
|
||||
public class UtilsController {
|
||||
|
||||
@GetMapping("/utils")
|
||||
public String webUtils(Model model) {
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@PostMapping("/setParam")
|
||||
public String post(HttpServletRequest request, Model model) {
|
||||
String param = ServletRequestUtils.getStringParameter(request, "param", "DEFAULT");
|
||||
|
||||
// Long param = ServletRequestUtils.getLongParameter(request, "param",1L);
|
||||
// boolean param = ServletRequestUtils.getBooleanParameter(request, "param", true);
|
||||
// double param = ServletRequestUtils.getDoubleParameter(request, "param", 1000);
|
||||
// float param = ServletRequestUtils.getFloatParameter(request, "param", (float) 1.00);
|
||||
// int param = ServletRequestUtils.getIntParameter(request, "param", 100);
|
||||
|
||||
// try {
|
||||
// ServletRequestUtils.getRequiredStringParameter(request, "param");
|
||||
// } catch (ServletRequestBindingException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
|
||||
WebUtils.setSessionAttribute(request, "parameter", param);
|
||||
model.addAttribute("parameter", "You set: "+(String) WebUtils.getSessionAttribute(request, "parameter"));
|
||||
return "utils";
|
||||
}
|
||||
|
||||
@GetMapping("/other")
|
||||
public String other(HttpServletRequest request, Model model) {
|
||||
String param = (String) WebUtils.getSessionAttribute(request, "parameter");
|
||||
model.addAttribute("parameter", param);
|
||||
return "other";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.webjar;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class TestController {
|
||||
|
||||
@RequestMapping(value = "/")
|
||||
public String welcome(Model model) {
|
||||
return "index";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.webjar;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
public class WebjarsdemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebjarsdemoApplication.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
@org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
public class Application {
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package org.baeldung.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "demo");
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package org.baeldung.boot.components;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.baeldung.boot.repository.FooRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class FooService {
|
||||
|
||||
@Autowired
|
||||
private FooRepository fooRepository;
|
||||
|
||||
public Foo getFooWithId(Integer id) throws Exception {
|
||||
return fooRepository.findOne(id);
|
||||
}
|
||||
|
||||
public Foo getFooWithName(String name) {
|
||||
return fooRepository.findByName(name);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class CommonException extends RuntimeException{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 3080004140659213332L;
|
||||
|
||||
public CommonException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.boot.exceptions;
|
||||
|
||||
public class FooNotFoundException extends RuntimeException{
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 9042200028456133589L;
|
||||
|
||||
public FooNotFoundException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
package org.baeldung.boot.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Foo implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
@Id
|
||||
@GeneratedValue
|
||||
private Integer id;
|
||||
private String name;
|
||||
|
||||
public Foo() {
|
||||
}
|
||||
|
||||
public Foo(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
|
||||
public Foo(Integer id, String name) {
|
||||
super();
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package org.baeldung.boot.repository;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface FooRepository extends JpaRepository<Foo, Integer> {
|
||||
public Foo findByName(String name);
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package org.baeldung.boot.service;
|
||||
|
||||
import org.baeldung.boot.components.FooService;
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class FooController {
|
||||
|
||||
@Autowired
|
||||
private FooService fooService;
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public Foo getFooWithId(@PathVariable Integer id) throws Exception {
|
||||
return fooService.getFooWithId(id);
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public Foo getFooWithName(@RequestParam String name) throws Exception {
|
||||
return fooService.getFooWithName(name);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
package org.baeldung.client;
|
||||
|
||||
public class Details {
|
||||
|
||||
private String name;
|
||||
|
||||
private String login;
|
||||
|
||||
public Details() {
|
||||
}
|
||||
|
||||
public Details(String name, String login) {
|
||||
this.name = name;
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package org.baeldung.client;
|
||||
|
||||
import org.springframework.boot.web.client.RestTemplateBuilder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Service
|
||||
public class DetailsServiceClient {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
public DetailsServiceClient(RestTemplateBuilder restTemplateBuilder) {
|
||||
restTemplate = restTemplateBuilder.build();
|
||||
}
|
||||
|
||||
public Details getUserDetails(String name) {
|
||||
return restTemplate.getForObject("/{name}/details", Details.class, name);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
package org.baeldung.common.error;
|
||||
|
||||
import org.springframework.boot.autoconfigure.web.ErrorController;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
public class MyCustomErrorController implements ErrorController {
|
||||
|
||||
private static final String PATH = "/error";
|
||||
|
||||
public MyCustomErrorController() {
|
||||
// TODO Auto-generated constructor stub
|
||||
}
|
||||
|
||||
@RequestMapping(value = PATH)
|
||||
public String error() {
|
||||
return "Error heaven";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getErrorPath() {
|
||||
return PATH;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package org.baeldung.common.error;
|
||||
|
||||
import org.springframework.boot.web.servlet.ServletRegistrationBean;
|
||||
|
||||
import javax.servlet.Servlet;
|
||||
|
||||
public class SpringHelloServletRegistrationBean extends ServletRegistrationBean {
|
||||
|
||||
public SpringHelloServletRegistrationBean() {
|
||||
}
|
||||
|
||||
public SpringHelloServletRegistrationBean(Servlet servlet, String... urlMappings) {
|
||||
super(servlet, urlMappings);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.common.error.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class ErrorController {
|
||||
|
||||
public ErrorController() {
|
||||
}
|
||||
|
||||
@RequestMapping("/400")
|
||||
String error400() {
|
||||
return "Error Code: 400 occured.";
|
||||
}
|
||||
|
||||
@RequestMapping("/errorHeaven")
|
||||
String errorHeaven() {
|
||||
return "You have reached the heaven of errors!!!";
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package org.baeldung.common.properties;
|
||||
|
||||
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
|
||||
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
|
||||
import org.springframework.boot.web.servlet.ErrorPage;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MyServletContainerCustomizationBean implements EmbeddedServletContainerCustomizer {
|
||||
|
||||
public MyServletContainerCustomizationBean() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customize(ConfigurableEmbeddedServletContainer container) {
|
||||
container.setPort(8084);
|
||||
container.setContextPath("/springbootapp");
|
||||
|
||||
container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
|
||||
container.addErrorPages(new ErrorPage("/errorHeaven"));
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package org.baeldung.common.resources;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
|
||||
import org.springframework.boot.ExitCodeGenerator;
|
||||
|
||||
public class ExecutorServiceExitCodeGenerator implements ExitCodeGenerator {
|
||||
|
||||
private ExecutorService executorService;
|
||||
|
||||
public ExecutorServiceExitCodeGenerator(ExecutorService executorService) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getExitCode() {
|
||||
int returnCode = 0;
|
||||
try {
|
||||
if (!Objects.isNull(executorService)) {
|
||||
executorService.shutdownNow();
|
||||
returnCode = 1;
|
||||
}
|
||||
} catch (SecurityException ex) {
|
||||
returnCode = 0;
|
||||
}
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package org.baeldung.config;
|
||||
|
||||
import org.baeldung.web.resolver.HeaderVersionArgumentResolver;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
|
||||
argumentResolvers.add(new HeaderVersionArgumentResolver());
|
||||
}
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package org.baeldung.controller;
|
||||
|
||||
import org.baeldung.domain.GenericEntity;
|
||||
import org.baeldung.domain.Modes;
|
||||
import org.baeldung.web.resolver.Version;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
public class GenericEntityController {
|
||||
private List<GenericEntity> entityList = new ArrayList<>();
|
||||
|
||||
{
|
||||
entityList.add(new GenericEntity(1l, "entity_1"));
|
||||
entityList.add(new GenericEntity(2l, "entity_2"));
|
||||
entityList.add(new GenericEntity(3l, "entity_3"));
|
||||
entityList.add(new GenericEntity(4l, "entity_4"));
|
||||
}
|
||||
|
||||
@RequestMapping("/entity/all")
|
||||
public List<GenericEntity> findAll() {
|
||||
return entityList;
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/entity", method = RequestMethod.POST)
|
||||
public GenericEntity addEntity(GenericEntity entity) {
|
||||
entityList.add(entity);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@RequestMapping("/entity/findby/{id}")
|
||||
public GenericEntity findById(@PathVariable Long id) {
|
||||
return entityList.stream().filter(entity -> entity.getId().equals(id)).findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbydate/{date}")
|
||||
public GenericEntity findByDate(@PathVariable("date") LocalDateTime date) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbymode/{mode}")
|
||||
public GenericEntity findByEnum(@PathVariable("mode") Modes mode) {
|
||||
return entityList.stream().findFirst().get();
|
||||
}
|
||||
|
||||
@GetMapping("/entity/findbyversion")
|
||||
public ResponseEntity findByVersion(@Version String version) {
|
||||
return version != null ? new ResponseEntity(entityList.stream().findFirst().get(), HttpStatus.OK) : new ResponseEntity(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.baeldung.controller.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class HelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public HelloWorldServlet() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("HelloWorldServlet: GET METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("HelloWorldServlet: POST METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package org.baeldung.controller.servlet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class SpringHelloWorldServlet extends HttpServlet {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public SpringHelloWorldServlet() {
|
||||
super();
|
||||
}
|
||||
|
||||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("SpringHelloWorldServlet: GET METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||||
PrintWriter out = null;
|
||||
try {
|
||||
out = response.getWriter();
|
||||
out.println("SpringHelloWorldServlet: POST METHOD");
|
||||
out.flush();
|
||||
} finally {
|
||||
if (!Objects.isNull(out))
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package org.baeldung.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.convert.converter.ConverterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
|
||||
|
||||
private static class StringToEnumConverter<T extends Enum> implements Converter<String, T> {
|
||||
|
||||
private Class<T> enumType;
|
||||
|
||||
public StringToEnumConverter(Class<T> enumType) {
|
||||
this.enumType = enumType;
|
||||
}
|
||||
|
||||
public T convert(String source) {
|
||||
return (T) Enum.valueOf(this.enumType, source.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T extends Enum> Converter<String, T> getConverter(final Class<T> targetType) {
|
||||
return new StringToEnumConverter(targetType);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package org.baeldung.converter;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
@Component
|
||||
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
|
||||
|
||||
@Override
|
||||
public LocalDateTime convert(final String source) {
|
||||
return LocalDateTime.parse(source, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,42 @@
|
|||
package org.baeldung.domain;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class GenericEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||
private Long id;
|
||||
private String value;
|
||||
|
||||
public GenericEntity() {
|
||||
}
|
||||
|
||||
public GenericEntity(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public GenericEntity(Long id, String value) {
|
||||
this.id = id;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
package org.baeldung.domain;
|
||||
|
||||
public enum Modes {
|
||||
|
||||
ALPHA, BETA;
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package org.baeldung.endpoints;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CustomEndpoint implements Endpoint<List<String>> {
|
||||
|
||||
public CustomEndpoint() {
|
||||
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return "customEndpoint";
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isSensitive() {
|
||||
return true;
|
||||
}
|
||||
|
||||
public List<String> invoke() {
|
||||
// Your logic to display the output
|
||||
List<String> messages = new ArrayList<String>();
|
||||
messages.add("This is message 1");
|
||||
messages.add("This is message 2");
|
||||
return messages;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package org.baeldung.endpoints;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.Endpoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class ListEndpoints extends AbstractEndpoint<List<Endpoint>> {
|
||||
private List<Endpoint> endpoints;
|
||||
|
||||
@Autowired
|
||||
public ListEndpoints(List<Endpoint> endpoints) {
|
||||
super("listEndpoints");
|
||||
this.endpoints = endpoints;
|
||||
}
|
||||
|
||||
public List<Endpoint> invoke() {
|
||||
return this.endpoints;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package org.baeldung.endpoints;
|
||||
|
||||
import org.springframework.boot.actuate.health.Health;
|
||||
import org.springframework.boot.actuate.health.HealthIndicator;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class MyHealthCheck implements HealthIndicator {
|
||||
|
||||
public Health health() {
|
||||
int errorCode = check(); // perform some specific health check
|
||||
if (errorCode != 0) {
|
||||
return Health.down().withDetail("Error Code", errorCode).withDetail("Description", "You custom MyHealthCheck endpoint is down").build();
|
||||
}
|
||||
return Health.up().build();
|
||||
}
|
||||
|
||||
public int check() {
|
||||
// Your logic to check health
|
||||
return 1;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package org.baeldung.main;
|
||||
|
||||
import org.baeldung.common.error.SpringHelloServletRegistrationBean;
|
||||
import org.baeldung.common.resources.ExecutorServiceExitCodeGenerator;
|
||||
import org.baeldung.controller.servlet.HelloWorldServlet;
|
||||
import org.baeldung.controller.servlet.SpringHelloWorldServlet;
|
||||
import org.baeldung.service.LoginService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@RestController
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan({ "org.baeldung.common.error", "org.baeldung.common.error.controller", "org.baeldung.common.properties", "org.baeldung.common.resources", "org.baeldung.endpoints", "org.baeldung.service", "org.baeldung.monitor.jmx", "org.baeldung.service" })
|
||||
public class SpringBootApplication {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Autowired
|
||||
private LoginService service;
|
||||
|
||||
@RequestMapping("/")
|
||||
String home() {
|
||||
service.login("admin", "admin".toCharArray());
|
||||
return "TADA!!! You are in Spring Boot Actuator test application.";
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
applicationContext = SpringApplication.run(SpringBootApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ExecutorService executorService() {
|
||||
return Executors.newFixedThreadPool(10);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HelloWorldServlet helloWorldServlet() {
|
||||
return new HelloWorldServlet();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SpringHelloServletRegistrationBean servletRegistrationBean() {
|
||||
SpringHelloServletRegistrationBean bean = new SpringHelloServletRegistrationBean(new SpringHelloWorldServlet(), "/springHelloWorld/*");
|
||||
bean.setLoadOnStartup(1);
|
||||
bean.addInitParameter("message", "SpringHelloWorldServlet special message");
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Autowired
|
||||
public ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator(ExecutorService executorService) {
|
||||
return new ExecutorServiceExitCodeGenerator(executorService);
|
||||
}
|
||||
|
||||
public void shutDown(ExecutorServiceExitCodeGenerator executorServiceExitCodeGenerator) {
|
||||
SpringApplication.exit(applicationContext, executorServiceExitCodeGenerator);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package org.baeldung.monitor.jmx;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.codahale.metrics.JmxReporter;
|
||||
import com.codahale.metrics.MetricRegistry;
|
||||
|
||||
@Configuration
|
||||
public class MonitoringConfig {
|
||||
@Autowired
|
||||
private MetricRegistry registry;
|
||||
|
||||
@Bean
|
||||
public JmxReporter jmxReporter() {
|
||||
JmxReporter reporter = JmxReporter.forRegistry(registry).build();
|
||||
reporter.start();
|
||||
return reporter;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
package org.baeldung.repository;
|
||||
|
||||
import org.baeldung.domain.GenericEntity;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface GenericEntityRepository extends JpaRepository<GenericEntity, Long> {
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package org.baeldung.service;
|
||||
|
||||
public interface LoginService {
|
||||
public boolean login(String userName, char[] password);
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
package org.baeldung.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.metrics.CounterService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class LoginServiceImpl implements LoginService {
|
||||
|
||||
private CounterService counterService;
|
||||
|
||||
@Autowired
|
||||
public LoginServiceImpl(CounterService counterService) {
|
||||
this.counterService = counterService;
|
||||
}
|
||||
|
||||
public boolean login(String userName, char[] password) {
|
||||
boolean success;
|
||||
if (userName.equals("admin") && "secret".toCharArray().equals(password)) {
|
||||
counterService.increment("counter.login.success");
|
||||
success = true;
|
||||
} else {
|
||||
counterService.increment("counter.login.failure");
|
||||
success = false;
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package org.baeldung.session.exception;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
|
||||
|
||||
@EntityScan(basePackageClasses = Foo.class)
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
public static void main(String[] args) {
|
||||
System.setProperty("spring.config.name", "exception");
|
||||
System.setProperty("spring.profiles.active", "exception");
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public HibernateJpaSessionFactoryBean sessionFactory() {
|
||||
return new HibernateJpaSessionFactoryBean();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package org.baeldung.session.exception.repository;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
|
||||
public interface FooRepository {
|
||||
|
||||
void save(Foo foo);
|
||||
|
||||
Foo get(Integer id);
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package org.baeldung.session.exception.repository;
|
||||
|
||||
import org.baeldung.boot.model.Foo;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Profile("exception")
|
||||
@Repository
|
||||
public class FooRepositoryImpl implements FooRepository {
|
||||
@Autowired
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
@Override
|
||||
public void save(Foo foo) {
|
||||
sessionFactory.getCurrentSession().saveOrUpdate(foo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Foo get(Integer id) {
|
||||
return sessionFactory.getCurrentSession().get(Foo.class, id);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package org.baeldung.web.resolver;
|
||||
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||
import org.springframework.web.context.request.NativeWebRequest;
|
||||
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
@Component
|
||||
public class HeaderVersionArgumentResolver implements HandlerMethodArgumentResolver {
|
||||
|
||||
@Override
|
||||
public boolean supportsParameter(final MethodParameter methodParameter) {
|
||||
return methodParameter.getParameterAnnotation(Version.class) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object resolveArgument(final MethodParameter methodParameter, final ModelAndViewContainer modelAndViewContainer, final NativeWebRequest nativeWebRequest, final WebDataBinderFactory webDataBinderFactory) throws Exception {
|
||||
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
|
||||
|
||||
return request.getHeader("Version");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
package org.baeldung.web.resolver;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.PARAMETER)
|
||||
public @interface Version {
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
server.port=8080
|
||||
server.contextPath=/springbootapp
|
||||
management.port=8081
|
||||
management.address=127.0.0.1
|
||||
|
||||
endpoints.shutdown.enabled=true
|
||||
|
||||
endpoints.jmx.domain=Spring Sample Application
|
||||
endpoints.jmx.uniqueNames=true
|
||||
|
||||
##jolokia.config.debug=true
|
||||
##endpoints.jolokia.enabled=true
|
||||
##endpoints.jolokia.path=jolokia
|
||||
|
||||
spring.jmx.enabled=true
|
||||
endpoints.jmx.enabled=true
|
||||
|
||||
## for pretty printing of json when endpoints accessed over HTTP
|
||||
http.mappers.jsonPrettyPrint=true
|
||||
|
||||
## Configuring info endpoint
|
||||
info.app.name=Spring Sample Application
|
||||
info.app.description=This is my first spring boot application G1
|
||||
info.app.version=1.0.0
|
||||
|
||||
## Spring Security Configurations
|
||||
security.user.name=admin1
|
||||
security.user.password=secret1
|
||||
management.security.role=SUPERUSER
|
||||
|
||||
logging.level.org.springframework=INFO
|
||||
|
||||
#Servlet Configuration
|
||||
servlet.name=dispatcherExample
|
||||
servlet.mapping=/dispatcherExampleURL
|
||||
|
||||
#banner.charset=UTF-8
|
||||
#banner.location=classpath:banner.txt
|
||||
#banner.image.location=classpath:banner.gif
|
||||
#banner.image.width= //TODO
|
||||
#banner.image.height= //TODO
|
||||
#banner.image.margin= //TODO
|
||||
#banner.image.invert= //TODO
|
|
@ -0,0 +1,14 @@
|
|||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@#@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@...@@@@@@@@@:..@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@#. @@@@@* *@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@#o @@@@@* @@@@@* @@@:*.*@@@@@@@: *8@@@ @@@@&:.#@. @o**@@@@**:@o*o@@:.:@@@@@:.o#@&*:@@@@
|
||||
@@@@@@@@@@@@* @@@@@* 8888 8@ @@@8 #@o 8@# .@ @@* :. @* @@@@ @. : &@ ** .@@@@
|
||||
@@@@@@@@@@. @ o@@@@@* *@@@o::& .* 8@@@@. @@ 8@@@@. @* @@@@ @. @@@& * @@@@# .@@@@
|
||||
@@@@@@@@@& @ @@@@@@* @@@@@@ 8 @@@@ .. o&&&&&&& @@ #@@@@. @* @@@@ @. @@@# * @@@@@ .@@@@
|
||||
@@@@@@@@@ @@o @@@@@@@* oooo* 8 @@@& @* @@@ # 88. 88. *& o#: @. @@@# *@ &#& .@@@@
|
||||
@@@@@@@@# @@@8 @@@@@@@* .*@@@#. *@@ @@@& :#@@@o .@@: *&@8 @o o@@: @. @@@# *@@#. :8# .@@@@
|
||||
@@@@@@@@@ @@@@ &@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@# o@@@@ @@@@@
|
||||
@@@@@& &@@@@ 8@@@@@@@@@8&8@@@@@#8#@@@o8@#&@@o&@@@&@@8@@&@@@@88@@8#@8&@@##@@@@@@#8@@#8@@88@@@@@ *@@@@@@@
|
||||
@@@# #@@@@#. @@@@@@@@@@@@@8@@8#o@&#@@@@o.@o*@@*.@@@.@&:8o8*@@@8&@@#@@@8@@@@8@#@@@8&@@@@@@#@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
|
@ -0,0 +1,4 @@
|
|||
dispatcher.servlet.name=dispatcherExample
|
||||
dispatcher.servlet.mapping=/dispatcherExampleURL
|
||||
example.servlet.name=dispatcherExample
|
||||
example.servlet.mapping=/dispatcherExampleURL
|
|
@ -0,0 +1,6 @@
|
|||
spring.output.ansi.enabled=never
|
||||
server.port=7070
|
||||
|
||||
# Security
|
||||
security.user.name=admin
|
||||
security.user.password=password
|
|
@ -0,0 +1,14 @@
|
|||
<configuration>
|
||||
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -0,0 +1,4 @@
|
|||
greeting=Hello! Welcome to our website!
|
||||
lang.change=Change the language
|
||||
lang.eng=English
|
||||
lang.fr=French
|
|
@ -0,0 +1,4 @@
|
|||
greeting=Bonjour! Bienvenue sur notre site!
|
||||
lang.change=Changez la langue
|
||||
lang.eng=Anglais
|
||||
lang.fr=Francais
|
|
@ -0,0 +1,8 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>RESOURCE NOT FOUND</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>404 RESOURCE NOT FOUND</h1>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,19 @@
|
|||
<html>
|
||||
<head>
|
||||
<title>WebJars Demo</title>
|
||||
<link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="container"><br/>
|
||||
<div class="alert alert-success">
|
||||
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
|
||||
<strong>Success!</strong> It is working as we expected.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/webjars/jquery/3.1.1/jquery.min.js"></script>
|
||||
<script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,29 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="ISO-8859-1" />
|
||||
<title>Home</title>
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function() {
|
||||
$("#locales").change(function () {
|
||||
var selectedOption = $('#locales').val();
|
||||
if (selectedOption != ''){
|
||||
window.location.replace('international?lang=' + selectedOption);
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1 th:text="#{greeting}"></h1>
|
||||
|
||||
<br /><br />
|
||||
<span th:text="#{lang.change}"></span>:
|
||||
<select id="locales">
|
||||
<option value=""></option>
|
||||
<option value="en" th:text="#{lang.eng}"></option>
|
||||
<option value="fr" th:text="#{lang.fr}"></option>
|
||||
</select>
|
||||
</body>
|
||||
</html>
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue