Proxy Design Pattern : Disadvantages - java

I was going through one of the Articles on Proxy pattern.
Read the Comments After the Explanation
In this article there are few downsides mentioned for Proxy Patterns, but I am not able to understand:
1) The downside here is 'magic' could be happening that an extender is unaware of (a 'black-box' problem). Please explain the magic.
2) A proxy can mask the life-cycle and state of a volatile resource from its client. A client may call the proxy not realizing that the resource is currently unavailable... in this case the proxy has to either block until a resource is available again, or it must produce some kind of error. In Java terms it would have to be an unchecked exception, since the Proxy must comply with the interface of the original object. Also the client may not be aware that the resource it is calling now is not the same resource it called a second ago; if there is any state on the resource then the client may be confused that the state appears to have been forgotten.
Please explain.
3) if a proxy is used to represent a remote resource in the local process, this can disguise the fact that remote communication is involved. As we know, remote invocation is completely different from local invocation, and our programs should not treat it as if it were the same. It is better if the proxy declares somehow that it is a proxy for a remote resource, rather than a local resource. Then clients would have be able to choose only local resources, or to modify their behavior when using a remote resource.
Would you please help me in understanding three point above related to the downsides of Proxy?

That makes 3 different questions. I'll answer the third one. You'd better edit your question to a single one, and ask each of the two others in a separate question.
When dealing with communication with a remote server, the proxy pattern is often used (by RMI, for example). You get a reference to an object from some factory, and what you get is in fact a stub (a proxy) which, for every method you call, serilaizes the arguments of the method, sends them to a server, waits for the response, and returns the result.
The proxy makes that almost transparent, but not being aware that all this happens behind the scenes can make you code things very inefficiently.
Take this example for example:
if (account.getBalance() > 0 && account.getBalance() < MAX) {
transferAmount(account.getBalance() / 2);
}
Now imagine that account is a proxy to a remote object. Each time getBalance() is called, a remote network call is made, which can potentially lead to an exception, or even return a different value each time, making this simple code snippet extremely inefficient.

Related

Java remote interface blocks the use of my GUI

I've given a bank application which I should modify so the balance of an account gets updated on every GUI screen. This should be done with RMI(Observable) in my example. I already made this work, at least, I'm almost certain about that.
There is a REMOTE interface called IBankingSession.
This REMOTE interface should have a method like setGUI(BankSessionController) or something like this. But, This isn't possible because the JavaFX parts aren't Serializable. The IBankingSession doesn't have any relationship to a GUI.
How can I link an instance of IBankingSession to this GUI? So I can update the GUI from this instance? It also feels weird to make a method like setGUI in a REMOTE interface. Because the GUI is of course, on the same screen as where the session is created.
I'm curious for some good idea's. Thanks in advance.
IBankingSession session = desk.logIn(tfAccount.getText(), tfPassword.getText());
First of all: you don't want to link your "remote" thing directly to your local clients that make use of it. That IBankingSession has no business knowing anything about the fact that your client wants to use JavaFx to put something on the user screens.
Instead, try something like this: define an interface that allows for callbacks (in other words: some kind of "push" model):
A client registers with the remote server; telling it: "I am interested in balance updates".
Then, upon a "balance" update, the remote service pushes that information to each client.
Now each client will be notified; and can then decide what to do with incoming updates; for example update some JavaFx UI component; or maybe, to log them into some persistent storage - giving you one mechanism that might be useful for a huge variety of different use cases.
You shouldn't be using observables at all, and certainly not over a network.
As far as RMI goes, you should strenously avoid anything in the nature of a client-side callback. There are firewall problems, latency problems, connectivity problems, ... every kind of thing that could cause your client to misfire.
You need to completely rethink this. It is not a viable design.

How to determine whether an EJB call is from a remote or local client

