We have a Play! application where we need to expose a set of REST interfaces to an intranet and a set of REST interfaces we have to expose to the public internet. They share a data layer so we would like to run them together if possible. My assumption is that they will be running on different ports. Being new to Play!, I don't know if this is possible to do within a single Play! instance. I have looked at modules but that didn't seem to fit what we are doing. Has anyone had any experience with this sort of scenario?
Forgot to mention we are using Play! 2.
You could restrict/permit access to resources by checking the ip.
public class IPLocalSecurity extends Controller {
#Before
public static void checkAccess() throws Exception {
if (!request.remoteAddress.matches("192\.168\.1\.*")) {
forbidden();
}
}
}
and use that in the resources controller.
#With(IPLocalSecurity.class)
public class IntranetController extends Controller{
....
}
Related
Hi everybody,
I encounter implementation issues with the rest-dispatch module of the gwtp framework.
If i follow the current documentation, the resource interface defining what a service provide should be as follow:
#Path(FOO)
#Produces(MediaType.APPLICATION_JSON)
public interface FooResource {
#GET
RestAction<FooDTO> getFoo();
}
On the client side (without delegate extension):
#Inject RestDispatch dispatcher;
#Inject FooResource fooResource;
...
dispatcher.execute(fooResource.getFoo(), new AsyncCallback<FooDTO>() {
#Override
public void onFailure(Throwable throwable) {
}
#Override
public void onSuccess(FooDTO fooDto) {
}
});
...
Question
The RestDispatch is waiting for method that return RestAction, but since the RestService interface has been remove from 1.5 release:
How can i implements the FooResource ?
Moreover
In the carstore sample project, the only resource that uses RestAction is:
https://github.com/ArcBees/GWTP-Samples/blob/master/carstore/src/main/java/com/gwtplatform/carstore/shared/api/StatisticsResource.java
But it's implementation, is in fact not an implementation in that case:
https://github.com/ArcBees/GWTP-Samples/blob/master/carstore/src/main/java/com/gwtplatform/carstore/server/api/StatisticsResourceImpl.java
Should i follow this example, and what is the purpose of an non-implemented Interface ?
I assume that my question is very specific and it is maybe principally directed to the authors of gwtp.
And i thank in advance those who will respond.
The rest-dispatch is a client-library, and the interface that describes the services are not to use on the server side.
I was attempting to do something not intended by the authors of GWTP.
Yet, the DelegateResource extension is a solution, if you want to use the interface on the server side too. It comes with a drawback: the anability to have type safe callback on the client side.
To go further, here the exchange i had with the team on github:
https://github.com/ArcBees/GWTP-Samples/issues/92
I am trying to understand the spring data solr showcase project.
https://github.com/christophstrobl/spring-data-solr-showcase
After spending quite a bit of time, I could not find how the productRepository is implemented and injected in https://github.com/christophstrobl/spring-data-solr-showcase/blob/master/src/main/java/org/springframework/data/solr/showcase/product/ProductServiceImpl.java
#Service class ProductServiceImpl implements ProductService {
private static final Pattern IGNORED_CHARS_PATTERN = Pattern.compile("\\p{Punct}");
private ProductRepository productRepository;
#Autowired
public void setProductRepository(ProductRepository productRepository) {
this.productRepository = productRepository;
}
The ProductRepository is defined as interface (https://github.com/christophstrobl/spring-data-solr-showcase/blob/master/src/main/java/org/springframework/data/solr/showcase/product/ProductRepository.java) and I did not find any code implementing this interface
interface ProductRepository extends SolrCrudRepository<Product, String> {
#Highlight(prefix = "<b>", postfix = "</b>")
#Query(fields = { SearchableProductDefinition.ID_FIELD_NAME,
SearchableProductDefinition.NAME_FIELD_NAME,
SearchableProductDefinition.PRICE_FIELD_NAME,
SearchableProductDefinition.FEATURES_FIELD_NAME,
SearchableProductDefinition.AVAILABLE_FIELD_NAME },
defaultOperator = Operator.AND)
HighlightPage<Product> findByNameIn(Collection<String> names, Pageable page);
#Facet(fields = { SearchableProductDefinition.NAME_FIELD_NAME })
FacetPage<Product> findByNameStartsWith(Collection<String> nameFragments, Pageable pagebale);
}
Below is how the spring context is configured:
https://github.com/christophstrobl/spring-data-solr-showcase/blob/master/src/main/java/org/springframework/data/solr/showcase/Application.java
If anyone could point me to the direction where this interface is implemented and injected, that would be great.
The showcase makes use of Spring Data repository abstractions using query derivation from method name. So the infrastructure provided by Spring Data and the Solr module take care of creating the required implementations for you. Please have a look at the Reference Documentation for a more detailed explanation.
The showcase itself is built in a way that allows you to step through several stages of development by having a look at the diffs transitioning from one step to the other. So having a look at Step 2 shows how to make use of Custom Repository Implementation, while Step 4 demonstractes how to enable Highlighting using #Highlight.
The goal of Spring Data is to reduce the amount of boilerplate coding (means to reduce repetition of code).
For the basic methods like save,find the implementation will provide by spring and spring will create beans(Objetcs) for these interfaces. To tell the spring that these are my repositories inside this package, we are writing #EnableJpaRepositories(basePackeges="com.spring.repositories") or <jpa:repositories base-package="com.acme.repositories"/> for JPA repositories
Foring solr repositores we have to write #EnableSolrRepositories(basePackages="com.spring.repositories" or <solr:repositories base-package="com.acme.repositories" /> Spring will create objetcs for these interfaces, we can inject these interface objetcs using #Autowire annotation.
Example:
#Service
Pulic class SomeService{
#Autowire
private SampleRepository;
/* #postConstruct annotation is used to execute method just after creating bean
and injecting all dependencies by spring*/
#PostConstruct
public void postConstruct(){
System.out.println("SampleRepository implementation class name"+ SampleRepository.getClass());
}
}
The above example is to see the implementation class of SampleRepository interface (This class is not user defined, it is class given by spring).
For reference documentation link http://docs.spring.io/spring-data/solr/docs/2.0.2.RELEASE/reference/html/. Try to read this simple documentation you can get more knowlede on spring-data.
I just started playing around with OSGi services and have the following situation. I have a project which contains 2 services. Service A requires Service B, so I tried to inject the dependent service using
#Inject
private ServiceB svc;
but the framework wont inject. If I setup the following two methods in Service A
and set these methods as "bind / undbind" in my OSGi componentA.xml the framework calls
these methods and I can use Service B in Service A.
public synchronized void bind(IServiceB service)
{
this.svc = service;
}
public synchronized void unbind(IServiceB service)
{
if (this.svc == service)
{
this.svc = null;
}
}
The question is, why does it not work with #Inject ? Sorry if this is a stupid question, I'm quite new to this whole topic. Many thanks in advance!
It looks like you are using Declarative Services, which does not support field injection or the JSR-330 annotations. Field injection has limited utility in OSGi, where services may be injected or "un-injected" at any time. Method injection is more generally useful because it gives you an opportunity to do something when this happens.
However I do urge you to use the annotations for Declarative Services. This will save you from having to write the component.xml by hand.
I've been trying some examples with OSGi Declarative Services (among other things, such as Blueprint) on Karaf. The problem I am trying to solve now, is how to get references to certain services at runtime (so annotations and/or XML are not really an option here)
I will explain my use case:
I am trying to design (so far only in my head, that's why I am still only experimenting with OSGi :) ) a system to control certain automation processes in industry. To communicate with devices, a special set of protocols is being used. To make the components as reusable as possible, I designed a communication model based on layers (such as ISO/OSI model for networking, but much more simple)
To transform this into OSGi, each layer of my system would be composed of a set of bundles. One for interfaces of that layer, and then one plugin for each implementation of that layer (imagine this as TCP vs. UDP on the Transport layer of OSI).
To reference any device in such network, a custom address format will be used (two examples of such addresses can be xpa://12.5/03FE or xpb://12.5/03FE). Such address contains all information about layers and their values needed in order to access the requested device. As you can guess, each part of this address represents one layer of my networking model.
These addresses will be stored in some configuration database (so, again, simple .cfg or .properties files are not an option) so that they can be changed at runtime remotely.
I am thinking about creating a Factory, that will parse this address and, according to all its components, will create a chain of objects (get appropriate services from OSGi) that implement all layers and configure them accordingly.
As there can be more implementations of a single layer (therefore, more services implementing a single interface), this factory will need to decide, at runtime (when it gets the device address passed as string), which particular implementation to choose (according to additional properties the services will declare).
How could this be implemented in OSGi? What approach is better for this, DS, Blueprint or something else?
I realise that this is now a very late answer to this question, but both answers miss the obvious built-in support for filtering in Declarative Services.
A target filter can be defined for a DS reference using the #Reference annotation:
#Component
public class ExampleComponent {
#Reference(target="(foo=bar)")
MyService myService;
}
This target filter can also be added (or overriden) using configuration. For the component:
#Component(configurationPid="fizz.buzz")
public class ExampleComponent {
#Reference
MyService myService;
}
A configuration dictionary for the pid fizz.buzz can then set a new filter using the key myService.target.
This is a much better option than jumping down to the raw OSGi API, and has been available for several specification releases.
I revoke my answer, because the acceppted answer is correct. When I answered that question I missed this little, but very important detail in the spec.
There is a nice way given by OSGi called service tracker. You can use inside a declarative service. In this example there is a config which holds the filter for the service you want to use. If the filter configuration changes, the whole component reactivating, so the tracking mechanism is restarting.
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
#Component(immediate = true, metatype = true)
#Properties(value = {
#Property(name = "filterCriteria", value = "(objectClass=*)")
})
public class CustomTracker {
private CustomServiceTracker customServiceTracker;
#Activate
protected void activate(ComponentContext componentContext) throws InvalidSyntaxException {
String filterCriteria = (String) componentContext.getProperties().get("filterCriteria");
customServiceTracker = new CustomServiceTracker(componentContext.getBundleContext(), filterCriteria);
customServiceTracker.open(true);
}
#Deactivate
protected void deactivate() {
customServiceTracker.close();
}
/**
* OSGi framework service tracker implementation. It is able to listen all serivces available in the system.
*/
class CustomServiceTracker extends ServiceTracker {
CustomServiceTracker(BundleContext bundleContext, String filterCriteria) throws InvalidSyntaxException {
super(bundleContext, bundleContext.createFilter(filterCriteria), (ServiceTrackerCustomizer) null);
}
#SuppressWarnings("checkstyle:illegalcatch")
#Override
public Object addingService(ServiceReference serviceReference) {
try {
Object instance = super.addingService(serviceReference);
// TODO: Whatever you need
return instance;
} catch (Exception e) {
LOGGER.error("Error adding service", e);
}
return null;
}
#Override
public void removedService(ServiceReference serviceReference, Object service) {
// TODO: Whatever you need
super.removedService(serviceReference, service);
}
#Override
public void modifiedService(ServiceReference serviceReference,
Object service) {
super.modifiedService(serviceReference, service);
}
}
}
The only option I see for this use case is to use the OSGi API directly. It sounds like you have to do the service lookups each time you get an address to process. Thus you will have to get the appropriate service implementation (based on a filter) each time you are going to process an address.
Declarative approaches like DS and Blueprint will not enable you to do this, as the filters cannot be altered at runtime.
I start loving OSGi services more and more and want to realize a lot more of my components as services. Now I'm looking for best-practice, especially for UI components.
For Listener-relations I use the whiteboard-pattern, which IMHO opinion is the best approach. However if I want more than just notifications, I can think of three possible solutions.
Imagine the following scenario:
interface IDatabaseService {
EntityManager getEntityManager();
}
[1] Whiteboard Pattern - with self setting service
I would create a new service interface:
interface IDatabaseServiceConsumer {
setDatabaseService(IDatabaseService service);
}
and create a declarative IDatabaseService component with a bindConsumer method like this
protected void bindConsumer(IDatabaseServiceConsumer consumer) {
consumer.setDatabaseService(this);
}
protected void unbindConsumer(IDatabaseServiceConsumer consumer) {
consumer.setDatabaseService(null);
}
This approach assumes that there's only one IDatabaseService.
[Update] Usage would look like this:
class MyUIClass ... {
private IDatabaseService dbService;
Consumer c = new IDatabaseServiceConsumer() {
setDatabaseService(IDatabaseService service) {
dbService = service;
}
}
Activator.registerService(IDatabaseServiceConsumer.class,c,null);
...
}
[2] Make my class a service
Image a class like
public class DatabaseEntryViewer extends TableViewer
Now, I just add bind/unbind methods for my IDatabaseService and add a component.xml and add my DatabaseEntryViewer. This approach assumes, that there is a non-argument constructor and I create the UI components via a OSGi-Service-Factory.
[3] Classic way: ServiceTracker
The classic way to register a static ServiceTracker in my Activator and access it. The class which uses the tracker must handle the dynamic.
Currently I'm favoring the first one, as this approach doesn't complicated object creation and saves the Activator from endless, static ServiceTrackers.
I have to agree with #Neil Bartlett, your option 1 is backward. You are in effect using an Observer/Observable pattern.
Number 2 is not going to work, since the way UI objects lifecycles are managed in RCP won't allow you to do what you want. The widget will have to be created as part of the initialization of some sort of view container (ViewPart, Dialog, ...). This view part is typically configured and managed via the Workbench/plugin mechanism. You should work with this, not against it.
Number 3 would be a simple option, not necessarily the best, but simple.
If you use Spring DM, then you can easily accomplish number 2. It provides a means to inject your service beans into your UI Views, Pages, etc. You use a spring factory to create your views (as defined in your plugin.xml), which is configured via a Spring configuration, which is capable of injecting your services into the bean.
You may also be able to combine the technique used by the SpringExtensionFactory class along with DI to accomplish the same thing, without introducing another piece of technology. I haven't tried it myself so I cannot comment on the difficulty, although it is what I would try to do to bridge the gap between RCP and OSGi if I wasn't already using Spring DM.