Calling web-app methods using hessdroid = new AsyncTask for each method? - java

In my Android application I want to call some web-app methods.
I use hessian for this (hessdroid library for Android).
That's how it works:
In my Android app I have interfaces for all of the the server methods e.g. getUserById(), getMessageById(), getSomethingElse() etc.
With Hessian I can call these methods through http.
So I need to initalize Hessian Proxy for that:
HessianProxyFactory proxyFactory = new HessianProxyFactory();
UserAccountService api = (UserAccountService) proxyFactory.create(UserAccountService.class, "http://localhost:8080/server/UserAccountService", getClassLoader());
After that I am able to run server methods like that:
UserAccount user = api.getUserById(999);
The problem is that api calls like "api.someMethod();" require running from separeted thread. In any other case I have NetworkOnMainThread exception.
My question is about how to make these calls in right way?
Should I create AsyncTask for every server method call? Or it is possible to make that more generic? I really dont think that creating AsyncTask for every method is a right way. It makes code dirty.
Any ideas? I really appreciate any solution you can provide.

Related

Find out which endpoint sent a REST call

I'm trying to create a visualisation of REST calls among several internal and external services/servers. I'd like to know which endpoint called which other endpoint. I figured that the only way to do this is to do this on the caller side, because the receiver does not have any information about the caller endpoint.
Here's my thinking:
I create an object like RestTemplate and call the method.
I create an Interceptor or something like that, which will extract the information from the RestTemplate.
My problem is that I'm not sure how to find out which REST endpoint called the RestTemplate method. The RestTemplate (or other similar object) call could be called in nested methods, so for example the endpoint could invoke a private method, which then calls the external service itself.
Is there any way how to get this information? Or am I maybe just thinking too hard and there is an easier way to do this?
Example:
#GetMapping("/hello")
public String hello() {
methodThatCallsOtherEndpoint("something.com/weather"); // this method inside itself calls an endpoint
logRestCall("localhost:8000/hello", "something.com/weather"); // how do I do this automatically without having to type it myself?
return "hello";
}
Thanks for any help.
If these services/servers have a static IP you can possibly, tag them by their IP address?
You can use Spring Sleuth to trace the relationship between different REST calls.

GRPC Java pass data from server interceptor to rpc service call

We are using Java GRPC for one of our internal services and we have a server side interceptor that we use to grab information from the headers and set them up in a logging context that that uses a ThreadLocal internally.
So in our interceptor we do something similar to this:
LogMessageBuilder.setServiceName("some-service");
final String someHeaderWeWant = headers.get(HEADER_KEY);
final LoggerContext.Builder loggingContextBuilder = new LoggerContext.Builder()
.someFieldFromHeaders(someHeaderWeWant);
LoggerContext.setContext(loggingContextBuilder.build());
Then in our service call we access it like this:
LoggingContext loggingContext = LoggingContext.getCurrent()
However the current context is null some of the time.
We then tried to use the GRPC Context class like below:
LogMessageBuilder.setServiceName("some-service");
final String someHeaderWeWant = headers.get(HEADER_KEY);
final LoggerContext.Builder loggingContextBuilder = new LoggerContext.Builder()
.someFieldFromHeaders(someHeaderWeWant);
Context.current().withValue(LOGGING_CONTEXT_KEY, loggingContextBuilder.build()).attach()
Then accessing it in the service call like:
LoggingContext context = LOGGING_CONTEXT_KEY.get(Context.current())
However that is also sometimes null and if I print out the memory addresses it appears that early on the context is always the ROOT context regardless of me attaching in the interceptor, but after a few calls the contexts are correct and the logger data is there like it should.
So if anyone has any ideas or better ways to propagate data from an interceptor to the service call I would love to hear it.
Each callback can be called on a different thread, so the thread-local has to be set for each callback. It seems you may accidentally be getting Contexts intended for other RPCs.
grpc-java 0.12.0 should be released this week. Context has been partially integrated in 0.12.0, and we also added Contexts.interceptCall() which is exactly what you need: it attaches and detaches the context for each callback.
In 0.12.0, you should now see new contexts being created for each server call (instead of ROOT) and contexts propagated from client calls to StreamObserver callbacks.
As another note, unlike ThreadLocal Context is intended to be tightly scoped: after attach(), you should generally have a try-finally to detach().

passing response object from java to javafx.( Desktop application )