I have an interesting problem.
We have a number of EJB's that are called both by local code (via local interface) and by client code (via remote interface).
The code runs on Weblogic 12c servers and use RMI for method invocations.
The system is in development already for many years, and along others implements browser functionality around user defined cursors (a kind of handle for a result set). There are already many calls to obtain such a cursor for various data types.
When the cursor is obtained it is used subsequently to request the underlying data (another call).
In our case we want to know whether the call is done from local code or from a remote client. We want to know this so we can preload the first n items, and thus reduce the number of calls to our server. Each call has an overhead of about 20ms, which we want to avoid.
The remote client code is generic (the cursor is wrapped in a kind of list) and could easily be adjusted to handle the preloaded data.
The local callers also call these EJB methods to obtain a cursor, but usually use other functionality to handle the cursor (wrapping in iterators, joins, etc). So they would become a lot more complex if they had to handle the preloading (and they often do not need it).
So we want to make an interceptor to do preloading of data in the cursor, but only if the call is made from a remote client. So far we could not find a way of doing so.
I tried RemoteServer.getClientHost() but it always throws the exception there is no connection.
I searched if the SessionContext could be extended with a field/value to be set by the caller to identify the remote client, but could find anything about doing this. (We have a homemade wrapper for the service interface which could be extended of inserting such information in a context).
So the question is:
Is there a generic way to find out in an EJB interceptor that the origin of the call was from a different system
If the remote client uses any kind of authentication there should be some info in the security context about the principal which can be used to differentiate. Otherwise, before finding a better solution new Throwable().getStackTrace() returns an array of all callers. There must be a method upstream that could tell if the call is local or it's been done via remote call.

Global Resource Object in Spring

I'm just getting into Spring (and Java), and despite quite a bit of research, I can't seem to even express the terminology for what I'm trying to do. I'll just explain the task, and hopefully someone can point me to the right Spring terms.
I'm writing a Spring-WS application that will act as middleware between two APIs. It receives a SOAP request, does some business logic, calls out to an external XML API, and returns a SOAP response. The external API is weird, though. I have to perform "service discovery" (make some API calls to determine the valid endpoints -- a parameter in the XML request) under a variety of situations (more than X hours since last request, more than Y requests since last discovery, etc.).
My thought was that I could have a class/bean/whatever (not sure of best terminology) that could handle all this service discovery stuff in the background. Then, the request handlers can query this "thing" to get a valid endpoint without needing to perform their own discovery and slow down request processing. (Service discovery only needs to be re-performed rarely, so it would be impactful to do it for every request.)
I thought I had found the answer with singleton beans, but every resource says those shouldn't have state and concurrency will be a problem -- both of which kill the idea.
How can I create an instance of "something" that can:
1) Wake up at a defined interval and run a method (i.e. to check if Service discovery needs to be performed after X hours and if so do it).
2) Provide something like a getter method that can return some strings.
3) Provide a way in #2 to execute a method in the background without delaying return (basically detect that an instance property exceeds a value and execute -- or I suppose, issue a request to execute -- an instance method).
I have experience with multi-threaded programming, and I have no problem using threads and mutexes. I'm just not sure that's the proper way to go in Spring.
Singletons ideally shouldn't have state because of multithreading issues. However, it sounds like what you're describing is essentially a periodic query that returns an object describing the results of the discovery mechanism, and you're implementing a cache. Here's what I'd suggest:
Create an immutable (value) object MyEndpointDiscoveryResults to hold the discovery results (e.g., endpoint address(es) or whatever other information is relevant to the SOAP consumers).
Create a singleton Spring bean MyEndpointDiscoveryService.
On the discovery service, save an AtomicReference<MyEndpointDiscoveryResults> (or even just a plain volatile variable). This will ensure that all threads see updated results, while limiting them to a single, atomically updated field containing an immutable object limits the scope of the concurrency interactions.
Use #Scheduled or another mechanism to run the appropriate discovery protocol. When there's an update, construct the entire result object, then save it into the updated field.

Can I load a Java class in a way that automatically removes its privileges?

