How to know which methods are invoked in java? - java

Is there any way to know which methods are getting invoked in Java during run time. Actually I am trying to detect those methods which are getting invoked and according to those methods that are invoked use Java Reflection APIS to invoke another method from another classes. In this way I want to divert the execution to my methods first and then call those running methods.
e.g
//Method Invoked_Method = "get the invoked method here "
if(Invoked_Method.equals("somemethodName"){
//invoke Another method ..
}
Although its a security breach, but I am working in team for security products. So have to experiment this.

You may want to consider AOP: http://aopalliance.sourceforge.net/
This allows you to intercept method calls that match a particular expression and enhance or change the default behaviour of the method.
If you're already using them, the Spring and Guice frameworks provide ways to leverage AOP relatively easily.

I suppose what you are saying is you need to trace the callstack at runtime. I found a thread regarding this.
Check this out

Related

understanding how custom metrics publisher work on hystrix

I am struggling a little bit to understand how to implement a Hystrix Metrics Publisher plugin.
Having read the documentation, it is still not clear how things are supposed to work together.
My goal is to write a plugin that will collect every metrics published by hystrix and write these metrics to a file on disk.
This file will later be collected and processed by an external tool giving us a good historical basis of the circuit’s behavior and problems.
The system where hystrix is running is a normal spring application. This said, I am also somewhat new on the java platform (although I am comfortable with the java language).
I thought that a first step towards understanding how the plugin could be implemented would be looking at the already implemented publishers. With this in mind, I looked at some of the implementations of hystrix-contrib directory.
I have chosen hystrix-codahale-metrics-publisher and hystrix-servo-metrics-publisher.
Both of them have a main class (servo is HystrixServoMetricsPublisher) which seems to register for receiving all possible kinds of metrics and some classes to deal with each kind of metric.
By looking at what I will call the main class, I see that, for example, there is a method called getMetricsPublisherForCommand that must return an implementation of the interface HystrixMetricsPublisherCommand.
Now questions start:
Question 1 I am assuming that once a plugin is registered every execution of every command on the context where the plugin is registered, and by the word command we can understand every execution of the execute() method of every class which inherits from HistrixCommand on that context, will generate a call to the getMetricsPublisherForCommand() method of my plugin. Is it true?
If so, there are a lot of low level implementations in hystrix such as thread pools and other, Should my getMetricsPublisherForCommand() implementation be thread-safe or I am guaranteed to receive calls in a sequential order? On what thread will my getMetricsPublisherForCommand() be executed?
Question 2 By looking at the documentation I am still not sure about what exactly the implementation of HystrixMetricsPublisherCommand to be returned by getMetricsPublisherForCommand() has to do. This is due to the fact that the HystrixMetricsPublisherCommand interface only specifies a method called initialize (). if it specified a method called, say, publish() I would conclude that the hystrix engine would call my custom getMetricsPublisherForCommand() method to get a metrics publisher on which it would call a publish() method to perform the custom publishing. But the initialize () method seens to be called only once when this given object is returned and I have found no other method the engine would call afterwards.
Also, by reading the documentation, I am under the impression that the implementation of HystrixMetricsPublisherCommand returned by getMetricsPublisherForCommand() will be somehow a singleton which completely breaks my understanding about how the thing is supposed to work.
The documentation say this:
The initialize() method will be called once-and-only-once to indicate when this instance can register with external services, start publishing metrics etc.
If you look at the servopublisher however you will notice that, unless I am completely and absolutely confused, the publishing stuff is performed right from the constructor. Now, if initialize() will be called to make some setup, how can I code my logic from the constructor where, unless the object is a singleton, it will be executed before any method including initialize () will have a chance to be called? In the other hand ,,, if this is a singleton, how can it run its constructor for every hystrix command?
May be I have missed something, I don't know ... but I need to understand conceptually what is going on here in order to implement my logic the right way. Thanks for your patience and I hope I have made myself clear enough in this long question.
First, recommend staying within the one (concise) question format.
Second, recommend using an existing implementation such as the default CodaHale (formerly DropWizard) implementation (which publishes to Graphite repository for Grafana consumption for example) to get it working.
HystrixPlugins.reset();
final WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
HystrixPlugins plugins = HystrixPlugins.getInstance();
plugins.registerCommandExecutionHook(...);
// Good idea to use properties to enable/disable metrics generally...
// Using Spring type example...
if (hystrixMetricsEnabled.get()) {
plugins.registerMetricsPublisher(new HystrixCodaHaleMetricsPublisher(
getRegistry(springContext, sce.getServletContext())));
...
Otherwise the Hystrix documentation and full source of classes involved are publicly available:
https://github.com/Netflix/Hystrix/wiki/Plugins#metricspublisher

CDI Interceptors: How to intercept `this` calls or get the current proxy object?

I have a class that users will inherit from and implement two methods: navigateForwards() and navigateBackwards() (it's a wizard-like web application).
The user may want to add interceptors to these methods.
Another class (let's say it's part of a framework) will find the appropriate subclass, select() it and call the navigate(String) method which will call either navigateForwards() or navigateBackwards(). At that point interceptors won't work anymore since it's an unproxied method call. I could add interceptors to the navigate() method, but that's not the method subclasses are interested in overriding.
Is there an easy way to tell CDI to intercept a method that otherwise wouldn't be intercepted?
I came up with a couple of general approaches to solve this but none of them seems very promising:
Somehow get the proxy object that called me. That would require some sort of self-injection that replicates the select() call made in the "framework" class.
Get the list of interceptors for the method from CDI and call them manually. Somehow.
Use DeltaSpike's EnableInterceptorsProxyFactory http://deltaspike.apache.org/documentation/proxy.html to wrap this. That could be slow and/or uncover other limitations.
There may be another option with CDI extensions, but I'm not sure what an extension is capable of.
I've already tried turning everything upside-down and using decorators instead of a base class in the hopes that a call to the delegate object would get intercepted but it didn't, at least not in JBoss EAP 6.x (most likely 6.4, but it could be an earlier version when I tested).
The simplest solution I found (which for some obscure reason hadn't occurred to me before) is making navigate() static and passing the object explicitly (e.g. as self).
Looking from the outside the class gets a bit weird since it looks like it could have a regular non-static method but has a static one. OTOH it does the job and is easy to understand. I needed the current proxy object so I passed it in. It's trivial and it keeps interceptor behavior.
There are just a few calls that have to be changed in my project, but other projects will have different needs so it isn't a general solution unfortunately. That's why I am not accepting my own answer.

When do we use denyAll in spring security

I am a bit confused as to why someone would use #PreAuthorize("denyAll") for a method. As per the spring security documentation, it always evaluates to false.
If we are not going to allow access to a particular method, what is the point of keeping such a method. Why not comment it out? Or is it that it can still be accessed from within the same class?
I am trying to understand under what scenario such a requirement would arise.
One small clarification that I found in general for deny all was
#DenyAll annotation can be used to restrict business interface access from anyone, logged in or not. The method is still invokable from within the bean class itself.
So the jist is it can be used for a method which is public for some reason or have been exposed (perhaps it implements an interface) but should never be called directly from outside. However they can be called from inside(within the class).
here is the link
One real example that I can give you is (which is quite related with my work). We have 2 business unit with same code base. Now in one unit there is a feature where some mobile reseller can directly call a service which cancels the voucher directly to the operator end but in the other unit we needed to block this due to some business rule. Since we use the same interface in both system so in one system we blocked its usage using denyall
Hope this gives you a clear idea.
I decorate my service classes in this way which requires the individual inner service methods to override the denying class level PreAuth annotation. This ensures that each method in the class will be appropriately secured w/a fallback to denyAll.
I know this is old but I stumbled on it looking for the syntax for #PreAuthorize('denyAll') and thought I'd throw my 2cents in.

User can only call methods if the object belongs the user

In a CRUD jsf application, owners have objects, like records.
I want that owners can only view/edit/delete objects created by themselves. One way to achieve this, in every method to check if object has been created by the logged user.
There can be many similar methods and objects, so I would like to use another elegant/automatic way instead of using
if (selectedObject.owner == loggedUser)
phrases in every methods.
Is it possible,if possible how?
You could use aspect oriented programming for access protection.
I'd write an aspect to intercept all method calls to the access restricted methods, apply the check in a before advice and throw an exception if it fails. Depending on the structure of the program either by looking for an explicit annotation or by using a rather generic pointcut.
This would move your if (obj.owner.equals(loggedUser)) to one central place, but of course you'd still need to take care not to include other users' items in lists etc.
"The" Java aspect implementation is AspectJ. It is also used and supported by the Spring framework, which you may already use anyway: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html
If I were you I would show the component only if the user is authorized, by using
rendered={user.isOwner}
You will use this as an attribute in your component.

What is the difference between mocks and stubs ( JMock)

What is the difference between mocks and stubs in jMock? I can create both with jMock? how i can create stubs with it and what the situation is most appropriate for this, I believe that using stubs is when I need to prepare some state for test.
Thanks
Wikipedia has an article regarding Mock objects, but the terminology is not explained as good as could be. We used to make this distinction (which may be subject to discussion, of course):
Mocks and stubs both simulate an object which is required for testing a component.
The word "mock" is used when you want to assert that a specific kind of interaction between the tested component and the mocked object takes place. That's why mock frameworks (like EasyMock) provide methods to assert that all expected calls have actually been performed. E. g. you want to see that your service actually calls a (mocked) DAO. So this call is part of your test conditions / assertions.
The word "stub" however is used when you are simply trying to provide an implementation which helps testing your component. What kind of interaction takes place does not matter, you just want the stub to fill in the gaps so you can test your component. Your focus lies on the tested components and what it does.
So it's just two words for the same thing, depending on what you are trying to achieve with it.
Mocha is a traditional mocking library very much in the JMock mould. Stubba is a separate part of Mocha that allows mocking and stubbing of methods on real (non-mock) classes. It works by moving the method of interest to one side, adding a new stubbed version of the method which delegates to a traditional mock object. You can use this mock object to set up stubbed return values or set up expectations of methods to be called. After the test completes the stubbed version of the method is removed and replaced by the original.
for more detail with example
http://jamesmead.org/blog/2006-09-11-the-difference-between-mocks-and-stubs
We usually make a distinction between queries and actions. Queries don't change the state of the world outside the mocked object--we can call it once or 5 times. They're like pre-conditions if you've done Design by Contract.
Actions change the outside world (e.g. subtract a value), and we specify mocks for those. It matters how many times we call a mock because the results will be different. These are like post-conditions.
Stub Queries, Mock Actions.

Categories