Update README.md

This commit is contained in:
Jonathan Cook
2019-10-13 23:40:45 +02:00
committed by GitHub
parent db85c8f275
commit d17e102e39
20392 changed files with 1639367 additions and 0 deletions
@@ -0,0 +1,13 @@
package org.baeldung;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@@ -0,0 +1,25 @@
package org.baeldung;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ExampleAspect {
@Around("@annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
final long start = System.currentTimeMillis();
final Object proceed = joinPoint.proceed();
final long executionTime = System.currentTimeMillis() - start;
System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
}
@@ -0,0 +1,11 @@
package org.baeldung;
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.METHOD)
public @interface LogExecutionTime {
}
@@ -0,0 +1,12 @@
package org.baeldung;
import org.springframework.stereotype.Component;
@Component
public class Service {
@LogExecutionTime
public void serve() throws InterruptedException {
Thread.sleep(2000);
}
}
@@ -0,0 +1,13 @@
package org.baeldung.aspectj;
public class Account {
int balance = 20;
public boolean withdraw(int amount) {
if (balance < amount) {
return false;
}
balance = balance - amount;
return true;
}
}
@@ -0,0 +1,29 @@
package org.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public aspect AccountAspect {
private static final Logger logger = LoggerFactory.getLogger(AccountAspect.class);
final int MIN_BALANCE = 10;
pointcut callWithDraw(int amount, Account account):
call(boolean Account.withdraw(int)) && args(amount) && target(account);
before(int amount, Account account) : callWithDraw(amount, account) {
logger.info(" Balance before withdrawal: {}", account.balance);
logger.info(" Withdraw ammout: {}", amount);
}
boolean around(int amount, Account account) : callWithDraw(amount, account) {
if (account.balance < amount) {
logger.info("Withdrawal Rejected!");
return false;
}
return proceed(amount, account);
}
after(int amount, Account balance) : callWithDraw(amount, balance) {
logger.info("Balance after withdrawal : {}", balance.balance);
}
}
@@ -0,0 +1,12 @@
package org.baeldung.aspectj;
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.METHOD)
public @interface Secured {
public boolean isLocked() default false;
}
@@ -0,0 +1,23 @@
package org.baeldung.aspectj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SecuredMethod {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethod.class);
@Secured(isLocked = true)
public void lockedMethod() throws Exception {
logger.info("lockedMethod");
}
@Secured(isLocked = false)
public void unlockedMethod() {
logger.info("unlockedMethod");
}
public static void main(String[] args) throws Exception {
SecuredMethod sv = new SecuredMethod();
sv.lockedMethod();
}
}
@@ -0,0 +1,27 @@
package org.baeldung.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class SecuredMethodAspect {
private static final Logger logger = LoggerFactory.getLogger(SecuredMethodAspect.class);
@Pointcut("@annotation(secured)")
public void callAt(Secured secured) {
}
@Around("callAt(secured)")
public Object around(ProceedingJoinPoint pjp, Secured secured) throws Throwable {
if (secured.isLocked()) {
logger.info(pjp.getSignature().toLongString() + " is locked");
return null;
} else {
return pjp.proceed();
}
}
}
@@ -0,0 +1,13 @@
package org.baeldung.logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdderAfterAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void afterAdvice() throws Throwable {
logger.info("I'm done calling the method");
}
}
@@ -0,0 +1,13 @@
package org.baeldung.logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdderAfterReturnAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void afterReturn(final Object returnValue) throws Throwable {
logger.info("value return was {}", returnValue);
}
}
@@ -0,0 +1,13 @@
package org.baeldung.logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdderAfterThrowAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void afterThrow(final Exception exception) throws Throwable {
logger.info("Exception thrown was {}", exception.getMessage());
}
}
@@ -0,0 +1,18 @@
package org.baeldung.logger;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdderAroundAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public Object aroundAdvice(final ProceedingJoinPoint joinPoint) throws Throwable {
logger.info("Arguments passed to method are: " + Arrays.toString(joinPoint.getArgs()));
final Object result = joinPoint.proceed();
logger.info("Result from method is: " + result);
return result;
}
}
@@ -0,0 +1,13 @@
package org.baeldung.logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AdderBeforeAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public void beforeAdvice() throws Throwable {
logger.info("I would be executed just before method starts");
}
}
@@ -0,0 +1,12 @@
package org.baeldung.logger;
public class SampleAdder {
public int add(int a, int b) {
if (a < 0 || b < 0) {
throw new IllegalArgumentException("Make sure all the arguments are greater than zero.");
}
return a + b;
}
}
@@ -0,0 +1,59 @@
package org.baeldung.performancemonitor;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.interceptor.PerformanceMonitorInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import java.time.LocalDate;
import java.time.Month;
@Configuration
@EnableAspectJAutoProxy
public class AopConfiguration {
@Pointcut("execution(public String org.baeldung.performancemonitor.PersonService.getFullName(..))")
public void monitor() { }
@Pointcut("execution(public int org.baeldung.performancemonitor.PersonService.getAge(..))")
public void myMonitor() { }
@Bean
public PerformanceMonitorInterceptor performanceMonitorInterceptor() {
return new PerformanceMonitorInterceptor(true);
}
@Bean
public Advisor performanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.monitor()");
return new DefaultPointcutAdvisor(pointcut, performanceMonitorInterceptor());
}
@Bean
public Person person(){
return new Person("John","Smith", LocalDate.of(1980, Month.JANUARY, 12));
}
@Bean
public PersonService personService(){
return new PersonService();
}
@Bean
public MyPerformanceMonitorInterceptor myPerformanceMonitorInterceptor() {
return new MyPerformanceMonitorInterceptor(true);
}
@Bean
public Advisor myPerformanceMonitorAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("org.baeldung.performancemonitor.AopConfiguration.myMonitor()");
return new DefaultPointcutAdvisor(pointcut, myPerformanceMonitorInterceptor());
}
}
@@ -0,0 +1,39 @@
package org.baeldung.performancemonitor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.springframework.aop.interceptor.AbstractMonitoringInterceptor;
import java.util.Date;
public class MyPerformanceMonitorInterceptor extends AbstractMonitoringInterceptor {
public MyPerformanceMonitorInterceptor() {
}
public MyPerformanceMonitorInterceptor(boolean useDynamicLogger) {
setUseDynamicLogger(useDynamicLogger);
}
@Override
protected Object invokeUnderTrace(MethodInvocation invocation, Log log) throws Throwable {
String name = createInvocationTraceName(invocation);
long start = System.currentTimeMillis();
log.info("Method "+name+" execution started at:"+new Date());
try {
return invocation.proceed();
}
finally {
long end = System.currentTimeMillis();
long time = end - start;
log.info("Method "+name+" execution lasted:"+time+" ms");
log.info("Method "+name+" execution ended at:"+new Date());
if (time > 10){
log.warn("Method execution longer than 10 ms!");
}
}
}
}
@@ -0,0 +1,16 @@
package org.baeldung.performancemonitor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class PerfomanceApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AopConfiguration.class);
Person person = (Person) context.getBean("person");
PersonService personService = (PersonService) context.getBean("personService");
System.out.println("Name is:"+personService.getFullName(person));
System.out.println("Age is:"+personService.getAge(person));
}
}
@@ -0,0 +1,42 @@
package org.baeldung.performancemonitor;
import java.time.LocalDate;
public class Person {
private String lastName;
private String firstName;
private LocalDate dateOfBirth;
public Person() {
}
public Person(String firstName, String lastName, LocalDate dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
@@ -0,0 +1,17 @@
package org.baeldung.performancemonitor;
import java.time.LocalDate;
import java.time.Period;
public class PersonService {
public String getFullName(Person person){
return person.getLastName()+" "+person.getFirstName();
}
public int getAge(Person person){
Period p = Period.between(person.getDateOfBirth(), LocalDate.now());
return p.getYears();
}
}
@@ -0,0 +1,8 @@
<aspectj>
<aspects>
<aspect name="org.baeldung.aspectj.SecuredMethodAspect"/>
<weaver options="-verbose -showWeaveInfo">
<include within="com.baeldung.aspectj.*"/>
</weaver>
</aspects>
</aspectj>
+23
View File
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<logger name="org.baeldung.performancemonitor.MyPerformanceMonitorInterceptor" level="INFO" />
<logger name="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" level="TRACE" />
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</configuration>
@@ -0,0 +1,54 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<bean id="sampleAdder"
class="org.baeldung.logger.SampleAdder" />
<bean id="doBeforeAspect" class="org.baeldung.logger.AdderBeforeAspect" />
<bean id="doAfterAspect" class="org.baeldung.logger.AdderAfterAspect" />
<bean id="doAfterThrowingAspect" class="org.baeldung.logger.AdderAfterThrowAspect" />
<bean id="doAfterReturningAspect" class="org.baeldung.logger.AdderAfterReturnAspect" />
<bean id="doAroundAspect" class="org.baeldung.logger.AdderAroundAspect" />
<aop:config>
<aop:aspect id="aspects" ref="doBeforeAspect">
<aop:pointcut id="pointCutBefore"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:before method="beforeAdvice" pointcut-ref="pointCutBefore" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterAspect">
<aop:pointcut id="pointCutAfter"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after method="afterAdvice" pointcut-ref="pointCutAfter" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterReturningAspect">
<aop:pointcut id="pointCutAfterReturning"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after-returning method="afterReturn"
returning="returnValue" pointcut-ref="pointCutAfterReturning" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterThrowingAspect">
<aop:pointcut id="pointCutAfterThrowing"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after-throwing method="afterThrow"
throwing="error" pointcut-ref="pointCutAfterThrowing" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAroundAspect">
<aop:pointcut id="pointCutAround"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:around method="aroundAdvice" pointcut-ref="pointCutAround" />
</aop:aspect>
</aop:config>
</beans>
@@ -0,0 +1,21 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CustomAnnotationIntegrationTest {
@Autowired
private Service service;
@Test
public void shouldApplyCustomAnnotation() throws InterruptedException {
service.serve();
}
}
@@ -0,0 +1,15 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,15 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}
@@ -0,0 +1,26 @@
package org.baeldung.aspectj;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class AccountUnitTest {
private Account account;
@Before
public void before() {
account = new Account();
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw5_thenSuccess() {
assertTrue(account.withdraw(5));
}
@Test
public void givenBalance20AndMinBalance10_whenWithdraw100_thenFail() {
assertFalse(account.withdraw(100));
}
}
@@ -0,0 +1,12 @@
package org.baeldung.aspectj;
import org.junit.Test;
public class SecuredMethodUnitTest {
@Test
public void testMethod() throws Exception {
SecuredMethod service = new SecuredMethod();
service.unlockedMethod();
service.lockedMethod();
}
}
@@ -0,0 +1,29 @@
package org.baeldung.logger;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {"classpath:springAop-applicationContext.xml"})
public class CalculatorIntegrationTest {
@Autowired
private SampleAdder sampleAdder;
@Test
public void whenAddValidValues_returnsSucessfully() {
final int addedValue = sampleAdder.add(12, 12);
assertEquals(24, addedValue);
}
@Test (expected = IllegalArgumentException.class)
public void whenAddInValidValues_throwsException() {
sampleAdder.add(12, -12);
}
}
@@ -0,0 +1,54 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<bean id="sampleAdder"
class="org.baeldung.logger.SampleAdder" />
<bean id="doBeforeAspect" class="org.baeldung.logger.AdderBeforeAspect" />
<bean id="doAfterAspect" class="org.baeldung.logger.AdderAfterAspect" />
<bean id="doAfterThrowingAspect" class="org.baeldung.logger.AdderAfterThrowAspect" />
<bean id="doAfterReturningAspect" class="org.baeldung.logger.AdderAfterReturnAspect" />
<bean id="doAroundAspect" class="org.baeldung.logger.AdderAroundAspect" />
<aop:config>
<aop:aspect id="aspects" ref="doBeforeAspect">
<aop:pointcut id="pointCutBefore"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:before method="beforeAdvice" pointcut-ref="pointCutBefore" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterAspect">
<aop:pointcut id="pointCutAfter"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after method="afterAdvice" pointcut-ref="pointCutAfter" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterReturningAspect">
<aop:pointcut id="pointCutAfterReturning"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after-returning method="afterReturn"
returning="returnValue" pointcut-ref="pointCutAfterReturning" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAfterThrowingAspect">
<aop:pointcut id="pointCutAfterThrowing"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:after-throwing method="afterThrow"
throwing="exception" pointcut-ref="pointCutAfterThrowing" />
</aop:aspect>
<aop:aspect id="aspects" ref="doAroundAspect">
<aop:pointcut id="pointCutAround"
expression="execution(* org.baeldung.logger.SampleAdder+.*(..))" />
<aop:around method="aroundAdvice" pointcut-ref="pointCutAround" />
</aop:aspect>
</aop:config>
</beans>