I am working on developing a library that needs to instantiate and return untrusted objects downloaded from an external website. At a high-level, the library works as follows:
Clients of the library requests a class from a remote source.
My library instantiates that object, then returns it to the user.
This is a major security risk, since the untrusted code can do just about anything. To address this, my library has the following design:
I enable the SecurityManager and, when instantiating the untrusted object, I use an AccessController to handle the instantiation in a context where there are no privileges.
Before returning the object back to the client, I wrap the object in a decorator that uses an AccessController to forward all method requests to the underlying object in a way that ensures that the untrusted code is never run with any permissions.
It occurs to me, though, that this might not be the most elegant solution. Fundamentally, I want to strip away all permissions from any object of any type downloaded from the remote source. My current use of AccessController is simply a way of faking this up by intercepting all requests and dropping privileges before executing them. The AccessController approach also has its own issues:
If the wrapped object has any methods that return objects, those returned objects have to themselves be wrapped.
The wrapper code will potentially be thousands of lines long, since every exported method has to be secured.
All of the methods exported by the downloaded object have to be known in advance in order to be wrapped.
My question is this: is there a way to load classes into the JVM (probably using a custom ClassLoader) such that any instances of those classes execute their methods with no permissions?
Thanks!
You will want to call defineClass with an untrusted ProtectionDomain.
Your current solution has a number of problems. It doesn't appear to cover the static initialiser. It may be possible to install code into some mutable arguments. Methods that use the immediate caller will still be privileged (AccessController.doPrivileged, say). But most of all, it falls about when rubbing up against any kind of global - for instance running a finaliser.
Don't know if there's a way to directly do what you asked, but I think your approach can be simplified by using interfaces and dynamic proxies. Basically, if you have an interface for the object to be returned, and all its methods return either simple types or interfaces, then you can wrap all the methods and their return values automatically, without knowing the methods in advance. Just implement an InvocationHandler that does the AccessController magic in its invoke method, and create proxies using Proxy.newProxyInstance(...).

web service client reference, in a servlet

I have a servlet, and that servlet uses a .net web service to perform some function. To do this, I created the webservice client in Netbeans using the "jax-rpc" style client.
Let's say that my service name is "Tester". Then two of the generated classes are called "Tester", and "TesterSoap".
To get a reference to the web service, I need to do this:
Tester t = new Tester_Impl();
TesterSoap tsoap = t.getTesterSoap();
To use the webservice, I can then do this:
tsoap.runTest();
My question is, since this is a servlet which gets executed many times, should I store the first two lines in static variables (so they only ever get executed once), or store them locally so that they execute everytime the servlet is executed?
Another way of asking the same question: is there a performance hit everytime the first two lines are called? (I'm testing everything locally so it's hard to measure).
Thanks...
If the default constructor and any of the initialization blocks of the Tester_Impl() class and the method getTesterSoap() doesn't do anything expensive (e.g. reading file from disk, loading data from DB, connecting a socket, etc, I however suppose it doesn't) then you don't need to worry about it.
You can consider declaring them as an instance variable of the class extending from HttpServlet. But, a big but, it is going to be shared among all HTTP requests, because there will be only one instance of the particular servlet class during whole application's lifetime. So if the Tester_Impl class is supposed to have a state, then it is a very bad idea to declare it as an instance variable. It would then be shared among all requests. With other words, it's not threadsafe. If you want to ensure threadsafety in servlets, then declare everything in the very same method block.
I would not optimize prematurely here. Test this out in as close to a production environment as you can (i. e. not on your local box) and see what the performance hit is. What I've done in the past is write a small shell script that hits my server with wget n times with a delay of k milliseconds and then measured the latency, possibly instrumenting the code with some timing or profiling myself (or with jvisualvm or some other profiling tool).
If you want to protect your design from a possible performance hit without doing the testing, you could use a factory to provide instances of the service client and then you could swap out singleton service clients for many of them whenever you feel like it.

Categories

Resources