I've stumbled upon this piece of code:
public ServiceBuilder provider(Class<? extends Api> apiClass)
What does provider in this context mean?
edit:
This is the piece of code I found it in:
https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/builder/ServiceBuilder.java
It's the name of the method. The method provider() returns a ServiceBuilder.
Here's a link to the Java Service Provider Interface.
What does provider in this context mean?
Seems this class is used with OAuth. And it's a way to make an unique way to use multiple login from various services.
Example:
Google: https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/builder/api/GoogleApi.java
Facebook: https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/builder/api/FacebookApi.java
Your method seems to be used to create an instance of there apis based on what you pass.
provider(FacebookApi.class)
for Facebook and so on. Then a Service is build using all the data.
By provider he means who provide the access token (and auth data)
Related
I have a Spring web application which uses Spring SAML and Spring Security to manage the login process.
Now I need to do some tasks after the correct login occurs. In particular I have to store some data in the SecurityContext.getContext() object.
I have never worked with Spring Security/SAML and I don't know how it manages the return from the IdP.
Is there any place in the code where usually you can put your code after the login process ends correctly?
I mean, I know where the redirect page is set but I cannot put my custom code in the Controller of this redirect page because that page is accessed more than one time, and I need to run my custom code only once at login time.
The best approach is to implement interface SAMLUserDetailsService, which will automatically store object you return from its loadUserBySAML method in the Authentication object which you can later query from the SecurityContext.getContext(). The interface is called once after each authentication. See the manual for details and examples.
The other possibility is AuthenticationSuccessHandler. The login process calls method onAuthenticationSuccess which has access to the Authentication object, which will be stored in the SecurityContext.getContext().
Simply create your own class which implements interface AuthenticationSuccessHandler (you can also extend some of the existing classes, such as SimpleUrlAuthenticationSuccessHandler or AbstractAuthenticationTargetUrlRequestHandler). Then plug your implementation to the securityContext.xml by changing class in the existing successRedirectHandler bean.
The problem is, that the Authentication object tends to be immutable - so the first way might be better.
You can use AuthenticationSuccessEvent. Just register a bean that implements ApplicationListener.
#Component
public class SomeSpringBean implements
ApplicationListener<AuthenticationSuccessEvent> {
public onApplicationEvent(AuthenticationSuccessEvent event) {
String userName = ((UserDetails) event.getAuthentication().
//do stuff
}
}
And you need to register AuthenticationEventPublisher.
Take a look here: https://gist.github.com/msarhan/10834401
If you use custom authentication provider, you can also plug whatever you want there.
Are you using Spring's Java configs?
If so, then you probably have a class that overrides WebSecurityConfigurerAdapter in your project. Extending this class gives you access to override the method configure(HttpSecurity http).
You can use that provided HttpSecurity builder object to configure a lot of things, one of which is the authentication success handler. More or less, you can create a simple that class that implements AuthenticationSuccessHandler (Spring has a few classes already built for extension to make this easy), and you can call http.successHandler(yourSuccessHandler) to register it with Spring Security.
Implementing that interface gives you the hook to put custom code into the onAuthenticationSuccess( ... ) method. I think they have one for failures as well.
I am asking to create an SIP client, but I am totally lost ...
After some researches I found the Jain SIP API in java, and I think that I will use it.
However I don't really know what classes I should use and what interfaces I should implement or not.
I have read this article : http://www.oracle.com/technetwork/articles/entarch/introduction-jain-sip-090386.html
And this : http://hudson.jboss.org/hudson/job/jain-sip/lastSuccessfulBuild/artifact/javadoc/javax/sip/package-summary.html#package_description
But I don't understand which part should I implement for an SIP client ? The SipListener OR the SipStack and the SipProvider ?
Thanks.
You need to implement both of those classes.
The SipProvider class will connect to your endpoint (Aterisk, for example). Note that this class must be on an static context, because only one connection is allowed per client.
You cant create a SipProvider instance calling a SipStack class, on sipStack.createSipProvider(listeningPoint). After this, you be able to create transactions and send requests to you endpoint.
The SipListener is the class that will process all responses from your server. This means that every request that you send to the server (Via SipProvider) will receive a response on SipListener. So, you must have this listener to process all data returned by your endpoint.
Try to implement the code that was described on oracle article that you cite. I started to develop based on this article, and works very fine!
Check the examples at the Reference Implementation https://java.net/projects/jsip/sources/svn/show/trunk/src/examples?rev=2279 to help you moving forward faster
I am reading Bloch's Effective java book[1] and came across the following example of SPI:
//Service interface
public interface Service {
//Service specific methods here
}
//Service provider interface
public interface Provider {
Service newService();
}
//Class for service registration and access
public class Services {
private Services(){}
private static final Map<String, Provider> providers =
new ConcurrentHashMap<String, Provider>();
public static final String DEFAULT_PROVIDER_NAME = "<def>";
//Registration
public static void registerDefaultProvider(Provider p) {
registerProvider(DEFAULT_PROVIDER_NAME, p);
}
public static void registerProvider(String name, Provider p) {
providers.put(name, p);
}
//Access
public static Service newInstance() {
return newInstance(DEFAULT_PROVIDER_NAME);
}
public static Service newInstance(String name) {
// you get the point..lookup in the map the provider by name
// and return provider.newService();
}
This my question: why is the Provider interface necessary? Couldn't we have just as easily registered the Service(s) themselves - e.g. maintain a map of the Service implementations and then return the instance when looked up? Why the extra layer of abstraction?
Perhaps this example is just too generic - any "better" example to illustrate the point would be great too.
[1] Second edition, Chapter 2. The first edition example does not refer to the Service Provider Interfaces.
Why is the Provider interface necessary? Couldn't we have just as easily registered the Service(s) themselves - e.g. maintain a map of the Service implementations and then return the instance when looked up?
As others have stated, the purpose of a Provider is to have an AbstractFactory that can make Service instances. You don't always want to keep a reference to all the Service implementations because they might be short lived and/or might not be reusable after they have been executed.
But what is the purpose of the provider and how can you use a "provider registration API" if you don't have a provider
One of the most powerful reasons to have a Provider interface is so you DON'T need to have an implementation at compile time. Users of your API can add their own implementations later.
Let's use JDBC as an example like Ajay used in another answer but let's take it a little further:
There are many different types of Databases and database vendors who all have slightly different ways of managing and implementing databases (and perhaps how to query them). The creators of Java can't possibly create implementations of all these different possible ways for many reasons:
When Java was first written, many of these database companies or systems didn't exist yet.
Not all these database vendors are open source so the creators of Java couldn't know how to communicate with them even if they wanted to.
Users might want to write their own custom database
So how do you solve this? By using a Service Provider.
The Driver interface is the Provider. It provides methods for interacting with a particular vendor's databases. One of the methods in Driver is a factory method to make a Connection instance(which is the Service) to the database given a url and other properties (like user name and password etc).
Each Database vendor writes their own Driver implementation for how to communicate with their own database system. These aren't included in the JDK; you must go to the company websites or some other code repository and download them as a separate jar.
To use these drivers, you must add the jar to your classpath and then use the JDK DriverManager class to register the driver.
The DriverManager class is the Service Registration.
The DriverManager class has a method registerDriver(Driver) that is used to register a Driver instance in the Service Registration so it can be used. By convention, most Driver implementations register at class loading time so all you have to do in your code is write
Class.forname("foo.bar.Driver");
To register the Driver for vendor "foo.bar" (assuming you have the jar with that class in your classpath.)
Once the Database Drivers are registered, you can get a Service implementation instance that is connected to your database.
For example, if you had a mysql database on your local machine named "test" and you had a user account with username "monty" and password "greatsqldb" then you can create a Service implementation like this :
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test?" +
"user=monty&password=greatsqldb");
The DriverManager class sees the String you passed in and finds the registered driver that can understand what that means. (This is actually done using the Chain of Responsibility Pattern by going through all the registered Drivers and invoking their Driver.acceptsUrl(Stirng) method until the url gets accepted)
Notice that there is no mysql specific code in the JDK. All you had to do is register a Driver of some vendor and then pass a properly formatted String to the Service Provider. If we later decide to use a different database vendor (like oracle or sybase) then we just swap jars and modify the our connection string. The code in the DriverManager does not change.
Why didn't we just make a connection once and keep it around? Why do we need the Service?
We might want connect/disconnect after each operation. Or we might want to keep the connection around longer. Having the Service allows us to create new connections whenever we want and does not preclude us from keeping a reference to it to re-use later.
This is a very powerful concept and is used by frameworks to allow many possible permutations and extensions without cluttering the core codebase.
EDIT
Working with multiple Providers and Providers that provide multiple Services:
There is nothing stopping you from having multiple Providers. You can connect to multiple databases created using different database vendor software at the same time. You can also connect to multiple databases produced by the same vendor at the same time.
Multiple services - Some Providers may even provide different Service implementations depending on the connect url. For example, H2 can create both file system based or in-memeory based databases. The way to tell H2 which one you want to use is a different url format. I haven't looked at the H2 code, but I assume the file based and the in memory based are different Service implementations.
Why doesn't the DriverManager just manage Connections and Oracle could implement the OracleConnectionWrapper? No providers!
That would also require you to know that you have an Oracle connection. That is very tight coupling and I would have to change lots of code if I ever changed vendors.
The Service Registration just takes a String. Remember that it uses the chain of Responsiblity to find the first registered Provider that knows how to handle the url. the application can be vendor neutral, and it can get the connection url and Driver class name from a property file. That way I don't have to recompile my code if I change vendors. However, if I hardcoded refernences to "OracleConnectionWrapper" and then I changed vendors, I would have to rewrite portions of my code and then recompile.
There is nothing preventing someone from supporting multiple database vendor url formats if they want. So I can make a GenericDriver that could handle mysql and oracle if I wanted to.
If you might need more than one service of each type, you can't just reuse the old Services. (Additionally, tests and the like might want to create fresh services for each test, rather than reusing services that might have been modified or updated by previous tests.)
I think the answer is mentioned in Effective Java along with an example.
An optional fourth component of a service provider framework is a
service provider interface, which providers implement to create
instances of their service implementation. In the absence of a service
provider interface, implementations are registered by class name and
instantiated reflectively (Item 53).
In the case of JDBC,
Connection plays the part of the service interface,
DriverManager.registerDriver is the provider registration API, DriverManager.getConnection is the service access API, and
Driver is the service provider interface.
So as you have correctly noted it is not a must to have the Provider interface but just a little cleaner approach.
So seems like you can have multiple Providers for the same Service and based on a specific Provider name you may get different instances of the same Service. So I would say each Provider is kind of like factory that creates the service appropriately.
For example suppose class PaymentService implements Service and it requires a Gateway. You have PayPal and Chase gateway that deal with those payment processors. Now you create a PayPalProvider and ChaseProvider each of which knows how to create the correct the PaymentService instance with the right gateway.
But I agree, seems contrived.
As a synthesis of the other answers (the fourth component is the textual reason) I think this is to limit compilation dependencies. With the SPI, you have all the tools to exclude en explicit reference to the implementation:
The META-INF/services/ directory contains files mentioning the available service provider implementations
The ServiceLoader standard class allows the resolution of the available implementations names and by the way a dynamic construction [1].
The SPI was not mentioned in the first edition. It was perhaps not the right place to include it in an item about static factories. The DriverManager mentioned in the text is a hint, but Bloch does not go in deep. In a way, the platform implements a kind of ServiceLocator pattern to reduce compilation dependencies, depending on the environment. With a SPI in your abstract factory, it becomes the ServiceFactory of a ServiceLocator with the help of the ServiceLoader for modularity.
The ServiceLoader iterator could be used to populate dynamically the services map of the example.
[1] In an OSGi environment, this is a subtle operation.
Service Provider Interface without a provider
Let's see how it would look like without a provider.
//Service interface
public interface Service {
//Service specific methods here
}
//Class for service registration and access
public class Services {
private Services(){}
private static final Map<String, Service> services =
new ConcurrentHashMap<String, Service>();
public static final String DEFAULT_SERVICE_NAME = "<def>";
//Registration
public static void registerDefaultService(Provider p) {
registerService(DEFAULT_SERVICE_NAME, p);
}
public static void registerService(String name, Provider p) {
services.put(name, p);
}
//Access
public static Service getInstance() {
return newInstance(DEFAULT_SERVICE_NAME);
}
public static Service getInstance(String name) {
// you get the point..lookup in the map the service by name
// and return it;
}
As you see, it's possible to create a Service Provider Interface without a Provider interface. Callers of #getInstance(..) eventually wouldn't notice a difference.
Then why do we need a provider?
The Provider interface is an Abstract Factory and Services#newInstance(String) is a Factory Method. Both design patterns have the advantage that they decouple service implementation from service registration.
Single responsibility principle
Instead of implementing the service instantiation in a startup event handler, which registers all services, you create one provider per service. This makes it loosely coupled and easier to refactor, because Service and Service Provider could be put near to each other, for example into another JAR-file.
"Factory methods are common in toolkits and frameworks, where library code needs to create objects of types that may be subclassed by applications using the framework." [1]
Lifetime management:
You might have realized in the upper code without providers, that we're registering service instances instead of a provider, which could decide to instantiate a new service instance.
This approach has some disadvantages:
1. Service instances have to be created before the first service call. Lazy initialization isn't possible. This will delay startup and bind resources to services which are rarely used or even never.
1b. You "cannot" close services after usage, because there is no way to reinstantiate them. (With a provider you could design the service interface in a way that the caller has to call #close(), which informs the provider and the provider decides to keep or finalize the service instance.)
2. All callers will use the same service instance, therefore you have to make sure that it's thread-safe. But making it thread-safe will make it slow. In contrary a provider might choose to create a couple of service instances to reduce retention time.
Conclusion
A provider interface isn't required, but it encapsulates service-specific instantiation logic and optimizes resource allocation.
Does Spring Security provide any way to authorize a user in java class, the way it provides tags for authorization in JSPs (such as <sec:authorize ifAllGranted="ROLE_ADMIN"/>)?
I am expecting a static method of some class that I can use in my code like this:
if(SomeSpringSecurityClass.authorize("ROLE_ADMIN")){
...
}
You'd better do this check declaratively, but if you still need programmatic way - it has already been discussed on stackoverflow earlier: How to check "hasRole" in Java Code with Spring Security?
In short words, there's no such single ready-made method but you can start from SecurityContextHolder.getContext() to perform this check.
I want to build a REST Client on an android phone.
The REST server exposes several resources, e.g. (GET)
http://foo.bar/customer List of all customer
http://foo.bar/customer/4711 The customer with id 4711
http://foo.bar/customer/vip List of all VIP customer
http://foo.bar/company List of all companys
http://foo.bar/company/4711 The company with the ID 4711
http://foo.bar/company/vip List of all VIP companys
I (think) I know how to talk to the REST server and get the information I need. I would implement a REST Client class with an API like this
public List<Customer> getCustomers();
public Customer getCustomer(final String id);
public List<Customer> getVipCustomer();
public List<Company> getCompanies();
public Customer getCompany(final String id);
public List<Customer> getVipCompanies();
Referred to the presentation "Developing Android REST client applications" from Virgil Dobjanschi I learned that it is no good idea to handle the REST request in an Worker Thread of the Activity. Instead I should use the Service API.
I like the idea of having a Singleton ServiceHelper which binds to a (Local) Service but I am afraid that I did not understand the Service concept correct.
For now I do not understand how to report a REST call result (done asynchrounous in a Service) back to the caller Activity. I also wonder if I need ONE Service which handles all REST requests (with different return types) or if I need a dedicated service for each REST request.
Probably I have many other understanding problems so the best thing for me would be a sample application which meets my needs. My use case is not unusual and I hope there is in example application out there.
Would you please let me know!
Any other suggestions which points me in the correct implementation direction are also helpful (Android API-Demo does not match my use case).
Thanks in advance.
Klaus
EDIT: Similar Topics found on SO (after posting this) which lead me in the direction I need (minimizing the complex "Dobjanschi pattern"):
Android: restful API service
OverView
Edit:
Anyone interest also consider taking a look at RESTful android this might give you a better look about it.
What i learned from the experience on trying to implement the Dobjanschi Model, is that not everything is written in stone and he only give you the overview of what to do this might changed from app to app but the formula is:
Follow this ideas + Add your own = Happy Android application
The model on some apps may vary from requirement some might not need the Account for the SyncAdapter other might use C2DM, this one that i worked recently might help someone:
Create an application that have Account and AccountManager
It will allow you to use the SyncAdapter to synchronized your data. This have been discussed on Create your own SyncAdapter
Create a ContentProvider (if it suits your needs)
This abstraction allows you to not only access the database but goes to the ServiceHelper to execute REST calls as it has one-per-one Mapping method with the REST Arch.
Content Provider | REST Method
query ----------------> GET
insert ----------------> PUT
update ----------------> POST
delete ----------------> DELETE
ServiceHelper Layering
This guy will basicly start (a) service(s) that execute a Http(not necessarily the protocol but it's the most common) REST method with the parameters that you passed from the ContentProvider. I passed the match integer that is gotten from the UriMatcher on the content Provider so i know what REST resource to access, i.e.
class ServiceHelper{
public static void execute(Context context,int match,String parameters){
//find the service resource (/path/to/remote/service with the match
//start service with parameters
}
}
The service
Gets executed (I use IntentService most of the time) and it goes to the RESTMethod with the params passed from the helper, what is it good for? well remember Service are good to run things in background.
Also implement a BroadCastReceiver so when the service is done with its work notify my Activity that registered this Broadcast and requery again. I believe this last step is not on Virgill Conference but I'm pretty sure is a good way to go.
RESTMethod class
Takes the parameters, the WS resource(http://myservice.com/service/path) adds the parameters,prepared everything, execute the call, and save the response.
If the authtoken is needed you can requested from the AccountManager
If the calling of the service failed because authentication, you can invalidate the authtoken and reauth to get a new token.
Finally the RESTMethod gives me either a XML or JSON no matter i create a processor based on the matcher and pass the response.
The processor
It's in charged of parsing the response and insert it locally.
A Sample Application? Of course!
Also if you are interesting on a test application you look at Eli-G, it might not be the best example but it follow the Service REST approach, it is built with ServiceHelper, Processor, ContentProvider, Loader, and Broadcast.
Programming Android has a complete chapter (13. Exploring Content Providers) dedicated to 'Option B: Use the ContentProvider API' from Virgil's Google I/O talk.
We are not the only ones who see the benefits of this approach. At the Google I/O conference in May 2010, Virgil Dobjanschi of Google presented a talk that outlined the following three patterns for using content providers to integrate RESTful web services into Android applications...
In this chapter, we’ll explore the second pattern in detail with our second Finch video example; this strategy will yield a number of important benefits for your applications. Due to the elegance with which this approach integrates network operations into Android MVC, we’ve given it the moniker “Network MVC.”
A future edition of Programming Android may address the other two approaches, as well as document more details of this Google presentation. After you finish reading this chapter, we suggest that you view Google’s talk.
Highly recommended.
Programming Android by Zigurd Mednieks, Laird Dornin, G. Blake Meike, and Masumi Nakamura. Copyright 2011 O’Reilly Media, Inc., 978-1-449-38969-7.
"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.
A reference implementation is available under http://datadroid.foxykeep.com (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.
Android Priority Job Queue was inspired by Dobjanschi's talk and sounds very promising to me.
Please comment if you know more implementations.
We have developped a library that adresses this issue : RoboSpice.
The library uses the "service approach" described by Virgil Dobjanschi and Neil Goodmann, but we offer a complete all-in-one solution that :
executes asynchronously (in a background AndroidService) network
requests that will return POJOs (ex: REST requests)
caches results (in Json, or Xml, or flat text files, or binary files)
notifies your activities (or any other context) of the result of the network
request if they are still alive
doesn't notify your activities of the
result if they are not alive anymore
notifies your activities on
their UI Thread
uses a simple but robust exception handling model
supports multiple ContentServices to aggregate different web services
results
supports multi-threading of request executions
is strongly
typed !
is open source ;)
and tested
We are actually looking for feedback from the community.
Retrofit could be very helpful here, it builds an Adapter for you from a very simple configuration like:
Retrofit turns your REST API into a Java interface.
public interface GitHubService {
#GET("/users/{user}/repos")
List<Repo> listRepos(#Path("user") String user);
}
The RestAdapter class generates an implementation of the GitHubService interface.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = restAdapter.create(GitHubService.class);
Each call on the generated GitHubService makes an HTTP request to the remote webserver.
List<Repo> repos = service.listRepos("octocat");
for more information visit the official site: http://square.github.io/retrofit/
Note: the adapter RestAdapter you get from Retrofit is not derived from BaseAdapter you should make a wrapper for it somehow like this SO question
Why is my ListView empty after calling setListAdapter inside ListFragment?
This is a little late but here is an article which explains the first pattern from the talk:
http://www.codeproject.com/Articles/429997/Sample-Implementation-of-Virgil-Dobjanschis-Rest-p
The thing I like about the first pattern is that the interface to the rest methods is a plain class, and the Content Provider is left to simply provide access to the database.
You should check out the source code for Google's official I/O 2010 app, for starters, particularly the SyncService and the various classes in the io subpackage.
Good news guys.
An implementation of the service helper is available here: https://github.com/MathiasSeguy-Android2EE/MythicServiceHelper
It's an open source project (Apache 2).
I am at the beginning of the project. I've done a project where I defined the pattern to do, but i haven't yet extract the code to make a clean librairy.
It will be done soon.