Android Network Operations Architecture - java

I am an aspiring Android Developer, I have faced many issues in integrating my REST apis in Android. Existing solutions like Retrofit, volley are very generic.
I have been working on creating a generic framework for REST apis. Need help to complete it. I have configured components as follows:
Assumptions: Json data type as request body and json data type as request response
CentralCommandClass (activities will access this class to perform network operations with callback method as parameter)
API class extends IntentService (static functions for get, post, put etc to start service with different parameters)
MyHttpRequest (having execute method to open url connection and gets response from server)
My questions are as follows:
Does this approach has any downside?
There is a requirement to fire few requests only after one specific request has been fired, how do I handle this case?

Related

Efficient way for rest calls inside same container

I am looking for away to make “internal” rest calls from a service entry point into rest services that are declared in the same war file.
Currently, I am using http connection to localhost. However, I believe dispatching the request directly (with requestDispatcher ?) will be more efficient - no need for connection, no need for extra execution threads, no need to send data via tcp socket, etc.
When I need the “internal” call, I do not know what is the actual object that will represent the payload, or the class/method that will process the request. All I have is the url, and a json string for the payload. I expect the response to be a json string.
Is there a standard method that will work for all rest container (e.g. using the servlet api) or using specific functions of Jersey/spring ?

reroute multiple endpoints according to the methods

I am trying to create a Rest route in Talen ESB open studio. I have an endpoint which has multiple methods inside.I access my API from Metadata. how can I reroute each endpoint according to its method. lets say endpoint is http://Example/api/version/Method/operation.
it has four methods Rawdata, balancing, customdata and final data. all these methods has multiple operations.
http://Example/api/version/Rawdata/getRawdata
http://Example/api/version/Rawdata/getdatafromfields
http://Example/api/version/balancing/getfiltereddata
How can I tell talend that when I call Rawdata in Soapui send this endpoint.
which components i can use or can Java code can do it?
Any help would be appreciated.

What's an appropriate way of appending metadata to objects before returning via a RESTful WS?

I have a RESTful web service that responds to /user/{userId} with a marshalled XML representation of a User domain object (using JAXB). What's an appropriate way of communicating back to the client additional details about their request, particularly if it doesn't return the information they're expecting? In a non-distributed Java application, you might have a catch block that deals with data access, or security exceptions. In the event that /user/{userId} doesn't return anything (e.g. the web services persistence mechanism isn't working, there is a security restriction, etc...) how do I include meaningful information in the response to the client?
I don't think DTOs are what I need because I'm not looking for different representations of a domain object. Rather, I'm looking for information about what happened during the request that may have prevented it from returning the information the client expected. Would it be appropriate to enclose the domain object within some kind of ResponseObject that holds the relevant metadata? The downside to this approach is that I'd rather not have my service layer interfaces all have ResponseObject as their return type because I may very well provide a non-RESTful implementation that doesn't have the same metadata requirements.
What's an appropriate way of communicating back to the client additional details about their request, particularly if it doesn't return the information they're expecting.
In the event that /user/{userId} doesn't return anything (e.g. the web services persistence mechanism isn't working, there is a security restriction, etc...) how do I include meaningful information in the response to the client?
This is what the HTTP Status Code is used for in a RESTful service.
To indicate that a requested userId doesn't correspond to an actual user, you can return a 404 Not Found.
To indicate an internal error within your application (such as not being able to connect to the database), you can return 500 Internal Server Error.
The option you are describing - wrapping your returns in a ResponseObject which then includes the true "response status" - sounds an awful lot like SOAP.
The beauty of REST, or at least what people claim, is that you can use the already-existing HTTP response status code to model almost all statuses of your actual response.
If it's really error situation (security problems, no DB connection or even user with provided ID not found), then just throw an Exception. Client receives fault and can behave according to information contained in it.
Which implementation do you use? In Apache CXF, for example, you can define exception handler and render XML for exception yourself, and there you are free to include any meta-info you like.
I would capture the information using exceptions, then map those exceptions to an HTTP response with the appropriate status code. You can achieve this by creating an implementation of ExceptionMapper if you're using JAX-RS, or you can subclass StatusService if you're using Restlet.
http://wikis.sun.com/display/Jersey/Overview+of+JAX-RS+1.0+Features
http://wiki.restlet.org/docs_2.0/13-restlet/27-restlet/331-restlet/202-restlet.html

How to obtain data from a webservice in a JSF action method?

I'm trying to determine the correct API calls on FacesContext to do the following when processing a backing bean action:
Within the action method construct a URL of dynamic parameters
Send the constructed URL to service
Parse the returned service response parameters
Continue with action method processing based on reponse string from request.
Any suggestions on the highlevel API calls for steps 2 and 3 to send me in the right direction would be very appreicated. Note, the service I'm calling is external to this application in a blackbox. Instructions are: send URL in specified format, parse response to see what happened.
This problem is not specific to JSF in particular, so you'll find nothing in JSF API. The standard Java API offers java.net.URL or, which allows more fine grained control, java.net.URLConnection to fire HTTP requests and obtain the response as an InputStream which you can then freely parse the usual Java way.
InputStream response = new URL("http://google.com").openStream();
// ...
Depending on the content type of the response, there may be 3rd party API's which ease the parsing. For example, Google Gson if it's JSON or Jsoup if it's HTML/XML.

Need sample Android REST Client project which implements Virgil Dobjanschi REST implementation pattern

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.

Categories

Resources