I am quite new to OSGi and everything that is close to that.
Jump into the problem: I have a server-class that keeps a list of listeners, the listeners can register theirselves via a method (register(this)) that puts the listener into that above mentioned list (all listeners implement the server-class listener interface of course):
public void register(ServerListener listener) {
if(theListeners == null)
theListeners = new ArrayList<ServerListener>();
theListeners.add(listener);
}
That's the ServerListener interface:
public interface ServerListener {
public void update(JsonObject data);
}
Now the server-class provides the listeners with new data from time to time via an update(JsonObject object) method.
public void updateListeners() {
new Thread() {
public void run() {
for(ServerListener l : theListeners) {
l.update(jsonObject);
}
}
}.start();
}
Now, I want to modify the server-class into a service bundle in an OSGi framework (Knopflerfish). I am not familiar with that at all. I want to try just for fun, but the way I am doing it right now would not work, the listeners actually don't know that they should implement the ServerListener interface. So the server can't register them via the interface.
The thing is, I want to server to push data, not the clients to pull (that would be easier, in my understanding). Can someone (who understood my poor explanation) point me in the right direction?
An 'OSGi-centric' approach is to use a pattern known as the whiteboard pattern, rather than the listener pattern as you might with plain Java. Instead of registering with the server-class, your listeners register as services with the OSGi service registry. This means the framework takes care of handling registration, unregistration, and listeners which go away.
There's a free whitepaper on the whiteboard pattern here: http://www.osgi.org/wiki/uploads/Links/whiteboard.pdf, and we've also got a discussion of it in chapter 5 of Enterprise OSGi in Action (http://www.manning.com/cummins ).
It can take a while to get your head wrapped around the listener pattern, because it's your listeners which provide services, and your 'server' which consumes the services, which feels backwards at first. Once you get used to it, though, it works really well. Your server consumes all the services which implement the ServiceListener interface, and pushes data out to them as required.
It's best not to use the OSGi APIs directly to register and consume the services - use either declarative services (SCR) or blueprint for dependency injection of the OSGi services. These allow you to register and consume the services with an XML metadata file or annotations.
(As other have suggested, using a package-level dependencies for the ServerListener interface should allow it to be imported by both the server and listener bundles, no matter which bundle exports the package.)
You've got multiple problems here:
You need to expose a service (the server class) for other objects to register with
Interested objects need to find the service in order to register themselves
The other objects need to implement a particular interface for this to work
In general, trying to retrofit existing code into the OSGi can be painful unless you already have a modular architecture.
The listener interface can live in the server bundle or you could put it in a seperate API/contract bundle - both are valid designs.
From how you are describing the problem it sounds like you don't know the different types of dependency you can have in OSGi.
Coming from traditional Java development, most developers will start with the 'my dependencies are based on JARs' - this is not the best model.
OSGi offers package-level dependencies. In this way as long as some bundle offers the needed package, you're bundle doesn't care which bundle/JAR provided the dependency.
So if you used a package-level dependency for your listener interface, the implementation doesn't need to care if it comes from the server bundle or a contract/API bundle.
As a final note your design tightly couples the server to the listeners. What happens if a listener fails? Or hangs? Pub/sub is a better model for this type of communication.
* edit *
And Holly's answer reminded me again of the whiteboard pattern - definitely a good idea.
Related
I have some doubt about how implement a simple scenario for a my style exercises following the Hexagonal architecture or Port & Adapter Pattern.
I have a UseCase (or service) that has to send a Contact (received from a contact form) to an external API service.
public class SendContactUseCase{
//output port interface
private final SendContact sendContact;
public ServiceLayer(SendContact sendContact) {
this.sendContact = sendContact;
}
public void sendContact(ContactRequest req){
sendContact.send(req);
}
}
So I have create an output port with a method send(ContactRequest req) after that I have implemented this interface as a driven adapter where I put the codes for the communication with the API
//driven adapter
public class SendContactToAPIAdapter implements SendContact {
//private final PossibleAPILib possibleAPIlib...;
#Override
public boolean send(ContactRequest req) {
//HERE the code to communicate with API
}
}
Here my doubt, what if at a later moment comes the need to send the "Contact" also to another channel, for example as XML attachment to a specific email address.
If I have understood correctly the Port & Adapter pattern to hide the infrastructure "logic" to the UseCase I should implement a new driven adapter from the same Port in order to inject the correct adapter in the UseCase.
public class SendContactXMLAdapter implements SendContact
But if I'd should invoke both the adapater? Beacause I have to send the contact to the both systems?
Should I to create a third adapter where hide the logic to call both systems?
I hope I've been clear
Thanks folks
Create a sample java project for a simple use case
The answer depends on what you actually want to accomplish.
To me, your anticipation of the 'need to send the "Contact" also to another channel' sounds like an additional feature of your business logic.
Based on that assumption, I would implement two separate port/adapter pairs, one for the API and one for XML. Your use case can then decide which ports to call.
This diagram visualizes what I mean: Component Architecture
If you really always want to send the contact to the API and export it as XML you could leave your use-case untouched and just extend the implementation of your SendContactToAPIAdapter to do both. But you should then also consider renaming it.
public interface ContactRegisterer{
public void registerContact(Contact contactToRegister) throws ContactRegisterException;
}
you could use this interface[represents a port which is used by more higher level logic of your application] so that the location of where to save the contact and how to save it could be changed independently from the client. This interface could be used to register contact to a single but different destinations, or to multiple and different destination. For instance, you could register to a file, a database, a service or all of them.
When you register to a single destination, all you need is to give a different implementation of the interface for registering to that destination.
When you register to multiple destinations, you could use Decorator design pattern. (Create a wrapper that implements the interface and also contains different objects implementing the same interface. The wrapper is given to the client(have the same interface, hence the client is not aware of the fact that it is given a wrapper), the wrapper in turn could use multiple threads for registering to each destination or use a for loop within a thread)
Another alternative is to use A Modified Version Of Chain of Responsibility pattern. In this pattern, you chain multiple(open ended) instances of the interface and every instance call the next after it is done registering to its destination.
It depends if the change is a technical change or a business logic change.
The ports and adapters architecture allows you to change the adapters without changing the Core of the application. If you have tests that validate your business logic, as you should, you'll see that you can swap adapters, everything will work fine and you won't have to change your Core tests. In this case, you can have the two adapters and configure one or the other based on some setting, or as you say, have an adapter that basically calls the other two.
On the other hand, if your business logic requirements change (depending on some business rule you have to send the contact to A or to B), you'll notice that you'll have to change your tests to verify the new requirements. In that case, your Core will define a different Port that will be more suited to the new business logic.
Let's say I have a really simple interface for getting files from somewhere:
interface FileManager {
File getFile(Object data);
}
We can assume there are multiple implementations of this interface and all applications only use the interface and are blissfully unaware of which implementation the OSGi context provides them with.
Since some methods to get files are really slow, I want to add an optional cache. But I don't want the applications to change from the FileManager interface to another one, since that would make them aware of which implementation they are using (and if it's slow or not).
So I came up with this:
class FileManagerCache implements FileManager {
private final Map<Object, File> cache = new HashMap<>();
public File getFile(final Object data) {
if (this.cache.containsKey(data)) {
return this.cache.get(data);
}
final File result = getDelegate().getFile(data);
this.cache.put(data, result);
return result;
}
private FileManager getDelegate() {
for (final FileManager fileManager : ServiceUtil.findServices(FileManager.class)) {
if (this != fileManager) {
return fileManager;
}
}
throw new UnsupportedOperationException("No FileManager is present!"); //$NON-NLS-1$
}
}
This implementation is registered with a very high "service.ranking" and so the first one the applications use, and it delegates to the next one in line in the list of possible implementations.
Now this approach is not very elegant, and probably error prone. How would I create a proxy in OSGi using standard mechanisms?
A safer way to define a proxy for another service is to use service properties.
For example you could give the slow FileManager a property like "name=A".
Then you could give the proxy the propertie name=A,cached=true. On initialization you could give the proxy a filter name=A to search for a service to proxy.
So the user of the service could either use any serivce (by ranking) or filter for cached=true if it needs the cached variant.
Why not just create a service which collects registered implementation of other services? Sample implementation and the idea you can get from here.
I think what you describe is a 2 service model because you combine multiple responsibilities. You combine the caching responsibility with the abstraction of where the file comes from. Or in other words, your design is mixing concerns and it is therefore not cohesive.
The easiest solution is therefore to have a FileManager and a FileManagerProvider service. You can then provide a cached File Manager and a transparent File Manager depending on your situation.
When I started in software more than 35 years ago I got coupling but it took me many years to understand how much more important cohesion is. This problem is a very archetypical example.
Now to see why this design is bad, you could implement the proxies with OSGi service hooks. You register an alternative and hide the original services. However, that is a lot of work to make a technical inferior solution, as all proxies related solutions have their own problems. Keeping it simple, straightforward, and using actual types to represent your abstractions is imho the best solution. (Though I admit I frequently find that I initially made uncohesive designs as well before I understood the problem well.)
Felix DependencyManager supports it.
There is the summary from http://felix.apache.org/documentation/subprojects/apache-felix-dependency-manager/reference/component-aspect.html
Dependency Manager - Aspect
Aspects, as part of aspect oriented programming, can be used in a
dynamic environment such as OSGi to "extend" existing services and add
certain "capabilities" to them. Examples of these are adding a
specific caching mechanism to a storage service or implementing
logging. Aspects in OSGi can be applied to services and can be added
and removed at runtime.
Aspects allow you to define an "interceptor", or chain of interceptors for a service to add features like caching or logging, etc. An aspect will be applied to any service that matches the specified interface and filter. For each matching service an aspect will be created based on the aspect implementation class. The aspect will be registered with the same interface and properties as the original service, plus any extra properties you supply here. It will also inherit all dependencies, and if you declare the original service as a member it will be injected.
#AspectService(ranking=10), properties={#Property(name="param", value="value")})
class AspectService implements InterceptedService {
// The service we are intercepting (injected by reflection)
protected InterceptedService intercepted;
public void doWork() {
intercepted.doWork();
}
}
I'll give a brief overview of my goals below just in case there are any better, alternative ways of accomplishing what I want. This question is very similar to what I need, but not quite exactly what I need. My question...
I have an interface:
public interface Command<T> extends Serializable {}
..plus an implementation:
public class EchoCommand implements Command<String> {
private final String stringToEcho;
public EchoCommand(String stringToEcho) {
this.stringToEcho = stringToEcho;
}
public String getStringToEcho() {
return stringToEcho;
}
}
If I create another interface:
public interface AuthorizedCommand {
String getAuthorizedUser();
}
..is there a way I can implement the AuthorizedCommand interface on EchoCommand at runtime without knowing the subclass type?
public <C extends Command<T>,T> C authorize(C command) {
// can this be done so the returned Command is also an
// instance of AuthorizedCommand?
return (C) theDecoratedCommand;
}
The why... I've used Netty to build myself a very simple proof-of-concept client / server framework based on commands. There's a one-to-one relationship between a command, shared between the client and server, and a command handler. The handler is only on the server and they're extremely simple to implement. Here's the interface.
public interface CommandHandler<C extends Command<T>,T> {
public T execute(C command);
}
On the client side, things are also extremely simple. Keeping things simple in the client is the main reason I decided to try a command based API. A client dispatches a command and gets back a Future. It's clear the call is asynchronous plus the client doesn't have deal with things like wrapping the call in a SwingWorker. Why build a synchronous API against asynchronous calls (anything over the network) just to wrap the synchronous calls in an asynchronous helper methods? I'm using Guava for this.
public <T> ListenableFuture<T> dispatch(Command<T> command)
Now I want to add authentication and authorization. I don't want to force my command handlers to know about authorization, but, in some cases, I want them to be able to interrogate something with regards to which user the command is being executed for. Mainly I want to be able to have a lastModifiedBy attribute on some data.
I'm looking at using Apache Shiro, so the obvious answer seems to be to use their SubjectAwareExecutor to get authorization information into ThreadLocal, but then my handlers need to be aware of Shiro or I need to abstract it away by finding some way of mapping commands to the authentication / authorization info in Shiro.
Since each Command is already carrying state and getting passed through my entire pipeline, things are much simpler if I can just decorate commands that have been authorized so they implement the AuthorizedCommand interface. Then my command handlers can use the info that's been decorated in, but it's completely optional.
if(command instanceof AuthorizedCommand) {
// We can interrogate the command for the extra meta data
// we're interested in.
}
That way I can also develop everything related to authentication / authorization independent of the core business logic of my application. It would also (I think) let me associate session information with a Netty Channel or ChannelGroup which I think makes more sense for an NIO framework, right? I think Netty 4 might even allow typed attributes to be set on a Channel which sounds well suited to keeping track of things like session information (I haven't looked into it though).
The main thing I want to accomplish is to be able to build a prototype of an application very quickly. I'd like to start with a client side dispatcher that's a simple map of command types to command handlers and completely ignore the networking and security side of things. Once I'm satisfied with my prototype, I'll swap in my Netty based dispatcher (using Guice) and then, very late in the development cycle, I'll add Shiro.
I'd really appreciate any comments or constructive criticism. If what I explained makes sense to do and isn't possible in plain old Java, I'd consider building that specific functionality in another JVM language. Maybe Scala?
You could try doing something like this:
Java: Extending Class At Runtime
At runtime your code would extend the class of the Command to be instantiated and implement the AuthorizedCommand interface. This would make the class an instance of AuthorizedCommand while retaining the original Command class structure.
One thing to watch for, you wouldn't be able to extend any classes with the "final" keyword.
In another question, someone told me to implement the following in my java program. But, I am very new to Java and I do not know how to start to convert my simple program into this structure:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
dependency injection.
program to the interface:
Does that come inside some framework? Should I start learning Spring and this structure will evolve naturally? Or, can I implement above technologies one by one without using a framework?
You can implement them without a framework if you wish, but you give up whatever benefits the framework offers you.
The layering you cite is correct and independent of any framework; it's just programming to interfaces and separation of concerns. You're free to do it without Spring if you wish to minimize the number of new technologies you want to learn right now.
If you don't know what persistence is, then you shouldn't jump into Spring. Persistence means storing data in relational databases using SQL to most people. If you don't know that, I'd recommend starting there.
All the patterns books in the world won't help you if you've never used the underlying technologies.
If you've never done any of this, I'd recommend sticking to straight JDBC, servlets, and JSPs using only JSTL (no scriptlets). Anything beyond that will just be confusing.
If you had a Foo model object, with persistence, service, and view tiers, the interfaces might look like this:
package model;
/**
* A model object that's interesting from your problem's point of view
*/
public class Foo
{
}
package persistence;
/**
* CRUD operations for a Foo
*/
public interface FooDao
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package service;
/**
* Just a data service that wraps FooDao for now, but other use cases would
* mean other methods. The service would also own the data connection and manage
* transactions.
*/
public interface FooService
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package view;
/**
* A class that owns services, validates and binds input from UI, and handles routing
* to the next view once service is complete.
*/
public interface FooController
{
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response);
}
These are just interfaces, of course. You'll need to provide implementations.
You might want to check out Domain Driven Design. The Code samples are in Java. The things you listed are design related more than any specific technology.
In short:
Data Access Layer is a module of your application that provides interface to your data. Data may be in SQL database, XML, file wherever. You write interfaces and classes that provide interface to access data usually as VO or DTO via DAOs
Service Layer contains most of the use-case logic. Service layer interacts with Data Access Layer to perform tasks in given use case. I did not find a good article on introductory service layer. You may see here and there
Controller is the one that interacts with Service Layer and/or Data Access Layer and/or other controllers in order to perform a specified client's tasks. For example, a sign-off button controller will request a sign-off action/service to invalidate user's sessions on all services that user is logged on to, then it will choose an appropriate view or log-off web-page to forward user to.
Presentation is your user interface. It can be a web-page made of HTML or Java Swing window or anything that user interacts with. GUI commonly known term for it. This is what your users will be interacting with using mouse clicks, scrolls, swipes, drag-and-drop. These actions are mapped with controller which performs action based on what user performed on UI.
Dependency Injection is a way to wire various components. There are a lot of resources on web. You can look in Martin Fowler's this article. It's basically a mechanism that allows components to behave much like plug-and-play devices, if you know what plug goes where.Spring is a good implementation of dependency injection. You may not want to write your own framework, and at this stage, you should rather not. There is a Spring MVC framework that can do things for you.
But I suggest you start from very basic. Instead of jumping on jargon, read from basic. Start with a good book on application development using Java. You can also look into
Design Patterns - Gang of Four
Core J2EE Patterns
Developing a Spring Framework MVC application step-by-step
dependency Injection with the Spring Framework
You can implement all of this is you want -- it's been done many times before, but nothing prevents you from doing it again.
What would be a better use of your time is to make sure you understand the separation of concerns you listed above (which are generally right) and identify the most efficient integration of existing frameworks to leverage (e.g., Hiberante, Spring, Guice, etc). There are multiple answers for that one (and no shortage of opinions!), but all things being equal, the less frameworks you have to integrate, the easier and better fitting it's likely to be.
Spring has a very well known framework which covers many of these things, so it would be wise to start there. It also allows you to work with other frameworks (i.e., you can use selective parts of Spring). For example, you can use Spring for dependency injection and use a different MVC framework.
It is very hard to answer this question. First of all, I don't know what your program looks like. Second, I don't think 'converting' it is something that can be done, or should be done for that matter. What you're talking about are architectural concepts that the developers usually have in mind while designign the application.
If these concepts interest you, I suggest reading a bit about Model-View-Controller pattern (MVC) and service-oriented Architecture (SOA).
These are general concepts that do not apply specifically to Java. However, they are widely used in Java enterprise development. Various frameworks allow you to create applications utilizing these concepts. For example, Spring Web MVC, as others have pointed out, is part of the Spring Framework that lets you create web applications that adhere to the MVC pattern.
If your program is really simple this separation might be done by using one calss for each
category.
Data Access Layer (read/write data) -> one class for presisting laoding
Service Layer (isolated business logic) -> one calss with bussiness logic
Controller (Link between view and model) -> in simple swing app this merges with UI
Presentation (UI) -> one class for one widnow
dependency injection -> not used in small apps
program to the interface -> Your service class should use interface tah is used by other class instead of directly your serivce implementation:
if it's not as simple program you might want to have package for each category.
BUT - don't overdesign! These concepts are ment to help you manage large scale applications, not to ruin you in your programming begginigs!
I am writing a Java application using SWT widgets. I would like to update the state of certain widgets upon a certain event happening (for example, updating the data model's state).
Is there something in Java similar to Cocoa's NSNotificationCenter, where I can register an object to listen for notification events and respond to them, as well as have other objects "fire off" a notification?
Ok, suppose that for example, you want parts of your program to be notified when your Loader starts a scan, and when it finishes a scan (don't worry about what a Loader is, or what a scan is, these are examples from some code I have lying around from my last job). You define an interface, call it "ScanListener", like
public interface ScanListener
{
public void scanStarted();
public void scanCompleted();
}
Now the Loader defines a method for your other code to register for callbacks, like
public void addScanListener(ScanListener listener)
{
listeners.add(listener);
}
The Loader, when it starts a scan, executes the following code
for (ScanListener listener : listeners)
{
listener.scanStarted();
}
and when it finishes, it does the same thing with listener.scanCompleted();
The code that needs to be notified of these events implements that interface (either themselves, or in an internal class), and calls "loader.addScanListener(this)". Its scanStarted() and scanCompleted() methods are called at the appropriate times. You can even do this with callbacks that take arguments and/or return results. It's all up to you.
What sort of notifications are you looking for? If all you want is for one object to be able to tell anybody else "hey, I've changed, update accordingly", the easiest way is to use the existing Observer interface and Observable class. Or write your own with an interface that defines what you want to get called on the listeners from the one that's changed.
There's no pre-existing per-process service that dispatches events in java that's equivalent to the default NSNotificationCenter. In java, the type of the event is specified by the event object being a particular type (which also means that the notification method depends on that type) rather than using a string. Prior to generics, writing a general event dispatcher and receiver that is also typesafe isn't really possible (witness the proliferation of *Event classes and *EventListener interfaces in the AWT and Spring libraries).
There are some facilities for event dispatch. As Paul mentioned, there's java.util.Observable, which as you point out, requires subclassing. There's also java.beans.PropertyChangeSupport, which could be useful depending on your situation.
You could also write one yourself. The source for PropertyChangeSupport is likely available in the openjdk, and you could look at the abandoned Apache Commons Event project. Depending on your needs, you may have to worry about stuff like threading, seralization, memory leaks (ensuring deregistration or using weak references), and concurrent modification (iterate over a copy of your list of listeners, as a listener may decide to unregister itself in response to a change).
Now that generics exist in Java, a generic event dispatch library would be possible; however, I haven't come across any. Anyone?
There's actually a facility built in to Java that does exactly what you want, but it's not something you may have considered, and, to be honest, it is likely a bit heavyweight for what you want.
That said, however, it does exist.
It's JMX.
You create MBeans, and then others can register for events from those MBeans. The MBean can then send of a Notification.
I personally wouldn't consider using it for this case (I'd just pound out my own), but the facility is there and it well defined and documented.
Not Java, but the IPython project has a notification center written in Python here that you could use as a template for a Java version.
In Java this would be a provider firing notifications to its listeners. But Java does not offer the loose coupling you get with Cocoa's NSNotification because in Java providers and subscribers must have references to each other. Compare for this chapter 18 in "Learn Objective-C for Java Developers".
There is an implementation of IOS NSNotificationCenter in Java.
You can find sources code in :
This Github project