Proxy pattern concrete class hiding implementation details - java

I have been reading about java proxy pattern and invocation handler and everywhere it is seen that the concrete class construction is available to the client.
For example,
//TwitterService service = (TwitterService) SecurityProxy.newInstance(new TwitterStub());
TwitterService service = new TwitterStub();
System.out.println(service.getTimelinePosts("abc"));
User can create an instance of TwitterStub directly and access the methods. I was wondering if there was a way of not exposing the or avoiding the construction of the concrete class via the client ?
Is there a better way ?

As the GoF puts it, the intent of the proxy pattern is "to provide a surrogate or placeholder for another object to control access to it".
So, in your specific case what happens is that you're creating a particular proxy instance directly. And that's fine as long as you (as a client) know that you want a particular type of proxy object.
If what you want is a level of indirection, you can use an Abstract Factory Pattern that return different types of proxy objects. But so far, the reason of proxy objects is to act on behalf of other objects.
As a side note, proxies are useful when you have objects that are expensive to create, but you don't want to necessarily cripple main application function due to such expense. For example, suppose you have a document with 1000 images. You can use proxies for them, and only load them when stricly needed (i.e. when they are in visible view), and you can still load the full document really fast without the overhead of reading 1000 images at once.

Related

A very specific usage of callbacks in Java

This question is about a specific usage of a callback pattern. By callback i mean an interface from which i can define method(s) that is (are) optionnaly (= with a default set to 'do nothing', thanks Java 8) called from a lower layer in my application. My "application" is in fact a product which may have a lot of changes between client projects, so i need to separates somethings in order to reuse what won't change (technical code, integration of technologies) from the rest (model, rules).
Let's take an example :
I developped a Search Service which is based upon Apache CXF JAX-RS Search.
This service parses a FIQL query which can only handle AND/OR condition with =/</&gt/LIKE/... condition to create a JPA criteria query. I can't use a a condition like 'isNull'.
Using a specific interface i can define a callback that will be called when i got the criteria query from apache CXF layer in my search service and add my condition to the existing ones before the query is executed. This condition are defined on the upper layer of my searchService (RestController). This is in order to reduce code duplicate, like retuning a criteria query and finalize it in every methods where i need it. And because using #Transactional in CXF JAX-RS controller does not work well Spring proxy and CXF work (some JAX-RS annotation are ignored);
First question : does this example seems to be a good idea in terms of design ?
Now another example : i have an object which have some basic fields created from a service layer. But i want to be able to set others non-nullable fields not related to the service's process before the entity is persisted. These fields may move from a projects to another so i'd like to not have to change the signature of my service's method every time we add / remove columns. So again i'm considering using a callback pattern to be able to set within the same transaction and before object is persisted by the Service layer.
Second question : What about this example ?
Global question : Except the classic usage of callback for events : is this a pratice to use this pattern for some specific usage or is there any better way to handle it ?
If you need some code sample ask me, i'll make some (can't post my current code).
I wouldn't say that what you've described is a very specific usage of "an interface from which i can define method(s) that is (are) optionally called from a lower layer". I think that it is reasonable and also quite common solution.
Your doubts may be due to the naming. I'd rather use the term command pattern here. It seems to me that it is less confusing. Your approach also resembles the strategy pattern i.e. you provide (inject) an object which performs some calculations. Depending, on the context you inject objects that behave in a different way (for example add different conditions to a query).
To sum up callbacks/commands are not only used for events. I'd even say that events are specific usage of them. Command/callback pattern is used whenever we need to encapsulate an operation within an object and transfer/pass it somehow (by the way, in Java there is no other way to do so but for example in C++ there are pointers to methods, in C# there are delegates...).
As to your second example. I'm not sure if I understand it correctly. Why can't you simply populate all required fields of an object before calling the service?

How to prevent client from seeing internal private classes in Android library ?

