I have been using the togglz since last few days.
I am trying to find out if there is annotation based approach available in togglez API.
I want to do it like below -
public class Application {
public static void main(String[] args) {
Application application = new Application();
boolean first=false;
first=application.validate1();
System.out.println(first);
}
#Togglz(feature = "FEATURE_01")
public boolean validate1() {
System.out.println("validate1");
return false;
}
}
Is there anything available in togglz.
I could not find it anywhere , if you have any idea about such annotation please help.
My requirement is to skip the method execution based on feature value passed into it
No, there is no such annotation in Togglz. You will need some framework that support interceptors for that (like Spring, CDI, EJB). Then you can implement such an interceptor yourself.
However, to be honest I'm not sure if such an annotation would make sense. What should be the result if the feature is off? What does the method return? null? Explicit feature checks using a simple if statement are more straight forward to use in theses cases. But that's just my opinion. ;-)
Related
I am developing a Spring Boot application. And I have some permission checks in that program that is checked within controller methods. For an example there are some checking methods to check if there is any duplicate records, if that logged in user a member and so on. So what I was thinking is I need to move onto #PreAuthorize. So how can I create custom methods to do those duplicate validations and member validations and used them via #PreAuthorize. I know those duplicate checked can be done in anywhere else but I personally need to use #PreAuthorize. So anybody can help me? I really appreciate that.
You can do this using custom expression with #PreAuthorise
#PreAuthorize("isDuplicate(#id)")
#GetMapping("/organizations/{id}")
#ResponseBody
public Organization findOrgById(#PathVariable long id) {
return organizationRepository.findOne(id);
}
public boolean isDuplicate(Long OrganizationId) {
// add your logic here to check duplicates or any validation
}
refer https://www.baeldung.com/spring-security-create-new-custom-security-expression for more info
If I wanted to keep a certain Java package free of 3rd party dependencies with ArchUnit, how would I do it?
More specifically I am looking at keeping my domain model in a hexagonal architecture free from spring code. I specified some rules which I believe ought to prevent the model from using spring. However, I am able to use spring annotations like #Component and #Bean without causing a violation.
What I tried so far is
layeredArchitecture().
layer("domain").definedBy(DOMAIN_LAYER).
layer("application").definedBy(APPLICATION_LAYER).
layer("primary-adapters").definedBy(PRIMARY_ADAPTERS).
layer("secondary-adapters").definedBy(SECONDARY_ADAPTERS).
layer("spring").definedBy("org.springframework..")
whereLayer("spring").mayOnlyBeAccessedByLayers("primary-adapters", "secondary-adapters", "application").
because("Domain should be kept spring-free").
check(CLASSES);
As well as
noClasses().that().resideInAPackage(DOMAIN_LAYER).
should().dependOnClassesThat().resideInAPackage("org.springframework..").
check(CLASSES);
noClasses().that().resideInAPackage(DOMAIN_LAYER).
should().accessClassesThat().resideInAPackage("org.springframework..").
check(CLASSES);
Here a code example which executes the tests just fine, although com.example.app.domain.Factory is importing org.springframework....
You can use DescribedPredicate:
void domainSpring() {
DescribedPredicate<JavaAnnotation> springAnnotationPredicate = new DescribedPredicate<JavaAnnotation>("Spring filter") {
#Override
public boolean apply(JavaAnnotation input) {
return input.getType().getPackageName().startsWith("org.springframework");
}
};
classes().that().resideInAPackage(DOMAIN_LAYER).should()
.notBeAnnotatedWith(springAnnotationPredicate).check(CLASSES);
}
You can also go with name matching.
So you don't have to write a custom DescribedPredicate.
ApplicationCoreMustNotDependOnFrameworks = noClasses()
.that().resideInAnyPackage(DOMAIN_LAYER)
.should().dependOnClassesThat().haveNameMatching("org.springframework.")
.orShould().dependOnClassesThat().haveNameMatching("javax.persistence.*")
.because("Domain should be free from Frameworks");
in my case, I wanted an exception to that rule.
I.e., instead of excluding completely Spring, I wanted to accept the classes in the event package (EventHanlder)
so you can replace "org.springframework" with "org.springframework(?!.*event).*" which is a regular expression
I have tried unsuccessfully to implement circuit breaker pattern, here, in Java using Spring framework.
How can you implement circuit breaker pattern by Java and Spring?
For a simple, straightforward circuit breaker implementation, check out Failsafe (which I authored). Ex:
CircuitBreaker breaker = new CircuitBreaker()
.withFailureThreshold(5)
.withSuccessThreshold(3)
.withDelay(1, TimeUnit.MINUTES);
Failsafe.with(breaker).run(() -> connect());
Doesn't get much simpler.
Apache commons has some implementations for several types of lightweight circuit breakers, here's a link to the docs
The project provides the EventCountCircuitBreaker and ThresholdCircuitBreaker classes, and an abstract AbstractCircuitBreaker so you could implement your own.
The code is open sources and is hosted at github, so anyone attempting to implement the pattern should at least take a peek.
Spring cloud provides some interesting integration with Hystrix. You should probably have a look into it...
Regarding the pattern itself
You can obtain a lot of useful information about this pattern at Martin Fowler's blog. It contains ruby implementation as well as references for implementation in other languages.
Regarding the java spring implementation
Please check the JRugged library.
It contains the Circuit Breaker implementation in spring as well as other design patterns.
You don't actually need to be using Spring cloud or Spring boot to use Hystrix.
Using hystrix-javanica makes it easy to use Hystrix with plain old Spring too.
Here is an example of fallback methods (both methods, getMessageTimeout and getMessageException, fail by default):
#Configuration
#ComponentScan
#EnableAspectJAutoProxy
public class CircuitBreakingWithHystrix {
#Bean
public HystrixCommandAspect hystrixAspect() {
return new HystrixCommandAspect();
}
public static void main(String[] args) throws Throwable {
ApplicationContext ctx
= new AnnotationConfigApplicationContext(CircuitBreakingWithHystrix.class);
ExampleService ex = ctx.getBean(ExampleService.class);
for (int i = 0; i < 1000; i++) {
System.out.println(ex.getMessageException());
System.out.println(ex.getMessageTimeout());
}
}
#Service
class ExampleService {
/*
* The default Hystrix timeout is 1 second. So the default
* version of this method will always fail.
* Adding the #HystrixProperty will cause
* the method to succeed.
*/
#HystrixCommand(
commandProperties = {
//#HystrixProperty(name = EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS,
// value = "5000")
},
fallbackMethod = "messageFallback"
)
public String getMessageTimeout() {
try {
//Pause for 4 seconds
Thread.sleep(4000);
} catch (InterruptedException ex) {
// Do something clever with this
}
return "result";
}
#HystrixCommand(
fallbackMethod = "messageFallback")
public String getMessageException() {
throw new RuntimeException("Bad things happened");
}
private String messageFallback(Throwable hre) {
return "fallback";
}
}
You can also examine the throwable sent to the fallback method to identify why the method call failed.
You can have a look at JCircuitBreaker . The implementation there implements circuit breaker like approach.
Please note that this is not 1:1 implementation of the pattern because it does not define fixed states like "half-open". Instead it makes the decision (if the breaker should be open or closed) basing on current application state (using so called "break strategy"). Nevertheless it should be possible to define such a "break strategy" which evaluates failures thresholds - so it should be possible to also implement original pattern using JCircuitBreaker.
resilience4j is also a implementation of circuit breaker for java.
you can use 'circuit breaker', 'retry'.
guide: https://resilience4j.readme.io/docs/circuitbreaker
I'm trying to use AOP with picocontainer.
so far I found in the documentation:
http://picocontainer.codehaus.org/interception.html
pico = new DefaultPicoContainer();
pico.as(INTERCEPT).addComponent(Apple.class, BraeburnApple.class);
and then create the interceptor, but looking through the code, I cannot find the INTERCEPT property anywhere.
as receives a Properties value, which pico implements in Characteristics class.
anyone has a clue, or has implemented it before and knows how to keep with it?
Thanks
looks like the property for this Behavior is somehow missing in this pico version, check org.picocontainer.Characteristics in older versions, I really hope it was implemented somewhere :)
Also there's old styled way for interception in pico: http://www.markhneedham.com/blog/2008/11/11/logging-with-pico-container/
Since the 2.14.3 org.picocontainer.behaviors still have these classes, I suppose this way is ok
This worked for me. First, create a proxy by extending a bean:
public static class ChangeMapInfoEndpointInterceptor extends MapInfoRoutingManagementBean {
#Override
public void setEndpoint(String endpoint) {
System.out.println("setEndpoint called");
}
}
Then pass it to the intercepting-styled container:
MutablePicoContainer context = new PicoBuilder().withBehaviors(new Intercepting()).build();
context.addComponent(MapInfoRoutingManagement.class, MapInfoRoutingManagementBean.class);
Intercepted intercepted = context.getComponentAdapter(MapInfoRoutingManagement.class).findAdapterOfType(Intercepted.class);
intercepted.addPostInvocation(MapInfoRoutingManagement.class, new ChangeMapInfoEndpointInterceptor());
I have a RESTful web service. For implementation using JAX-RS (Jersey).
Have the following method:
public void foo (#PathParam ("name") String uuid) {
...
}
I need to do validation of input parameters. And if data invalid throw WebApplicationException.
I added my custom annotation CheckUuid (extends ):
public void foo (#PathParam ("name") #CheckUuid String uuid) {
...
}
Is it possible to do validation using annotations on a stage when the method chosen, but not yet called? For example using PreProcessInterceptor?
Java EE6 has some built in validation functionality.
http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html
I have not used it however, but I saw it brought up during Java One and it looks pretty cool.
I'm not sure at what point this would happen, but I think it might work out for you.
As a result, it was decided to use the standard pattern in the method validation. Because in Jersey do not have PreProcessInterceptor.