For the last couple of years I've had my head in Python, where there are numerous choices for simple, minimal frameworks that allow me to stand up a website or service easily (eg. web.py). I'm looking for something similar in Java.
What is the simplest, least-moving-parts way of standing up simple services using Java these days? I'm looking for something as simple as:
the ability to receive HTTP requests
the ability to dispatch those requests to handlers (preferably a regular expression based url to handler mapping facility)
the ability to set HTTP headers and generally fully control the request/response
Bonus points if the framework plays well with Jython.
[Update] Thanks for the responses, some of these look quite interesting. I'm not seeing the url dispatch capability in these, however. I'm looking for something similar to Django's url.py system, which looks like:
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
Where you specify a url regular expression along with the handler that handles it.
I liked to worth the Simple HTTP Server from the Simple Framework. It offers a nice Tutorial about how to start as well.
there are several alternatives:
servlets
restlet: lightweight REST framework
jax-rs: using jersey or the restlet module implementing the jax-rs specs
grizzly: NIO based server (with HTTP support + handlers)
apache mina: event-driven, async server (with HTTP support)
all these frameworks come with a built-in server.
EDIT
jax-rs has a similar approach using url templates:
#Path("/users/{username}")
public class UserResource {
#GET
#Produces("text/xml")
public String getUser(#PathParam("username") String userName) {
}
}
then put your handlers in an Application object:
public class MyApplicaton extends Application {
public Set<Class> getClasses() {
Set<Class> s = new HashSet<Class>();
s.add(UserResource.class);
return s;
}
}
another example with JAX-RS:
#GET
#Produces("application/json")
#Path("/network/{id: [0-9]+}/{nid}")
public User getUserByNID(#PathParam("id") int id, #PathParam("nid") String nid) {
}
EDIT 2
Restlet supports a centralized configurations like Django, in your Application object:
// Attach the handlers to the root router
router.attach("/users/{user}", account);
router.attach("/users/{user}/orders", orders);
router.attach("/users/{user}/orders/{order}", order);
Servlets might be the way to go. To do very simple things you only need to override one method of one class. More complicated stuff is of course possible, but you can go a long way with a little work.
Investigate Tomcat or Jetty - both are open source and well supported.
public class HelloWorldServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/plain" );
PrintWriter out = response.getWriter();
out.print( "hello world!" );
}
}
Note: This is more general discussion than answer.
I'm having similar issues coming from Python for 10+ years and diving, as it were, back into Java. I think one thing I'm learning is that the "simplicity" factor of Python is very different from that of Java. Where Python abounds with high-level framework-- things like web.py, Java seems much more lower level. Over the past few months, I've gone from saying "What's the Java way to do this easy in Python thing" to "How does one build up this thing in Java." Subtle, but seems to bring my thoughts around from a Python-centric view to a more Java-centric one.
Having done that, I've realized that standing up a website or service is not simple for a Java outsider, that's because there's a large amount of info I have to (re)grok. It's not as simple as python. You still need a webserver, you need to build a "container" to drop your Java code into, and then you need the Java code (am I wrong on this, everyone? Is there a simpler way?).
For me, working with Scala and Lift has helped- and not even those, but this one thread by David Pollack. This was what I needed to build a Jetty server. Take that, follow the directions (somewhat vague, but might be good enough for you) and then you have a servlet container ready to accept incoming traffic on a port (or 3 ports, in his case). Then you can write some Java code using HTTPServlet or something to go the rest of the way.
Again, this is just what I did to get past that barrier, but I'm still not a Java guru. Good luck.
I've hard about: Apache Mina
But quite frankly I don't even know if it is what you need.
:-/
:)
Jetty is a pretty nice embedded http server - even if it isn't possible to do the mapping like you describe, it should be pretty easy to implement what you are going for.
Related
Problem
Very short: I want to create Spring Shell, but as a web application.
I want to create a web-application (preferably using Spring Boot), where the frontend (ReactJS) looks like a terminal (or shell), and the backend processes inputted commands. Look at https://codepen.io/AndrewBarfield/pen/qEqWMq. I want to build a full web app for something that looks like that.
I want to build a framework, so that I can develop backend commands without knowing anything about the frontend/web application structure. I basically want to instantiate a "Terminal" object, where I give some kind of input-stream and output-stream. This way I can program this Terminal based on my given interfaces and structure, without the need of setting up all kind of front-end stuff.
A good summary of the question would be: how to send all keyboard inputs to the backend, and how to send all output to the frontend?
The reason I want to create a web application, is because I want it to be available online.
What I tried
I think the way of reaching this is using websockets. I have created a small web application using this (https://developer.okta.com/blog/2018/09/25/spring-webflux-websockets-react) tutorial, without the security part. The websocket part is almost suitable, I just cannot get an "input" and "output" stream-like object.
#Controller
public class WebSocketController {
private SimpMessagingTemplate simpMessagingTemplate;
#Autowired
public WebSocketController(SimpMessagingTemplate simpMessagingTemplate) {
this.simpMessagingTemplate = simpMessagingTemplate;
}
#MessageMapping("/queue")
#SendToUser("/topic/greetings")
public Greeting greeting(HelloMessage message, #Header(name = "simpSessionId") String sessionId) throws Exception {
System.out.println(sessionId);
// Do some command parsing or whatever.
String output = "You inputted:" + HtmlUtils.htmlEscape(message.getName());
return new Greeting(output);
}
private MessageHeaders createHeaders(String sessionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
return headerAccessor.getMessageHeaders();
}
Now with this code, you can parse a command. However, it doesn't keep any "state". I don't know how it works with states and websockets.
I saw you had this Spring Sessions + WebSockets (https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-websocket.html), but this is not really what I want.
I can send a message from the backend to the frontend by using this code:
simpMessagingTemplate.convertAndSendToUser(sessionId, "/topic/greetings", "hey", createHeaders(sessionId));
However, I want my terminal to be able to wait for input commands from the user. Seems like a stretch, but does anybody know how to achieve this?
What I sort of want
I basically want other people to program to this interface:
public interface ITerminal {
void setInputStream(Object someKindOfWrapperForTheInput);
void setOutputStream(Object someWrapperOfSimpMessagingTemplate);
void start();
}
When somebody opens the web application, they get a dedicated terminal object (so a single connection per user). Whever somebody enters a command in the frontend application, I want it to be received by the terminal object, processed, and response outputted to the frontend.
Reasons for doing this
I really like creating command-line applications, and I don't like building frontend stuff. I work as a software engineer for a company where we build a web application, where I mostly program backend stuff. All the frontend part is done by other people (lucky for me!). However, I like doing some projects at home, and this seemed cool.
If you have any thoughts or ideas on how to approach this, just give an answer! I am interested in the solution, using the SpringBoot framework is not a requirement. I ask this question using Spring Boot and ReactJS, because I have already built applications with that. A lot has been figured out already, and I think this probably exists as well.
The only requirement is that I can achieve this with Java on a tomcat-server. The rest is optional :)
Unclear?
I tried my best to make my story clear, but I am not sure if my purpose of what I want to achieve is clear. However, I don't know how to formulate it in such a way you understand. If you have any suggestions or questions, dont hesitate to comment!
If the only thing you want is a Live Spring shell that shows up in the browser it's fairly simple, all you need is to expose a standard WebSocket via the WebSocketConfigurer, then add a WebSocketHandler that executes the command and then returns the resulting String as a TextMessage.
Firstly the Socket configuration that allows clients to connect to the 'cli' endpoint
#Configuration
#EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {
#Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(cliHandler(), "/cli").setAllowedOrigins("*");
}
#Bean
public CLIWebSocketHandler cliHandler() {
return new CLIWebSocketHandler();
}
}
Then the WebSocketHandler that executes the command. I recommend that for every #ShellMethod you specify the return type as String, don't use logging or System writes as they won't be returned during the evaluation.
#Component
public class CLIWebSocketHandler extends TextWebSocketHandler {
#Autowired
private Shell shell;
#Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String result = shell.evaluate(() -> message.getPayload()).toString();
session.sendMessage(new TextMessage(result));
}
}
You can use an extension like Simple WebSocket Client to test it, by going to ws://localhost:port/cli
This is the most basic solution, adding features like security should be easy after this. Notice that I don't use STOMP, because you probably want to isolate users. But it can work alongside STOMP based endpoints, so you can have pub-sub functionality for other parts of the project.
From the question I sense that answer you'd like is something that involved Input and OutputStreams. You could possibly look into redirecting the output of Spring Shell to a different stream then have them forwarded to the sessions but it's probably much more complicated and has other trade-offs. It's simpler to just return a String as the result, it looks better in print outs anyway.
I know there are a lot of answers on this questions , but i am still confused about difference between JAX-RS API(the specification), and Jersey framework( reference implementation).
I read that:
Jersey framework basically uses com.sun.jersey.spi.container.servlet.ServletContainer servlet to intercept all the incoming requests. As we configure in our projects web.xml, that all the incoming rest request should be handled by that servlet. There is an init-param that is configured with the jersey servlet to find your REST service classes. REST service classes are not Servlet and they need NOT to extend the HttpServlet as you did in your code. These REST service classes are simple POJOs annotated to tell the jersey framework about different properties such as path, consumes, produces etc. When you return from your service method, jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream
My question is when you say :" jersey takes care of marshalling those objects in the defined 'PRODUCES' responseType and write it on the client stream", what you mean by jersey , what is actual class or library that handles objects .
I am confused when i read that jersey is the engine that handles JAX-RS API specification. Can someone please explain what exactly is behind word jersey in this sentence? What actual class from Jersey do do the job of processing requests and responses in Jersey?
The concept of specification and implementation is really pretty basic software engineering concepts. Your specification is the high level design. To help understand, I just came up with a really simple example.
Say I want to have a parsing library. I know how I want to be able to use it. The only problem is that I am not very good at writing parsing code. So I create a high level specification, and I outsource the implementation. Here are the three classes that are part of the spec. They are all contained in one "API jar", say myparsers-api.jar
public interface Parser {
String[] parse(String s);
}
public interface ParserFactory {
Parser getBySpaceParser();
Parser getByCommaParser();
}
public class ParserDepot {
private static ServiceLoader<ParserFactory> loader
= ServiceLoader.load(ParserFactory.class);
public static ParserFactory getDefaultParserFactory() {
final List<ParserFactory> factories = new ArrayList<>();
loader.forEach(factories::add);
if (factories.isEmpty()) {
throw new IllegalStateException("No ParserFactory found");
}
return factories.get(0);
}
}
So at this point, I can actually code against this jar. If I were to uses it as is right now in another project, the project would compile just fine.
ParserFactory factory = ParserDepot.getDefaultParserFactory();
Parser parser = factory.getBySpaceParser();
String[] tokens = parser.parse("Hello World");
System.out.println(Arrays.toString(tokens));
So even though there is no implementation of this specification, I can still code against it, and compile against it. But when I try to actually run the program, it won't work, as there is no implementation. You can try to run this code, and you will get an IllegalStateException (see the docs for ServiceLoader if you're unfamiliar with this pattern).
So I outsource the implementation to say a company called Stack Overflow. They get my myparsers-api.jar and they need to give me back an implementation. They would need to implement a ParserFactory, and a couple of Parsers. They might look something like this
public class SoByCommaParser implements Parser {
#Override
public String[] parse(String s) {
return s.split("\\s+,\\s+");
}
}
public class SoBySpaceParser implements Parser {
#Override
public String[] parse(String s) {
return s.split("\\s+");
}
}
public class SoParserFactory implements ParserFactory {
#Override
public Parser getBySpaceParser() {
return new SoBySpaceParser();
}
#Override
public Parser getByCommaParser() {
return new SoByCommaParser();
}
}
Now Stack Overflow gives me back a jar (say so-myparsers-impl.jar) with these three classes and the required META-INF/services file (per the ServiceLoader pattern), and now when I add the so-myparsers-impl.jar to my project and try to run it again, the program now works, because now it has an implementation.
This is exactly how the JAX-RS spec works. It only defines the high level design of how it should work. The classes, interfaces, and annotations that are part of that design are placed in an "API jar" just like my high level parsers are put into a jar. Implementations cannot alter these classes. All the classes that are part of the JAX-RS specification (version 2.x) are put into one single jar javax.ws.rs-api. You can code against that jar, and your code will compile just fine. But there is nothing to make it "work".
You check out both the written specification and the classes defined by the specification and you will notice that the only classes included in the source code are those mentioned in the specification. But what you should notice is that the written specification doesn't mention anything at all about how it is supposed to be implementation. Take for example the following code
#Path("/test")
public class TestResource {
#GET
public String get() {
return "Testing";
}
}
#ApplicationPath("/api")
public class MyApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.add(TestResource.class);
return classes;
}
}
Now the specification states that this is all we need to run a JAX-RS application in a servlet container. And that's all it says. It says nothing about how it all supposed to work. This is just how it is designed to work.
So what, is there some magic voodoo in Java that we don't know about that will make this Application class start a server, and some hocus pocus that will make a #Path annotated class automatically accept requests. No. Some body needs to provide the engine. The engine might be 20,000 lines of code just to make the above code work as specified.
That being said, Jersey is just the name of an implementation. It's like when I outsourced my parser implementation to Stack Overflow; The name Jersey itself is just the name of the project, just like Hadoop is a name of the project. In this case, what the project is, is an implementation of the JAX-RS specification. And because JAX-RS is just a specification, it means that anyone can implement it. If you wanted to, you could write your own implementation. As long as it works how it is defined to work in the written specification, then you can say that your code is an implementation of JAX-RS. There's more than just Jersey out there; you also have RESTEasy, which is another implementation.
As far as how Jersey implements the engine, that is way too broad. What I can do, is give you a high level overview of what happens behinds the scenes.
A JAX-RS application is defined to run inside of a servlet container. If you understand servlet containers and the servlet spec, then you'll know that the only way to handle requests is either by writing a HttpServlet or Filter. So if you want to implement JAX-RS then you need to able to handle requests either through a HttpServlet or a Filter. The ServletContainer you mentioned, is actually both. So for Jersey, this is the "entry point" into the Jersey application, as far as request processing is concerned. It can be configured in a number of ways (I've leave that research to you).
And if you understand how to write your own servlet, then you know all you get is an HttpServletRequest and HttpServletResponse. You need to figure out what to do from there; get request info from the request, and send response info back out in the response. Jersey handles all of this.
If you really want to get into the gory details of what is going on under the hood, you will just need to to dig into the source code, starting from the entry point, the ServletContainer. Be prepared to spend months on this to get a really good understanding of how it all works. It's not something that can be explained in one Stack Overflow post, if that's what you're expecting.
You already pointed that JAX-RS is a specification and Jersey is the implementation which is how is Java especially Java EE work, maybe this article can explain more better.
To summarize JAX-RS is just a specification, there is no real implementation. The real implementation was done by Jersey and other library that following JAX-RS specification.
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/
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.
I'm writing a very simple web framework using Java servlets for learning purposes. I've done this before in PHP, and it worked by consulting the request URI, then instantiating the appropriate class and method.
This worked fine in PHP, as one can do something like $c = new $x; $x->$y;. I'm unsure however of how to translate this to Java, or even if this is an appropriate way to go about it.
So far, I've tried:
Router router = new Router(request.getPathInfo());
String className = router.route(); //returns com.example.controller.Foo
Class c = Class.forName(className);
Object x = c.newInstance();
Foo y = (Foo) x;
y.doSomething();
This seems fine for a couple of routes, but doesn't seem like it would scale well, nor would it allow for sourcing routes from a configuration file.
How should I make it work?
Get hold of actions in a Map<String, Action> where the String key represents less or more a combination of request method and request pathinfo. I've posted similar answer before here: Java Front Controller
You can fill such a map either statically (hardcoding all actions) or dynamically (convention over configuration, looking up classes in a certain package, or scanning the entire classpath for classes with a certain annotation or implementing a certain interface).
And just stick to Servlet. The Filter isn't there for. At highest use it to forward the request to the controller Servlet. In the Servlet, just implement HttpServlet#service().
I would use a Servlet Filter as Front Controller. The router would connect paths with request dispatchers. In the doFilter method you would convert ServletRequest to HttpServletRequest, extract the request path and match it against the registered mappings. The result of this mapping is a request dispatcher you would dispatch the request with.
In pseudo code:
doFilter(ServletRequest request, ServletResponse response) {
httpServletRequest = (HttpServletRequest) request;
path = httpServletRequest.getRequestURI();
dispatcher = router.getTarget(path);
dispatcher.dispatch(request, response);
}
Depending on your need the default routing mechanism of the Servlet API could be sufficient.
Not quite sure what you're after but you might want to take a look at Java servlets. Granted many web frameworks are abstracted above plain servlets, but it's a jolly good place to start learning about Java web apps if you ask me (which indirectly you did ;) )
Download the Java servlet specification here: Java Servlet Spec - it's quite interesting.
How should you make it work? However you want it to. If you're just doing it for learning purposes, whatever you do will be fine.
I would suggest having all your actions implement the same interface though (maybe extend Servlet) so that you don't have to compile in all different classes.
Then you can essentially do what you're doing, except that your cast to Foo becomes a cast to Servlet and then you don't have to have a special case for all your different classes.
You can then also load up the routes from configuration (maybe an XML file).
Essentially what you're doing is implemented by the Struts 1 framework so it might be worthwhile reading up on that (it's open-source so you can also look at the source if you want).