I have a library with several packages-
lets say
package a;
package b;
inside package a I have public a_class
inside package b I have public b_class
a_class uses b_class.
I need to generate a library from this , but I do not want the Client to see b_class.
The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class.
Is there another way to do so ? maybe using interfaces or some form of design pattern ??
If you reject to move the code to an individual, controlled server, all you can do is to hinder the client programmer when trying to use your APIs. Let's begin applying good practices to your design:
Let your packages organized as they are now.
For every class you want to "hide":
Make it non-public.
Extract its public API to a new, public interface:
public interface MyInterface {...}
Create a public factory class to get an object of that interface type.
public class MyFactory
{
public MyInterface createObject();
}
So far, you have now your packages loosely coupled, and the implementation classes are now private (as good practices preach, and you already said). Still, they are yet available through the interfaces and factories.
So, how can you avoid that "stranger" clients execute your private APIs? What comes next is a creative, a little complicated, yet valid solution, based on hindering the client programmers:
Modify your factory classes: Add to every factory method a new parameter:
public class MyFactory
{
public MyInterface createObject(Macguffin parameter);
}
So, what is Macguffin? It is a new interface you must define in your application, with at least one method:
public interface Macguffin
{
public String dummyMethod();
}
But do not provide any usable implementation of this interface. In every place of your code you need to provide a Macguffin object, create it through an anonymous class:
MyFactory.getObject(new Macguffin(){
public String dummyMethod(){
return "x";
}
});
Or, even more advanced, through a dynamic proxy object, so no ".class" file of this implementation would be found even if the client programmer dares to decompile the code.
What do you get from this? Basically is to dissuade the programmer from using a factory which requires an unknown, undocumented, ununderstandable object. The factory classes should just care not to receive a null object, and to invoke the dummy method and check the return value it is not null either (or, if you want a higher security level, add an undocumented secret-key-rule).
So this solution relies upon a subtle obfuscation of your API, to discourage the client programmer to use it directly. The more obscure the names of the Macguffin interface and its methods, the better.
I need to generate a library from this , but I do not want the Client to see b_class. The only solution I know of is to flatten my beautifully understandable packages to single package and to use default package access for b_class. Is there another way to do so ?
Yes, make b_class package-private (default access) and instantiate it via reflection for use in a_class.
Since you know the full class name, reflectively load the class:
Class<?> clz = Class.forName("b.b_class")
Find the constructor you want to invoke:
Constructor<?> con = clz.getDeclaredConstructor();
Allow yourself to invoke the constructor by making it accessible:
con.setAccessible(true);
Invoke the constructor to obtain your b_class instance:
Object o = con.newInstance();
Hurrah, now you have an instance of b_class. However, you can't call b_class's methods on an instance of Object, so you have two options:
Use reflection to invoke b_class's methods (not much fun, but easy enough and may be ok if you only have a few methods with few parameters).
Have b_class implement an interface that you don't mind the client seeing and cast your instance of b_class to that interface (reading between the lines I suspect you may already have such an interface?).
You'll definitely want to go with option 2 to minimise your pain unless it gets you back to square one again (polluting the namespace with types you don't want to expose the client to).
For full disclosure, two notes:
1) There is a (small) overhead to using reflection vs direct instantiation and invocation. If you cast to an interface you'll only pay the cost of reflection on the instantiation. In any case it likely isn't a problem unless you make hundreds of thousands of invocations in a tight loop.
2) There is nothing to stop a determined client from finding out the class name and doing the same thing, but if I understand your motivation correctly you just want expose a clean API, so this isn't really a worry.
When using Kotlin, you can use the internal modifier for your library classes.
If I understand correctly you are asking about publishing your library for 3rd party usage without disclosing part of your source? If that's the case you can use proguard, which can obfuscate your library. By default everything will be excluded/obfuscated, unless you specify things you want to exclude from being obfuscated/excluded.
If you want to distribute [part of] your code without the client being able to access it at all, that means that the client won't be able to execute it either. :-O
Thus, you just have one option: Put the sensible part of your code into a public server and distribute a proxy to access it, so that your code would be kept and executed into your server and the client would still be able to execute it through the proxy but without accessing it directly.
You might use a servlet, a webservice, a RMI object, or a simple TCP server, depending on the complexity level of your code.
This is the safest approach I can think of, but it also deserves a price to pay: In addition to complexing your system, it would introduce a network delay for each remote operation, which might be big deal depending on the performance requirements. Also, you should securize the server itself, to avoid hacker intrussions. This could be a good solution if you already have a server that you could take advantage of.

does java.util.ServiceLoader load only a single instance of a service

I want to ask whether the ServiceLoader.load() can help me create multiple instances of the loaded service?
I have been doing some testing and its seems it can only load one instance of the service at a time. If it is possible to have multiple instances, can someone explain how I can achieve this?
You don't want to use the ServiceLoader itself to create multiple copies. You could, using the reload method of the loader, but that is not the intended usage of it, probably doesn't perform very well, and also has the side effect that other implementations are reloaded as well.
More likely, what you want to do is instead of create a factory class (or some similar concept), which itself creates the instances of the class you actually want to use, in the end, and use the service loader to load such factory instances instead.

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(...).

Application design - Updating domain object

I would like to improve the design of some part of my application. It is a swing application in which the user interface is updated by data received from a server (TCP/UDP). At the moment i pass my domain object (POJO) to the constructor of the class the will connect with the server, receive and send data, and directly use getter and setter method.
public static void main(String[] args) {
TcpClient client = new TcpClient(server, port, domainModel);
}
public class TcpClient {
public void connect() {
// Code to create the socket and connect to the server.
new Thread(new TcpProtocol(socket, domainModel)).start();
}
}
I 'm using some sort of Factory class inside the TcpProtocol class to create the right object.
I would like to decouple my domain object from the network programming part. Is there some common pattern to use for this ? I was thinking about DAO and Value Object, commonly used for JavaEE applications. Those are the only one i see, but if someone has better proposition please let me know.
Thank you.
As a general rule I consider non-trivial code in the constructor to be a design smell since it complicates inheritance and other forms of extensibility.
If you do not need the object to update itself from the network after it is created, then you can use a Factory to create your POJO. I tend to avoid ValueObjects unless you are wrapping something with very little data like currency/dates otherwise you will end up with a bunch of getters/setters.
If you need the object to access the network during its use, then you can make it a Proxy and pass in a DAO that handles all the network code. For testing you pass in a Mock/Stub instead.
A start to reaching your goal would be to remove the network access code from your constructor (I'm assuming you have one class that contacts the network and you're passing your POJO to its constructor). You would instead create a utility that contacts the network.
To instantiate the correct object type from your data stream, you might consider creating a Factory that knows how to adapt the stream to specific object types.
Maybe using the java.io ObjectInputStream and ObjectOutputStream might be a simple way to do this since it does not depend on the class of the object transferred?
What i would suggest to do is apply the Observer pattern. You might also need to apply the Mediator pattern along with your Observer - but check carefully if your design
warrants this kind of complexity.
The idea behind the observer is that your UI code "listens" for changes in the presented model. When changes take place (presumably from your network-bound code) an event is fired and your UI is thus notified in order to update itself accordingly,

Categories

Resources