The Modern Java Ecosystem (for the Sinatra or web.py lover)
arantaday.com
arantaday.com
Jersey is an implementation of JAX-RS. It has 3 major pieces: jersey-core, jersey-client, jersey-server. (The name should be obvious what they are for).
If you're writing JAX-RS services, you can return a few different formats: XML, JSON, ATOM. All you need to do is to annotate the method with the following annotation:
// will return XML or JSON depending on the request from the client.
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
This is a big win if you need to support both. - Object to XML conversion is done by JAXB.
- Object to JSON conversion is done by Jackson via JAXB.
Jersey is part of JavaEE 6 standard (part of your Application Server if it supports it).What's lacking from JavaEE 6 is an MVC framework which is targeted for JavaEE 7.
Another key feature is JAX-WS (the plain old SOAP WebService). The nice thing about JavaEE 6 is that the minimum differences in the programming style between JAX-RS and JAX-WS.
JAX-RS operates according to resources (e.g.: give me all students, give me student with id=1, delete student with id=1, etc). So some of the examples would be:
// Rough pseudo-code, omitting a few JAX-RS annotation
public class StudentResource{
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public <List> all(){}
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Student get(long id){}
}
JAX-WS operates according to services (e.g.: initiateInvoiceWorkflow, performPayment, etc). public interface AccountingService{
@WebMethod(operationName="initiateInvoiceWorkflow" ...)
Invoice initiateInvoiceWorkFlow();
}
// have your implementation...
So in theory, you can have something that's called StudentRepository where you can use that repository with both JAX-RS (REST) and JAX-WS (WebService) implementation easily (I've done this and it's quite straightforward) if your "Enterprise client" forces you to do so.The important bit here is testing. You can easily test both JAX-RS and JAX-WS implementation in both unit-test or integration-test. You can easily do unit-test because you don't need to deploy them to the server: they're just normal Java classes. You can do integration test by deploying them to the server and generates the client implementation (in which I'll cover next).
The client-side implementation of JAX-RS is also similar to that of JAX-WS programming style.
In JAX-WS, you grab a WSDL, throw it to a generator tool that comes with JDK to generate the model (Invoice, Student, etc) and the proxy client-side to call the server-side. Very very straightforward, 5 minute job.
In JAX-RS, you'd use jersey-client to perform HTTP call as follow:
// url => is a string that points to JAX-RS end-point e.g.: student/1
// header => json? xml? atom?
// type => (typeof Student) (well... it's Java).
Student student = Client.create().resource(url).accept(header).get(type);
Keep in mind that in the client-side, your Student class must have roughly the same structure and must be annotated using JAXB XML annotation (the client-side also relies on JAXB -> Jackson -> Java object conversion for the case of JSON, or just JAXB -> JAva object for the case of XML).So no hacking using XPath or something like that (I work in Ruby once in a while and when I read some of the 3rd-party libraries/gems that implement client-side API against popular service provider, most of the implementations do brute force using XPath querying node element and stuff).
PS: Excuse me for the poor formatting, where can I learn to format my comment?
UPDATE: fix the format.
Oh and one more thing: JAX-RS (Jersey) is just an implementation on top of Servlet. So all of your previous knowledge regarding to Servlet (Context, deployment, URL, Filter) will be definitely useful.
But you're absolutely right on most of these points.
All the formatting tricks are here: http://news.ycombinator.com/formatdoc
I can only give you pointers to JavaEE 6 books (overall).
Beginning GF3 is an OK introduction to JavaEE 6: http://www.amazon.com/Beginning-GlassFish-Experts-Voice-Tech...
Oracle Tutorial (formerly SUN tutorial) for JavaEE 6 is another OK one (reviews were meh, but you've got limited choice so...) http://docs.oracle.com/javaee/6/tutorial/doc/
I saw Amazon has the print edition and another one to be in stock by mid 2012 (Advanced Java EE 6...)
Here's another book covering Java EE6 (intro):
http://www.amazon.com/Java-EE-GlassFish-Application-Server/d...
Seems to cover Servlet more than Apress book (first book).
You probably would need to know JPA 2.0 (ORM) as well.
And some more "best practices/real world-ish" tutorials:
http://www.amazon.com/World-Night-Hacks-Dissecting-Business/...
Good luck.
http://www.amazon.com/Pro-JPA-Mastering-Persistence-Technolo...
If JavaEE can reduce JPA2/Model boiler plate code, then it'll be much improved.
Here's an example of a simple Websocket chat server: https://gist.github.com/1421652
Disclaimer: It's an open source project that I have some commits to
Is that like a 'full disclosure' notice or are we supposed to be terrified of your code?
MyType myVar = gson.fromJson(jsonString);
JPA on a back, some basic IoC in the middle (nothing fancy). Mockito and jUnit for tests.
All in all it's just a bunch of small layered classes with some bits of annotations and no xml. Well, one web.xml file with single servlet declaration for JAX-RS :)
With good IDE (they all are great this days), Maven for dependencies, well-known practices and modern APIs Java isn't that scary or cumbersome anymore. It's just a nice small language. A bit verbose without closures and type inference but still Ok.
I should note, though, that we generally use our Java layer as a service provider. We keep main bits of logic on a client side in JavaScript and call Java either for transactions and data, or in cases when something is hard to do on a client. It's just easier that way.
That alone creates a bit of mismatch because JAXB (which is used by JAX-RS) uses getter/setter by default unless you specified it otherwise.
And sometime you do have some logic in your getter/setter for validation or other purposes.
I got bitten by this before while it seems like a small thing it's actually a bit problematic.
If you're using JPA2, take a look at Spring-Data (formerly Hades). Spring-Data helps you to reduce JPA boilerplate code.
The way Spring-Data works is by using a convention: specify your NamedQuery and a Java interface with method name == NamedQuery name. Then magic suddenly happens.
This has been resolved, but it left a bad taste in my mouth because there isn't a good solution other than waiting for them to fix it.
You say you aren't a big fan of 'heavy use of annotations' but you don't qualify what 'heavy' is so I am guessing that it is pretty much all annotations.
How do you make your determination of what annotations are 'ok' and what annotations aren't? Or do you say something like 'oh, I won't use that annotation because it might blow up on me at some later date'? What is your mental process there? Is @GET good or is @POST bad? What about @Inject or @JsonProperty?
The 'annotations leave a bad taste in my mouth' statement seems kind of odd to me. Generally, a language feature isn't something that I'm careful about avoiding. I could see making a statement like "I tried to use software product XYZ and it was so full of bugs that I switched to software product ABC."
But annotations aren't a software product, they are a language feature that products can take advantage of. It just happens to be that two products you were using had conflicting annotations. No big deal, you still have choices as you can just swap out products. That in itself doesn't make the functionality that annotations provide taste bad.
I've met people who have had this view of annotations as being some magical creature. They didn't understand them or how they worked at all. They stuck it in their heads that 'annotations are bad', so we aren't going to use them and aren't going to even bother learning how they might help us. Everything was very black and white. I found this behavior really odd because everything in software development is grey.
The problem is that guice is using these annotations to wire things together, but so was jax-rs. It's been over a year so I don't remember the exact problem I was having, but the short version is that annotations don't compose well and when two different frameworks require you to place annotations on the same class/method, and then they conflict with one another, it because very hard to fix.
This aligns with my feelings: http://www.nofluffjuststuff.com/blog/brian_gilstrap/2010/02/...
However, I don't know why the author would even suggest that annotations are innocent looking. They aren't any more 'innocent' than an if statement. Something like: 'if (myMethod())' could easily be a long running database query or call out to a fibonacci solver. Should we all be afraid of using if statements too?
I'm sorry, but there is really nothing 'magical' about annotations. It is simply a marker on a class, property or method that other code can read from and do things with. Prior to annotations, apps were processing Javadoc (@see early versions of GWT), which was an even more terrible idea since you didn't know if it was Javadoc or an annotation.
The summary is that a) software engineering is not easy and it does involve knowing what you are doing in order for things to not appear 'magical'. b) If you are going to put an annotation on something, then you should know what code is going to read that annotation and what effects it might have. That said, that isn't the fault of the annotation language feature.
Your response seems to be that one needs to understand the complex interactions of annotations before using them, therefore annotations are fine.
That's a non sequitur.
That is the magic. You escape your default programming paradigm of sequential statements and start doing metaprogramming.
The reason there are annotations is that the java language wasn't capable of doing certain things without annotations. Some of us think that java shouldn't do these things.
It'd be silly to not dislike these features just because somebody thought that they would be a good idea, without being fully prescient about how the feature would be used in the wild.
Certainly, there are language features that I don't use, because I don't need them in what I do, but that is different than purposely avoiding something.
- Everyone should avoid global static initialization of complex data, even though it's the most convenient way to achieve certain effects. The chances of screwing up something with the initialization order of variables are just too high, and impossible to control. - There are people who like C++ template metaprogramming. Some very cool things can be achieved with it. But all C++ projects that I've seen ban it. Some because they want new people to be able to easily pick up the project. Others just because of the tool issues around heavy duty template use, like slow compilation speed and horrible error messages. - C++ has many different kinds of inheritance. In practice many projects will ban most of them, and only allow single public inheritance of bases classes with implementation, and single or multiple public inheritance of base classes with only virtual methods. The convenience of multiple implementation inheritance is just not viewed as sufficient to balance the risk of shooting yourself in the foot. And the utility of non-public inheritance is not viewed as high enough to balance needing to explain it to people coming from Java.
Or how about Perl?
- Anybody suggesting changing $[, the variable that controls the array indexing base, would generally be given a good thrashing. Allowing changing the language (at runtime!) from 0-based indexing to 1-based was presumably thought to be a benign feature at some point, but it's hard to see how in retrospect. - As a more modern example, later Perl got the ability to embed executable Perl code inside regular expressions with (??{}). Again, it's totally possible to see uses for this. But in practice it's so inscrutable (and at least in the past so crashy), that it's best reserved for stunt coding. Maybe not using it means rewriting some extremely compact regular expression in a way that's 3x longer, but that's still a net win.
Does that help showing the flavor of things you'd want to avoid?
For distributed clustering, Hazelcast is amazingly good.
For massively scalable network services, Netty does a fantastic job.
That said, using a backtick character like that seems like a really error prone approach. Definitely not my cup of tea.
It's rarely used in any other context (besides Lisp). It's really unobtrude, making the rest of the code standing out. It's at an easy to remember place at the keyboard. The parser is good enough to catch any quote or backquote mistakes. It's really an non-issue and you forget about it after a while.
A sample,
<ul>
` for (a : list)
<li>$a
`
</ul>-Templating. Something like SimpleTemplate Engine in Bottlepy. http://bottlepy.org/docs/dev/stpl.html
-How do I get rid of Tomcat at least for development. I would like to run java -jar MyApp.jar -Dport=8080 and get a live running webapp in my dev environment.
Here's examples of both:
http://www.benmccann.com/dev-blog/embedded-jetty/
http://www.benmccann.com/dev-blog/embedded-tomcat/
I put together an example and uploaded it to GitHub. I'd love feedback on it:
https://github.com/benmccann/sprightly
P.S. Closure templates are cool because they can be used both client-side and server-side. I'm not aware of other templating languages that have this feature. I haven't used it much yet, but want to experiment with it more when I get time.
Jetty everything. You can even keep it for production.
I tend to use 'mvn tomcat:run' to run my dev server, which I find even easier, fwiw.
http://freemarker.sourceforge.net/
It's pretty simple and straigtforward, its what I use instead of JSP.
Also, if you're doing web stuff, I HIGHLY recommend sitemesh.
It's a really clean way of implementing layouts and everytime I use other languages like Python, I always try and find equivalents but am always disappointed.
The documentation is a bit thin, but the code is rock solid and very fast.
Combined with JEXL for an expression language, this is one of the best server side engines I've ever used.
No, it's not.
URL mapping is a framework detail, not a language detail — although the framework can be limited by the language. In Sinatra you'd write:
get 'someroute' do
# do stuff
end
http://www.sinatrarb.com/intro.html#Routeseach style (these and half a dozen others) has its advantages and inconvenients. For instance, separate urls mapping (Rails, Django) give a starting point laying out the structure of the site and make views/controllers easier to reuse (as they're not coupled to URLs)[0], whereas annotating the handler directly gives a better view of where they're involved and how.
[0] They also make it simpler to "graft" sub-sites in
I don't mind both styles (after working with Spring MVC 3, Servlet 3, JAX-RS, and Rails)
@GET
public Collection<Integer> listStudentIds() {
return STUDENTS.keySet();
}
or @DELETE
@Path("{uid: [0-9]+}")
public boolean deleteStudent(@PathParam("uid") int uid) {
final Student deletedStudent = STUDENTS.remove(uid);
if (deletedStudent == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} else {
return true;
}
}
I'll grant that Java programs often become more verbose than their Python/Ruby counterparts - but I would argue that trait can be held to a minimum with the proper libraries and coding style. list_student_ids = get(STUDENTS.keys) # [0]
second example, Python: @delete
@path(r'{uid: [0-9]+}')
def delete_student(uid):
if STUDENTS.pop(uid, None): # [0]
return True
raise WebApplicationException(Response.Status.NOT_FOUND)
the last line generally wouldn't be this complex, in Flask you'd just call `flask.abort(404)` (which can be used inline with an `or`, as with waffle_ss's ruby example, but that's not usual/good Python style), in Django it'd be `raise Http404()`.Although in Django you'd really use the `get_object_or_404` shortcut for ORM objects:
def delete_student(uid):
get_object_or_404(StudentModel, pk=uid).delete()
return True
And you wouldn't bother with the return since a 200 result would mean the deletion was correctly executed.[0] Used Python's MutableMapping API here, it works slightly differently than Java's equivalent Map interface: `.keys()` returns a sequence of the mapping's keys and `.pop()` asks for a default value to return in case nothing was found there, otherwise it raises `KeyError` if the key was not found)
r'(?P<uid>[0-9]+)'
(the `r` prefix is for `r`awstring, so the developer does not have to string-escape each backslash used in the regex among other things) def delete_student(uid)
STUDENTS.remove(uid) || raise WebApplicationException.new(Response.Status.NOT_FOUND)
end public void deleteStudent(int uid) {
if (STUDENTS.remove(uid) == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
}And that is the reason I still write in Python or Lisp when I don't need something (Hadoop, Lucene, etc) from the JVM ;-)
def delete_student(uid)
STUDENTS.remove(uid) or raise WebApplicationException, Response.Status.NOT_FOUND
endPersonally I'd rather have a distinct boolean value to test for, the java version is much more explicit as to exactly what its doing.
!!STUDENTS.remove(uid) get "/list_student_ids" do
STUDENTS.key_set
end
delete "/delete_student/:uid" do
STUDENTS.remove(params[:uid]) or raise WebApplicationException, Response::Status::NOT_FOUND
true
end
1. http://www.sinatrarb.com/2. There's also a gain from the framework being able to map things to each other without being told explicitly. `@PathParam("uid")` for instance, it's only there because the framework has no way to match the parameter name `uid` to the URL-extracted parameter `uid`. Likewise with HTTP methods being part of the routing instead of a separate annotation, in part.
3. Java's APIs and type system, such as implicit nulls and not being able to use arbitrary types in boolean contexts
Some savings through the removal of types, sure, but that is not what I personally see as most import here.
I find it amazing that "DRY" has become such a positive pattern when it was touted as one of the driving points of the Ruby on Rails framework. Don't repeat yourself.
For instance, Java folks are always ready to throw exceptions instead of letting stuff resolve itself if it doesn't quite work.
If I returned a fake value - the client would get a 200 response on his attempt to delete a non-existent resource, which is clearly the incorrect behavior. I could return nothing - but then the client would see a 204. So, I choose to throw an exception with a response 'NOT_FOUND'
throw new WebApplicationException(Response.Status.NOT_FOUND);
so that the client gets a 404 response.There are a few things I'd like to point out to add to this example:
1) JAX-RS is still new. In the future, they might improve the exception handling or whatnot (so if you return null, they might decided to return 404 ... who knows)
2) We can always wrap all JAX-RS with a Filter. So you can throw JPA level exception (not found) and let the filter catch it and convert it to WebApplicationException(404). Thus in theory, your JAX-RS implementation won't have any RuntimeException explicitly in the code.
@DELETE
@Path("{uid: [0-9]+}")
public Response deleteStudent(@PathParam("uid") int uid) {
final Student deletedStudent = STUDENTS.remove(uid);
if (deletedStudent == null) {
return Response.status(Response.Status.NOT_FOUND).build();
} else {
return Response.ok().entity(true).build();
}
}The full (buildable) source code - including the CsvParam and DateParam classes - are here: https://github.com/smanek/students
http://iam.guillaume.bort.fr/post/558830013/why-there-is-no-...