Im am planning on creating a desktop application with JavaFX. I would like to use JavaFX only for the UI, and all backend work should be done by java(with spring).Im not sure how to develop the frontend to call the service layer, and also receive the response and display the response on the next page.
Basically I need to know the following(just an example of want i want to accomplish).
1) to call the controller class I would do something like below in 'Login.fx'?
function btnLoginAction(): Void {
var loginController = LoginController {};
loginController.authenticateUser(txtboxUsername.text.trim(), pwdboxPassword.text.trim());
}
2) LoginController would be my java class and would call the service layer. after authentication, i would want to call another page('Welcome.fx') and pass the firstname of the logged-in user as a parameter. How do I accomplish this?
Im new to javafx(java gui development as a whole), hence let me know if there is a better approach to go about this, and some links to help me better understand.
NOTE: I am using javafx 1.3.
You can use java classes from javafx, e.g. the way you suggested is correct.
To achieve that you can just add a parameter to Welcome class and set it during creation/accessing with value received from LoginController instance.
P.S.: but I really suggest you to move to JavaFX 2.0. JavaFX 1.3 script language is not supported unfortunately, so no new functionality would be accessible.

dynamic proxy soap web service client in java?

Is there any way to use soap-rpc web services such that the client is generated via a shared interface? Restful web services do it this way, but what about soap based? Do you always have to use a tool like Axis or CXF to generate your stubs and proxies, or is there something out there that will set it up dynamically?
Thanks.
EDIT #1:
To clarify, I'm looking to do something like this:
Common interface:
#WebService
public interface MyWebService {
#WebMethod
String helloWorld();
}
This common interface can already be used to create the server side component. My question is: can this type of common interface be used on the client side to generate dynamic proxies? Restful web services do it this way (Restlets & CXF) and it seems the .Net world has this type of functionality too.
I would see this tutorial of JAX-WS useful for your purposes:
In the example code the Web Services Client is configured by adding an annotation #WebServiceRef with a property pointing to the WSDL location to the client implementation class and no tools are needed to access the stuff from the Web Service that is referenced.
Was this the way you would like to have it, or did this even answer to right question?
Not exactly sure what you're looking for, but if you don't want to rely on JAX-WS/JAXB-generated artifacts (service interfaces and binding objects), you can make use of the Service and Dispatch APIs. For example:
QName serviceName = new QName(...);
Service service = Service.create(serviceName);
QName portName = new QName(...);
String endpointAddress = "...";
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
SOAPMessage request = ...;
SOAPMessage response = dispatch.invoke(request);
Check Apache CXF. Configuring a Spring Client (Option 1).
When you want to call a webservice, you must have knowledge of methods implemented on it. For that, We need to make stubs OR we can read it from WSDL.
I have created a WS client, using AXIS2 libraries, which is without stubs. The thing is, for each diff. WS we need to create response handles.
You can call any WS method using SOAP envelops and handle the response.
//common interface for response handlers...
//implement this for diff. web service/methods
public interface WSRespHandler{
public Object getMeResp(Object respData);
}
//pass particular handler to client when you call some WS
public class WebServiceClient {
public Object getResp(WSRespHandler respHandler) {
...
return repHandler.getMeResp(xmlData);
}
}
Please check the link below, which shows the example interface for WS client.
http://javalibs.blogspot.com/2010/05/axis2-web-service-client-without.html
For every diff. WS method we can have diff. implementation for WSRespHandler interface, which will help parsing the response.
Not knowing java so well, but being forced to learn some to accomplish a task that I was given, I needed to consume a .Net service that I have already written, I had to do a little research.
I found that 99% of the examples/samples/problems with invoking a method call against a .Net service, or any service for that matter involved using J2EE (ServiceManager) or build classes and a proxy that reflect the service being invoked. Unfortunately for me, none of this would work. I was working "in a box". I could not add new classes, could not WSDL references, did not have J2EE, but DID have access to the standard java libs.
I am used to doing this sort of thing in pretty much every other language but java, but now there was no choice, and java it was.
A lot of digging and figuring out all new terminology, methods, classes, etc, I knew I was getting close, but was having issues with some small items to complete the task.
Then I came across this post: http://www.ibm.com/developerworks/xml/library/x-jaxmsoap/
As long as you have some sort of idea of what you need to send the soap service in term of the soap envelope, the above link will give you the information you need to be able to invoke a service without the classes, wsdl class generators and J2EE, apache or other dependencies.
In an hour from the time I read the mentioned article, I had a class working and about 10 minutes later, converted the code to the "in the box" solution.
Hope this helps
Apache Tuscany might help you, although it may be heavier than you want
http://tuscany.apache.org/

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