Merge branch 'master' of https://github.com/eugenp/tutorials into public-access-modifier

This commit is contained in:
m.raheem 2019-08-21 16:49:28 +02:00
commit 484a2e4d65
162 changed files with 997 additions and 154 deletions

View File

@ -4,7 +4,7 @@ import org.apache.commons.lang3.StringUtils;
public class PrintTriangleExamples {
public static String printARightAngledTriangle(int N) {
public static String printARightTriangle(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
for (int j = 1; j <= r; j++) {
@ -29,6 +29,17 @@ public class PrintTriangleExamples {
return result.toString();
}
public static String printAnIsoscelesTriangleUsingStringUtils(int N) {
StringBuilder result = new StringBuilder();
for (int r = 1; r <= N; r++) {
result.append(StringUtils.repeat(' ', N - r));
result.append(StringUtils.repeat('*', 2 * r - 1));
result.append(System.lineSeparator());
}
return result.toString();
}
public static String printAnIsoscelesTriangleUsingSubstring(int N) {
StringBuilder result = new StringBuilder();
String helperString = StringUtils.repeat(' ', N - 1) + StringUtils.repeat('*', N * 2 - 1);
@ -41,8 +52,9 @@ public class PrintTriangleExamples {
}
public static void main(String[] args) {
System.out.println(printARightAngledTriangle(5));
System.out.println(printARightTriangle(5));
System.out.println(printAnIsoscelesTriangle(5));
System.out.println(printAnIsoscelesTriangleUsingStringUtils(5));
System.out.println(printAnIsoscelesTriangleUsingSubstring(5));
}

View File

@ -9,9 +9,9 @@ import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class PrintTriangleExamplesUnitTest {
private static Object[][] rightAngledTriangles() {
String expected0 = "";
private static Object[][] rightTriangles() {
String expected0 = "";
String expected2 = "*" + System.lineSeparator()
+ "**" + System.lineSeparator();
@ -39,9 +39,9 @@ public class PrintTriangleExamplesUnitTest {
}
@Test
@Parameters(method = "rightAngledTriangles")
public void whenPrintARightAngledTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightAngledTriangle(nrOfRows);
@Parameters(method = "rightTriangles")
public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printARightTriangle(nrOfRows);
assertEquals(expected, actual);
}
@ -81,6 +81,14 @@ public class PrintTriangleExamplesUnitTest {
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")
public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) {
String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows);
assertEquals(expected, actual);
}
@Test
@Parameters(method = "isoscelesTriangles")

View File

@ -1,4 +1,4 @@
package com.baeldung.algorithms.stringsortingbynumber;
package com.baeldung.algorithms.sort.bynumber;
import java.util.Comparator;

View File

@ -1,6 +1,6 @@
package com.baeldung.algorithms.stringsortingbynumber;
package com.baeldung.algorithms.sort.bynumber;
import com.baeldung.algorithms.stringsortingbynumber.NaturalOrderComparators;
import com.baeldung.algorithms.sort.bynumber.NaturalOrderComparators;
import org.junit.Test;
import java.util.ArrayList;

130
java-jdi/pom.xml Normal file
View File

@ -0,0 +1,130 @@
<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>
<artifactId>java-jdi</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>java-jdi</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${tools.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>java-jdi</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</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>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.6.1</assertj.version>
<tool.version>1.8</tool.version>
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<tools.version>1.8</tools.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.jdi;
public class JDIExample {
public static void main(String[] args) {
String jpda = "Java Platform Debugger Architecture";
System.out.println("Hi Everyone, Welcome to " + jpda); //add a break point here
String jdi = "Java Debug Interface"; //add a break point here and also stepping in here
String text = "Today, we'll dive into " + jdi;
System.out.println(text);
}
}

View File

@ -0,0 +1,171 @@
package com.baeldung.jdi;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.Bootstrap;
import com.sun.jdi.ClassType;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.LocalVariable;
import com.sun.jdi.Location;
import com.sun.jdi.StackFrame;
import com.sun.jdi.VMDisconnectedException;
import com.sun.jdi.Value;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.LaunchingConnector;
import com.sun.jdi.connect.VMStartException;
import com.sun.jdi.event.BreakpointEvent;
import com.sun.jdi.event.ClassPrepareEvent;
import com.sun.jdi.event.Event;
import com.sun.jdi.event.EventSet;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.event.StepEvent;
import com.sun.jdi.request.BreakpointRequest;
import com.sun.jdi.request.ClassPrepareRequest;
import com.sun.jdi.request.StepRequest;
public class JDIExampleDebugger {
private Class debugClass;
private int[] breakPointLines;
public Class getDebugClass() {
return debugClass;
}
public void setDebugClass(Class debugClass) {
this.debugClass = debugClass;
}
public int[] getBreakPointLines() {
return breakPointLines;
}
public void setBreakPointLines(int[] breakPointLines) {
this.breakPointLines = breakPointLines;
}
/**
* Sets the debug class as the main argument in the connector and launches the VM
* @return VirtualMachine
* @throws IOException
* @throws IllegalConnectorArgumentsException
* @throws VMStartException
*/
public VirtualMachine connectAndLaunchVM() throws IOException, IllegalConnectorArgumentsException, VMStartException {
LaunchingConnector launchingConnector = Bootstrap.virtualMachineManager().defaultConnector();
Map<String, Connector.Argument> arguments = launchingConnector.defaultArguments();
arguments.get("main").setValue(debugClass.getName());
VirtualMachine vm = launchingConnector.launch(arguments);
return vm;
}
/**
* Creates a request to prepare the debug class, add filter as the debug class and enables it
* @param vm
*/
public void enableClassPrepareRequest(VirtualMachine vm) {
ClassPrepareRequest classPrepareRequest = vm.eventRequestManager().createClassPrepareRequest();
classPrepareRequest.addClassFilter(debugClass.getName());
classPrepareRequest.enable();
}
/**
* Sets the break points at the line numbers mentioned in breakPointLines array
* @param vm
* @param event
* @throws AbsentInformationException
*/
public void setBreakPoints(VirtualMachine vm, ClassPrepareEvent event) throws AbsentInformationException {
ClassType classType = (ClassType) event.referenceType();
for(int lineNumber: breakPointLines) {
Location location = classType.locationsOfLine(lineNumber).get(0);
BreakpointRequest bpReq = vm.eventRequestManager().createBreakpointRequest(location);
bpReq.enable();
}
}
/**
* Displays the visible variables
* @param event
* @throws IncompatibleThreadStateException
* @throws AbsentInformationException
*/
public void displayVariables(LocatableEvent event) throws IncompatibleThreadStateException, AbsentInformationException {
StackFrame stackFrame = event.thread().frame(0);
if(stackFrame.location().toString().contains(debugClass.getName())) {
Map<LocalVariable, Value> visibleVariables = stackFrame.getValues(stackFrame.visibleVariables());
System.out.println("Variables at " +stackFrame.location().toString() + " > ");
for (Map.Entry<LocalVariable, Value> entry : visibleVariables.entrySet()) {
System.out.println(entry.getKey().name() + " = " + entry.getValue());
}
}
}
/**
* Enables step request for a break point
* @param vm
* @param event
*/
public void enableStepRequest(VirtualMachine vm, BreakpointEvent event) {
//enable step request for last break point
if(event.location().toString().contains(debugClass.getName()+":"+breakPointLines[breakPointLines.length-1])) {
StepRequest stepRequest = vm.eventRequestManager().createStepRequest(event.thread(), StepRequest.STEP_LINE, StepRequest.STEP_OVER);
stepRequest.enable();
}
}
public static void main(String[] args) throws Exception {
JDIExampleDebugger debuggerInstance = new JDIExampleDebugger();
debuggerInstance.setDebugClass(JDIExample.class);
int[] breakPoints = {6, 9};
debuggerInstance.setBreakPointLines(breakPoints);
VirtualMachine vm = null;
try {
vm = debuggerInstance.connectAndLaunchVM();
debuggerInstance.enableClassPrepareRequest(vm);
EventSet eventSet = null;
while ((eventSet = vm.eventQueue().remove()) != null) {
for (Event event : eventSet) {
if (event instanceof ClassPrepareEvent) {
debuggerInstance.setBreakPoints(vm, (ClassPrepareEvent)event);
}
if (event instanceof BreakpointEvent) {
event.request().disable();
debuggerInstance.displayVariables((BreakpointEvent) event);
debuggerInstance.enableStepRequest(vm, (BreakpointEvent)event);
}
if (event instanceof StepEvent) {
debuggerInstance.displayVariables((StepEvent) event);
}
vm.resume();
}
}
} catch (VMDisconnectedException e) {
System.out.println("Virtual Machine is disconnected.");
} catch (Exception e) {
e.printStackTrace();
}
finally {
InputStreamReader reader = new InputStreamReader(vm.process().getInputStream());
OutputStreamWriter writer = new OutputStreamWriter(System.out);
char[] buf = new char[512];
reader.read(buf);
writer.write(buf);
writer.flush();
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.lcm;
import java.math.BigInteger;
public class BigIntegerLCM {
public static BigInteger lcm(BigInteger number1, BigInteger number2) {
BigInteger gcd = number1.gcd(number2);
BigInteger absProduct = number1.multiply(number2).abs();
return absProduct.divide(gcd);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.lcm;
import java.util.Arrays;
public class EuclideanAlgorithm {
public static int gcd(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return number1 + number2;
} else {
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int biggerValue = Math.max(absNumber1, absNumber2);
int smallerValue = Math.min(absNumber1, absNumber2);
return gcd(biggerValue % smallerValue, smallerValue);
}
}
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0)
return 0;
else {
int gcd = gcd(number1, number2);
return Math.abs(number1 * number2) / gcd;
}
}
public static int lcmForArray(int[] numbers) {
int lcm = numbers[0];
for (int i = 1; i <= numbers.length - 1; i++) {
lcm = lcm(lcm, numbers[i]);
}
return lcm;
}
public static int lcmByLambda(int... numbers) {
return Arrays.stream(numbers).reduce(1, (lcmSoFar, currentNumber) -> Math.abs(lcmSoFar * currentNumber) / gcd(lcmSoFar, currentNumber));
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.lcm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class PrimeFactorizationAlgorithm {
public static Map<Integer, Integer> getPrimeFactors(int number) {
int absNumber = Math.abs(number);
Map<Integer, Integer> primeFactorsMap = new HashMap<Integer, Integer>();
for (int factor = 2; factor <= absNumber; factor++) {
while (absNumber % factor == 0) {
Integer power = primeFactorsMap.get(factor);
if (power == null) {
power = 0;
}
primeFactorsMap.put(factor, power + 1);
absNumber /= factor;
}
}
return primeFactorsMap;
}
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return 0;
}
Map<Integer, Integer> primeFactorsForNum1 = getPrimeFactors(number1);
Map<Integer, Integer> primeFactorsForNum2 = getPrimeFactors(number2);
Set<Integer> primeFactorsUnionSet = new HashSet<Integer>(primeFactorsForNum1.keySet());
primeFactorsUnionSet.addAll(primeFactorsForNum2.keySet());
int lcm = 1;
for (Integer primeFactor : primeFactorsUnionSet) {
lcm *= Math.pow(primeFactor, Math.max(primeFactorsForNum1.getOrDefault(primeFactor, 0),
primeFactorsForNum2.getOrDefault(primeFactor, 0)));
}
return lcm;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.lcm;
public class SimpleAlgorithm {
public static int lcm(int number1, int number2) {
if (number1 == 0 || number2 == 0) {
return 0;
}
int absNumber1 = Math.abs(number1);
int absNumber2 = Math.abs(number2);
int absHigherNumber = Math.max(absNumber1, absNumber2);
int absLowerNumber = Math.min(absNumber1, absNumber2);
int lcm = absHigherNumber;
while (lcm % absLowerNumber != 0) {
lcm += absHigherNumber;
}
return lcm;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigInteger;
public class BigIntegerLCMUnitTest {
@Test
public void testLCM() {
BigInteger number1 = new BigInteger("12");
BigInteger number2 = new BigInteger("18");
BigInteger expectedLCM = new BigInteger("36");
Assert.assertEquals(expectedLCM, BigIntegerLCM.lcm(number1, number2));
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
public class EuclideanAlgorithmUnitTest {
@Test
public void testGCD() {
Assert.assertEquals(6, EuclideanAlgorithm.gcd(12, 18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, EuclideanAlgorithm.lcm(12, 18));
}
@Test
public void testLCMForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmForArray(new int[]{3, 5, 15}));
}
@Test
public void testLCMByLambdaForArray() {
Assert.assertEquals(15, EuclideanAlgorithm.lcmByLambda(new int[]{3, 5, 15}));
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.baeldung.lcm.PrimeFactorizationAlgorithm.*;
public class PrimeFactorizationAlgorithmUnitTest {
@Test
public void testGetPrimeFactors() {
Map<Integer, Integer> expectedPrimeFactorsMapForTwelve = new HashMap<>();
expectedPrimeFactorsMapForTwelve.put(2, 2);
expectedPrimeFactorsMapForTwelve.put(3, 1);
Map<Integer, Integer> expectedPrimeFactorsMapForEighteen = new HashMap<>();
expectedPrimeFactorsMapForEighteen.put(2, 1);
expectedPrimeFactorsMapForEighteen.put(3, 2);
Assert.assertEquals(expectedPrimeFactorsMapForTwelve, getPrimeFactors(12));
Assert.assertEquals(expectedPrimeFactorsMapForEighteen, getPrimeFactors(18));
}
@Test
public void testLCM() {
Assert.assertEquals(36, PrimeFactorizationAlgorithm.lcm(12, 18));
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.lcm;
import org.junit.Assert;
import org.junit.Test;
import static com.baeldung.lcm.SimpleAlgorithm.*;
public class SimpleAlgorithmUnitTest {
@Test
public void testLCM() {
Assert.assertEquals(36, lcm(12, 18));
}
}

View File

@ -86,6 +86,24 @@
<version>${spectator-api.version}</version>
</dependency>
<dependency>
<groupId>io.astefanutti.metrics.aspectj</groupId>
<artifactId>metrics-aspectj</artifactId>
<version>${metrics-aspectj.version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.astefanutti.metrics.aspectj</groupId>
<artifactId>metrics-aspectj-deps</artifactId>
<version>${metrics-aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
@ -104,6 +122,7 @@
<spectator-api.version>0.57.1</spectator-api.version>
<spring-boot-starter-web.version>2.0.7.RELEASE</spring-boot-starter-web.version>
<assertj-core.version>3.11.1</assertj-core.version>
<metrics-aspectj.version>1.1.0</metrics-aspectj.version>
</properties>
</project>

View File

@ -0,0 +1,34 @@
package com.baeldung.metrics.aspectj;
import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import java.io.PrintStream;
import java.util.concurrent.TimeUnit;
public class MetricsAspectJMain {
private static final MetricRegistry REGISTRY = new MetricRegistry();
public static void main(String args[]) throws InterruptedException {
startReport();
ObjectRunner runner = new ObjectRunner();
for (int i = 0; i < 5; i++) {
runner.run();
}
Thread.sleep(3000L);
}
private static void startReport() {
SharedMetricRegistries.add(ObjectRunner.REGISTRY_NAME, REGISTRY);
ConsoleReporter.forRegistry(REGISTRY)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.outputTo(new PrintStream(System.out))
.build()
.start(3, TimeUnit.SECONDS);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.metrics.aspectj;
import com.codahale.metrics.annotation.Timed;
import io.astefanutti.metrics.aspectj.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Metrics( registry = ObjectRunner.REGISTRY_NAME)
public class ObjectRunner {
private static final Logger logger = LoggerFactory.getLogger(ObjectRunner.class);
public static final String REGISTRY_NAME = "ObjectRunner";
@Timed(name = "timerName")
public void run() {
logger.info("run");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
}
}
}

View File

@ -457,6 +457,7 @@
<module>java-collections-conversions</module>
<module>java-collections-maps</module>
<module>java-collections-maps-2</module>
<module>java-jdi</module>
<!-- <module>java-dates</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>java-dates-2</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<!-- <module>java-ee-8-security-api</module> --> <!-- long running -->
@ -1156,6 +1157,7 @@
<module>java-collections-conversions</module>
<module>java-collections-maps</module>
<module>java-collections-maps-2</module>
<module>java-jdi</module>
<!-- <module>java-dates</module> --> <!-- We haven't upgraded to java 9. Fixing in BAEL-10841 -->
<module>java-ee-8-security-api</module>
<module>java-lite</module>

View File

@ -0,0 +1,17 @@
package com.baeldung.validation.listvalidation;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@ComponentScan(basePackages = "com.baeldung.validation.listvalidation")
@Configuration
@SpringBootApplication
public class SpringListValidationApplication {
public static void main(String[] args) {
SpringApplication.run(SpringListValidationApplication.class, args);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.validation.listvalidation.constraint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.Payload;
@Constraint(validatedBy = MaxSizeConstraintValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaxSizeConstraint {
String message() default "The input list cannot contain more than 4 movies.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,21 @@
package com.baeldung.validation.listvalidation.constraint;
import java.util.List;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import com.baeldung.validation.listvalidation.model.Movie;
public class MaxSizeConstraintValidator implements ConstraintValidator<MaxSizeConstraint, List<Movie>> {
@Override
public boolean isValid(List<Movie> values, ConstraintValidatorContext context) {
boolean isValid = true;
if (values.size() > 4) {
isValid = false;
}
return isValid;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.validation.listvalidation.controller;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.validation.listvalidation.constraint.MaxSizeConstraint;
import com.baeldung.validation.listvalidation.model.Movie;
import com.baeldung.validation.listvalidation.service.MovieService;
@Validated
@RestController
@RequestMapping("/movies")
public class MovieController {
@Autowired
private MovieService movieService;
@PostMapping
public void addAll(@RequestBody @NotEmpty(message = "Input movie list cannot be empty.") @MaxSizeConstraint List<@Valid Movie> movies) {
movieService.addAll(movies);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.validation.listvalidation.exception;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ConstraintViolationExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(ConstraintViolationExceptionHandler.class);
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) {
Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
String errorMessage = "";
if (!violations.isEmpty()) {
StringBuilder builder = new StringBuilder();
violations.forEach(violation -> builder.append("\n" + violation.getMessage()));
errorMessage = builder.toString();
} else {
errorMessage = "ConstraintViolationException occured.";
}
logger.error(errorMessage);
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.validation.listvalidation.model;
import java.util.UUID;
import javax.validation.constraints.NotEmpty;
public class Movie {
private String id;
@NotEmpty(message = "Movie name cannot be empty.")
private String name;
public Movie(String name) {
this.id = UUID.randomUUID()
.toString();
this.name = name;
}
public Movie(){
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.validation.listvalidation.service;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baeldung.validation.listvalidation.model.Movie;
@Service
public class MovieService {
private final Logger logger = LoggerFactory.getLogger(MovieService.class);
private static List<Movie> moviesData;
static {
moviesData = new ArrayList<>();
Movie m1 = new Movie("MovieABC");
moviesData.add(m1);
Movie m2 = new Movie("MovieDEF");
moviesData.add(m2);
}
public Movie get(String name) {
Movie movie = null;
for (Movie m : moviesData) {
if (name.equalsIgnoreCase(m.getName())) {
movie = m;
logger.info("Found movie with name {} : {} ", name, movie);
}
}
return movie;
}
public void add(Movie movie) {
if (get(movie.getName()) == null) {
moviesData.add(movie);
logger.info("Added new movie - {}", movie.getName());
}
}
public void addAll(List<Movie> movies) {
for (Movie movie : movies) {
add(movie);
}
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.validation.listvalidation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.baeldung.validation.listvalidation.model.Movie;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringListValidationApplication.class)
@AutoConfigureMockMvc
public class MovieControllerIntegrationTest {
@Autowired
private MockMvc mvc;
ObjectMapper objectMapper = new ObjectMapper();
@Test
public void givenValidMovieList_whenAddingMovieList_thenIsOK() throws Exception {
List<Movie> movies = new ArrayList<>();
Movie movie = new Movie("Movie3");
movies.add(movie);
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isOk());
}
@Test
public void givenEmptyMovieList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
List<Movie> movies = new ArrayList<>();
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
@Test
public void givenEmptyMovieName_whenAddingMovieList_thenThrowBadRequest() throws Exception {
Movie movie = new Movie("");
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(Arrays.asList(movie))))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
@Test
public void given5MoviesInputList_whenAddingMovieList_thenThrowBadRequest() throws Exception {
Movie movie1 = new Movie("Movie1");
Movie movie2 = new Movie("Movie2");
Movie movie3 = new Movie("Movie3");
Movie movie4 = new Movie("Movie4");
Movie movie5 = new Movie("Movie5");
List<Movie> movies = new ArrayList<>();
movies.add(movie1);
movies.add(movie2);
movies.add(movie3);
movies.add(movie4);
movies.add(movie5);
mvc.perform(MockMvcRequestBuilders.post("/movies")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(movies)))
.andExpect(MockMvcResultMatchers.status()
.isBadRequest());
}
}

View File

@ -7,7 +7,7 @@
<artifactId>spring-security-mvc-boot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-mvc-boot</name>
<packaging>pom</packaging>
<packaging>war</packaging>
<description>Spring Security MVC Boot</description>
<parent>
@ -46,6 +46,20 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
@ -214,13 +228,22 @@
</profile>
</profiles>
<modules>
<module>spring-security-mvc-boot-default</module>
<module>spring-security-mvc-boot-mysql</module>
<module>spring-security-mvc-boot-postgre</module>
</modules>
<properties>
<start-class>org.baeldung.custom.Application</start-class>
<!--If you want to run the example with the voters comment the tag
above and uncomment the one below -->
<!--<start-class>org.baeldung.voter.VoterApplication</start-class> -->
<!--If you want to run the example with the multiple logins, comment
the tag above and uncomment the one below -->
<!--<start-class>org.baeldung.multiplelogin.MultipleLoginApplication</start-class> -->
<!--If you want to run the example with the multiple http elements,
comment the tag above and uncomment the one below -->
<!--<start-class>org.baeldung.multipleentrypoints.MultipleEntryPointsApplication</start-class> -->
<!--If you want to run the example with the Https enabled endpoints,
comment the tag above and uncomment the one below -->
<!-- <start-class>org.baeldung.ssl.HttpsEnabledApplication</start-class> -->
<taglibs-standard.version>1.1.2</taglibs-standard.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<ehcache-core.version>2.6.11</ehcache-core.version>

View File

@ -1,42 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-mvc-boot-default</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-mvc-boot-default</name>
<packaging>jar</packaging>
<description>Spring Security MVC Boot</description>
<parent>
<artifactId>spring-security-mvc-boot</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<properties>
<start-class>org.baeldung.custom.Application</start-class>
<!--If you want to run the example with the voters comment the tag
above and uncomment the one below -->
<!--<start-class>org.baeldung.voter.VoterApplication</start-class> -->
<!--If you want to run the example with the multiple logins, comment
the tag above and uncomment the one below -->
<!--<start-class>org.baeldung.multiplelogin.MultipleLoginApplication</start-class> -->
<!--If you want to run the example with the multiple http elements,
comment the tag above and uncomment the one below -->
<!--<start-class>org.baeldung.multipleentrypoints.MultipleEntryPointsApplication</start-class>-->
<!--If you want to run the example with the Https enabled endpoints,
comment the tag above and uncomment the one below -->
<!-- <start-class>org.baeldung.ssl.HttpsEnabledApplication</start-class> -->
</properties>
</project>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-mvc-boot-mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-mvc-boot-mysql</name>
<packaging>jar</packaging>
<description>Spring Security MVC Boot using MySQL</description>
<parent>
<artifactId>spring-security-mvc-boot</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-mvc-boot-postgre</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-security-mvc-boot-postgre</name>
<packaging>jar</packaging>
<description>Spring Security MVC Boot using PostgreSQL</description>
<parent>
<artifactId>spring-security-mvc-boot</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,17 +0,0 @@
package com.baeldung.jdbcauthentication.postgre;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbcauthentication.postgre.PostgreJdbcAuthenticationApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PostgreJdbcAuthenticationApplication.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -18,7 +18,7 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
@PropertySource("classpath:persistence-h2.properties")
@PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"})
@EnableJpaRepositories(basePackages = { "com.baeldung.data.repositories" })
@EnableWebMvc
@Import(SpringSecurityConfig.class)

View File

@ -3,8 +3,10 @@ package org.baeldung.custom;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-defaults.properties")
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);

View File

@ -3,8 +3,10 @@ package org.baeldung.ip;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-defaults.properties")
public class IpApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(IpApplication.class, args);

View File

@ -2,10 +2,12 @@ package org.baeldung.jdbcauthentication.h2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@SpringBootApplication
@EnableWebSecurity
@PropertySource("classpath:application-defaults.properties")
public class H2JdbcAuthenticationApplication {
public static void main(String[] args) {

View File

@ -1,9 +1,11 @@
package com.baeldung.jdbcauthentication.mysql;
package org.baeldung.jdbcauthentication.mysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-mysql.properties")
public class MySqlJdbcAuthenticationApplication {
public static void main(String[] args) {

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbcauthentication.mysql.web;
package org.baeldung.jdbcauthentication.mysql.web;
import java.security.Principal;

View File

@ -1,9 +1,11 @@
package com.baeldung.jdbcauthentication.postgre;
package org.baeldung.jdbcauthentication.postgre;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-postgre.properties")
public class PostgreJdbcAuthenticationApplication {
public static void main(String[] args) {

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbcauthentication.postgre.web;
package org.baeldung.jdbcauthentication.postgre.web;
import java.security.Principal;

View File

@ -2,8 +2,10 @@ package org.baeldung.multipleauthproviders;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-defaults.properties")
// @ImportResource({ "classpath*:spring-security-multiple-auth-providers.xml" })
public class MultipleAuthProvidersApplication {
public static void main(String[] args) {

View File

@ -2,8 +2,10 @@ package org.baeldung.multipleentrypoints;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-defaults.properties")
// @ImportResource({"classpath*:spring-security-multiple-entry.xml"})
public class MultipleEntryPointsApplication {
public static void main(String[] args) {

View File

@ -3,8 +3,10 @@ package org.baeldung.multiplelogin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@SpringBootApplication
@PropertySource("classpath:application-defaults.properties")
@ComponentScan("org.baeldung.multiplelogin")
public class MultipleLoginApplication {
public static void main(String[] args) {

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