An Opinionated Guide to Modern Java, Part 3: Web Development
blog.paralleluniverse.co
blog.paralleluniverse.co
Java devs-- you seriously owe it to yourself to spend the time investigating and ramping up onto Scala and Play. This is where the future of Java web app development is being driven from, by Typesafe and the Play / Spray /Akka open source developers. You do yourself a great disservice by sticking with Spring, Hibernate, JBoss, and the old standbys.
Please enough of that, especially coming from the Scala community. Let's act as professionals and judge tools on their merits instead of instigating flame wars.
Second, I'm doing both (web Java at work, web Scala on my spare time) and in my experience, there is really no clear winner. What's especially interesting is that I can find about the same number of positive things to say about the Scala tool stack (Scala/Typesafe platform/Akka/Play) as I can say negative things about each of them. Every time I'm happy about something in the Scala world, I find something I'm not happy with that counter balances it (tooling, slowness of template recompilation, unprovedness of the actor model, Play's arguable step backward in the v2 compared to v1, etc...).
Java is impossibly verbose and has a very limited type system compared to Scala but man... do I develop things quickly with it. There is close to zero friction to get from nothing to something workable, maintainable and fast. And the tooling is top notch, the environment and compilers are super stable, and Java 8 is numbing a lot of the pain I used to feel. In contrast, I feel that I'm often fighting against the Scala compiler whenever I write Scala code. It feels nice in the end to see how concise and neat the code looks compared to Java, but I'm never really convinced the pain was worth it.
So, back to your original point: I've tried (and continue to experiment with) all these "new" technologies that Scala is claiming to bring to the table, and so far, I'm unconvinced that they are a clear improvement over what we currently use in the Java world.
And given that Scala continues to be a marginal language on the JVM, I don't think I'm the only one doubting that Scala represents the future.
The real benefits of Play and Akka become apparent when a third-party service you send API calls to starts acting flaky. Or when your web service that you offer to clients is suddenly being hit by an iPhone game that just got purchased by a million people. Or when that nasty little bug that winds up throwing an exception from time to time rears its head all of a sudden. Play and Akka give you a resilience that is very hard to come by in the Java world.
Typesafe's home page has, in giant type, "Applications are becoming Reactive" and they are absolutely spot f'ing on. Writing blocking code, waiting on threads, assuming you're running on one JVM, these things are great and all, and very easy to do because all of those templates are built into IntelliJ and you just have to click a few buttons to get all that, but wow, the performance difference once you get into the Play world is just frighteningly good.
Of course there are Java developers who can kick ass with Spring, Hibernate, Servlet containers, and war deployments, but all of these tools are huge, bloated, and starting to show their age. Modern frameworks like Play make things simpler for those of us who don't have +7 year JEE experience with Spring and Hibernate.
There, fixed that for ya.
I agree with the Java vs Scala poster. And unlike him, I have a 30,000 line scala production project under my belt. Everything he says is true, and then some. Ever split up a file into chunks because intellij can't edit it effectively?
Yeah, didn't think so. (Just telling like it is)
I have a 20k line Scala project in production and editing it has certainly never been an issue. Why does Intellij have problems with large files?
I'm sure the Jetbrains folks have fixed that right up, but at the time, breaking it into 500 line chunks was required, due to the exponential nature of the slowdown we accomplished.
The basic reality is Scala compiles are slow. Syntax and red-line highlighting isn't cheap, and no amount of brilliant russian IDE developers can totally fix everything.
scalac certainly isn't fast but I just clean compiled our 20k line project in 75 seconds.
I'm not claiming that's great or anything, I just don't find it to be a showstopper.
Heh, that's brilliant, read the SBT compilation guide, 1 source file per class (obviously that's not set in stone, but a good guideline to follow).
Also, SBT is boss. Enabling automatic build in one's IDE is asking for pain. Why, why is the IDE blocking when I save the file? That's why.
> The basic reality is Scala compiles are slow
For deployment sure, but not a show stopper either (20K LOC in around a minute on warm JVM).
For incremental builds Scala is not even remotely slow, particularly if you follow best practices and break your application up into modules (sub projects in sbt world).
Anyway, things have changed (a lot) since 2011, we're not in the stone ages anymore -- if you want that, go check out Haskell where you'll get no tooling, no stack traces, and eternal compile times ;-) With a superior type system, brilliant community, yada, yada if that's your thing.
Interestingly, the biggest thing I wish I had when writing Java is algebraic data types and pattern matching. A few years ago I would have said it was lambda, but having sum types would make expressing many things so much easier.
We rewrote these applications using JAX-RS (RESTEasy) and they were much simpler, easier to maintain, without API breakage in new framework versions. It just a bunch of methods with annotations. XML and JSON serialization is automatic (via JAXB and Jackson). And you can use the same lightweight ORM as Play (Ebean), since it's an external project.
Well-thought out, mature technology is often better for getting work done than the hype of the day.
Play 1 was almost perfect. Really hope someone would fork Play 1 and continue with it.
This is, imho, what makes Play so fantastic. That you can have def index = Action { hardComputation() } for blocking code, and change it to def index = Action.async { Future { hardComputation() } } and you have magically changed your application to be asynchronous through the request-as-actor paradigm of Play. Play makes it easy to write async code. Play makes it way easier to control configuration for things like thread pools, dispatchers, and the like vs. Jetty. The performance of the nonblocking async code is incredible, and winds up saving a ton of money and developer time.
Async is only beneficial in terms of IO.
http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Comput...
If you have a method that relies upon a DNS query, and your DNS server starts to respond to requests very slowly, your blocking application will run out of threads very quickly, and you'll be spending time poring over thread dumps trying desperately to see why all of your threads are waiting when the load average on your app server is basically zero. Your monitors will be going off like crazy because it appears that your application is flapping, sometimes able to handle a request and sometimes not. You will be tearing your hair out (and Java devs have all done this, though maybe not because of DNS).
If you have a non-blocking application, you will get an alarm that one of your pages may be acting a little slower than normal (even though the rest of your app is running normally). You'll look into the controller source, see that it's performing a DNS query, and poof, your debugging is done and you're off to restart bind.
If you have a sufficiently slow DNS you will chew through all the memory available to your non-blocking application in an amount of time that isn't functionally different from how long it will take you to exhaust your threadpool.
The whole point of the lightweight thread approach with shrinking stacks is that you will use the same amount of memory for both and they will fail at roughly the same point.
You are talking about a problem domain where concurrency is what you are scaling and where the things that would block are orders of magnitude slower than processor time.
If you were working in a problem domain where latency is what you are scaling and the blocking calls are on the same order as processor time, non-blocking approaches can be best as the blocking mechanism can still carry overhead even with light weight threads.
Maximizing throughput is another beast entirely as well.
Given the amount of money you get with them, doing consulting in Germany, I think they will stay around for quite a while.
Also, Spring is not that bad, though sometimes I have hard time to understand some of the initialization/runtime problems. Hibernate and JBoss I rather skip, and use Tomcat and Dalesbred for relational data access.
I think Play / Spray and Akka are great but let's differentiate between the language and the framework.
You can write Play / Akka with Java (they added Java 8 support recently) and you can write Spring / Java EE with Scala (I do that all the time and it's working great)
More than that, I have mixed Java / Scala projects and it works like a charm (once you configure maven / gradle correctly that is)
The "new" Spring versions are nothing like it used to be. Also the new Java EE ones. no XML configuration files, all convention over configuration. And I sometimes prefer a @GET + @Path or @RequestMapping annotation over concatenating routes with ~ like they have in Spray.
It's just a matter of preference and personal taste, but let's separate the language discussion with the framework / ecosystem discussion, they are not the same.
It'd be nice if we could also write Gradle with Scala, or some other decent JVM language.
Those technologies have stayed on, while other trends have come and and go.
I put my money on TypeSafe.
Pivotal still (05/2014) doesn't have Java8 support for some of it's frameworks (grails https://jira.grails.org/browse/GRAILS-11063 ). TypeSafe pre-released versions of Play that take full advantage of Java8 features.
Given that if you need to run a Java 1.4.2 app on top of JBoss (or Glassfish!) then the types of technologies that these two companies are pushing are solving problems in a different domain.
And arguably the PermGen change in Java8 would benefit Grails/Groovy the most.
While I agree with you about the others 'json manipulation' is not an area that Play can even be compared to Jersey (Jackson). Jersey transparently converts the request body to the required input type whereas with Play you still have to un-marshal the body while taking care of errors (admiddently that can be 'hidden' away using Action composition but still is work that the developer has to worry about). With Jersey its magic that just works.
The pleasant, compositional interaction borne of Scala's syntactical flexibility is why Play's wonderful to use (and Akka as the backend is largely behind-the-scenes). I used to be a detractor early in Play2 because of some large-scale-unfriendly decisions, but they've pretty much all been fixed.
Deleted comment
For Java web development, it is worth re-considering Spring Boot though * (http://projects.spring.io/spring-boot/)
Spring MVC and Data (et al) powered entirely by annotations, and (e.g.) Thymeleaf for templating, can lead to some fairly powerful yet concise apps.
We just started using this where I work, and it's a great step forward compared to old style, XML driven Spring MVC and Hibernate.
Also Spring Boot does bring quite a lot of support for REST, via RestTemplate/RestOperations, along with support for consuming and producing JSON and/or XML at the controller levels.
* Edit: I say re-considering since the article only briefly mentions it.
Modern JavaEE isn't nearly as heavy as the article seems to think ... but I can't argue with the article's underlying pragmatism. Use the simplest set of tools that accomplish the task!
The Spring solution to this problem was always my favorite part of their stack: JDBC template removed most of the error prone boilerplate from JDBC, adds a couple of features, and still lets you write SQL directly, which is probably what you should be doing in almost all the cases where a relational database becomes valuable.
I can't wait for shops to start to use Java 8. The removal of so much boilerplate when trying to build functional interfaces should make the Java toolsets move forward very quickly.
I never cared for the library until I realized I'm spending a lot of time on the developer's blog; he is prolific and very knowledgeable about everything database and java. Was sold on it soon after.
http://huherto.github.io/springyRecords/goals/
Also, this fellow HNer has been experimenting with Java 8 features. Pretty cool. https://github.com/benjiman/benjiql
I suspect that task size has to be smaller than the typical bit of web processing code for context switching overhead to really dominate, or even be expensive enough to matter. That says as much about how expensive common tools and frameworks are as it does about the cost of context switching.
EDIT: scratch the last statement about Go using OS threads for goroutines. I was thinking of something else.
Sometimes on Linux systems, even allocating a large stack size doesn't actually consume that as physical memory. Malloc might give you the memory block, but until you actually make function calls or allocate data on the stack, it might not consume the memory.
Now, fibers are not perfect: their main shortcoming is integration with legacy code. The optimal approach is scheduler activations, or "user assisted" kernel scheduling.
On the other hand, Go does use green threads, and the main developers of Go are by no means naive. So maybe green threads do have some benefit, but only when implemented in something higher-level than libc and pthread.
But yeah, a whole lot of people seem to think "man, OS threads suck, surely we can do better with green threads," only to find out why OS threads suck, and that many developer-years of work have gone into making them not suck more.
http://msdn.microsoft.com/en-us/library/windows/desktop/dd62...
https://news.ycombinator.com/item?id=6977177
BTW, I wonder if Paul Turner's work on fibers will change this equation if/when it makes it into the production kernel.
https://www.youtube.com/watch?v=KXuZi9aeGTw
Google has had very promising initial results with it.
EDIT: So I guess we should run more big multi-threaded server apps with musl and see what breaks.
If you are in a million thread scenario it is usually because most of them are idle and retaining state for some eventual activity. That also tends to mean that they are long lived.
It would be interesting to do this for native threads at the kernel level: it's very similar to swapping, except for stack data you could just throw the data away if you could figure out that it was indeed dead.
Native threads don't have a way to reclaim stack memory other then swap. My personal opinion is that this should be solved in the kernel and that kernel threads should have an option for reclaiming stack space so I can run as many as I want.
It's true that app servers were originally conceived as a way of hosting multiple apps in a single JVM, but it quickly became apparent that this was a terrible idea, and nobody does it. You run one instance of the app server per app. The app server is really just a great big bundle of useful libraries and a web framework.
They're separated in the sense that the app server is something you download that exposes an API, and the app is something you write on top of the API. It's much the same as the way the JVM and the class files are separated, or the way the OS and the JVM are separated. It's a fairly straightforward, pragmatic application of layering.
Rack in the ruby world exposes an API that ruby web apps build on top of, but you never install an app server then install your app into the server.
My preferred solution would be to package the app and the app server as operating system packages, and have the app depend on the app server. That makes the dependency explicit, but doesn't leave you with a gigantic deployable.
Anyone interested in modern JVM web development I would still advise to invest time in learning Scala (or Clojure). They can work with your legacy code and libraries, but my productivity and general joy in programming shot through the roof when I started using Scala.
That was exactly my experience. Maintaining Java code from time to time makes me realise just how big the difference is.
It's a questionable framework mashed together with a poorly though out messaging system.
I would rather use Spring Integration, Quasar, or Akka.
Classloader per verticle type makes dependency injection painful. "I don't know what a Spring "ApplicationContext" is" -- Tim Fox
Uses multiple classloaders so you can "run multiple versions of the same module at the same time". Not something I have ever done or would do.
Uses Hazelcast for clustering but uses tons of classloaders so using anything other than simple types in Hazelcast is hard and inefficient.
Message bus is tightly coupled to application cluster through Hazelcast.
Messaging is missing the most useful features of AMQP like wildcard topics and queues. Only possible to do very basic message routing. Many messages have to be sent multiple times to mimic advanced routing.
Dividing everything into 'verticles' encourages use of callbacks for everything. This increases code size and complexity which increases the need for testing. 'Callback hell'
Encourages polyglot programming.
Writing Vertx apps with Groovy makes me feel like I could add a whole chapter to 'How to Write Unmaintainable Code'.
Some of those I consider advantages - polyglot is the whole reason I looked into it, Groovy is the main language the app I'd be integrating it into is written in, callbacks are the mainstay of many other frameworks (try writing anything in Node.js without a callback!).
That the clustering is poorly designed is probably not an issue in itself since in my case it's a web server embedded in another app, but it's a concern that the framework isn't well thought out and I don't like that (it sounds like) the whole thing is heavily entangled with Hazelcast (which I have no need for, or interest in).
Thanks again for writing down your thoughts!
> try writing anything in Node.js without a callback!
I wouldn't even try writing anything in Node. Server side javascript is not an option I would consider. http://www.youtube.com/watch?v=bzkRVzciAZg
Hazelcast on it's own is pretty useful if you need a distributed data grid in Java although it's not without its quirks. Unfortunately it's much less useful in Vertx because of the classloaders.
Callbacks as an antipattern is one of the main points of this HN post.
Some of these "problems" aren't problems at all, e.g. what's wrong with polyglot programming?
> Writing Vertx apps with Groovy makes me feel like I could add a whole chapter to 'How to Write Unmaintainable Code'.
Vert.x enables many JVM languages to program it. Perhaps the real problem's with the language you've chosen. Groovy's business purpose is to ensure jobs (i.e. consulting contracts and conference seat sales) for life for its promoters at SpringSource. Choose a language with another mission and that could make all the difference.
The framework and the language are both problems in my opinion. If it was up to me I would have chosen a different framework, messaging system, language, and more. Wasn't my decision to make though.
for {
user <- asyncGetUser(1)
company <- asyncGeCompany(user.companyid)
longresult <- asyncProcess(company.getSomething)
} yield longresultIt can be a problem. In Akka actors, referencing sender() from a future will be unpredictable because sender() could've changed in the mean time.
I think there are three strong solutions which address this problem:
1) Immutable state. Solves this problem completely but accidental capture remains an issue.
2) Hiding mutable state within actors. I hesitate to present this as a general solution though since it really requires going all-in with actors (I don't consider that to be a bad thing, necessarily).
3) Projects like Scala Spores [1] aim to tackle this at the compiler by capturing mutable references and executing async closures in an immutable environment and prohibiting accidental capturing. IOW, turning accidental capture into a compiler error. I'm excited about this one.
[1] https://speakerdeck.com/heathermiller/spores-distributable-f...
It's also somewhat unavoidable when you're dealing IO, unless you stick to .pipeTo(self)
user = getUser(1)
company = getCompany(user.companyId)
longresult = process(company.getSomething)
is a) simpler (because that's what your normal code looks like), b) performs exactly the same (as fibers basically do the same thing, only transparently), and c) retains context (like ThreadLocal variables).So if that was the only way, I'd say, fine. But once you have lightweight threads, they are always preferred (even Scala now has its own poor-man's lightweight threads in the form of async/await).
Actually, no. My code will always look like the for comprehension be it async or not, because my 'get' methods will always return an Either, Option or some other monadic context to represent the computation succeeding or not.
> performs exactly the same (as fibers basically do the same thing, only transparently),
Yes, I agree.
> c) retains context (like ThreadLocal variables).
Threadlocal variables are almost always code smell. If you find yourself using them, there is almost certainly a better way of accomplishing the same thing.
I don't see how having a Fork/Join threadpool that 'powers' the futures would be any slower than lightweight threads either.
With futures I can say, start operation 1 and operation 2 in parallel, then chain a callback to execute using both pieces of data, saving me some latency of doing the operations serially. How do you do this using quasar? Now that's a trivial example... what about arbitrary dependency trees? This falls out naturally with futures but I don't know of a nice way to do this with lightweight threads. e.g. 1 operation branches off into 5 other parallel operations which then chain some of their own additional callbacks for processing before finally bringing all the results back together, perhaps to form a json response. Does this example make sense?
Of course, you can keep using futures (what I call semi-blocking API), only futures that block the fiber rather than the thread, when you join them.
Of course you can have long-running fibers that interact with one another through channels. See: http://blog.paralleluniverse.co/2014/02/20/reactive/
Maybe it's just been a long time since I had to deal with Java-land, but you need to know about so many different things just to get off the ground. Granted, this may be easier with newer frameworks, but still.
I think that's probably true of just about any mature environment these days, isn't it?
Nobody wants it to be true. You make something new, thinking, this time i'll do it right, it'll be so simple, easy to get going with. And it is at first. Then you add stuff to deal with all the things that turned out to be pain points, all the edge cases and use cases that someone had that seemed reasonable after all, before you know it, it's a monster again.
To get off the ground with Rails 3/4, you sure need to know a lot. That wasn't neccesarily true in Rails 1/2 when some of us got started, and we were able to learn the new stuff gradually as it was added in, but to get started from scratch, let's say you don't even know ruby very well, oy, it's a lot now.
And why? Because we want a mature environment to do a bunch of things for us, so that we don't have to (badly) re-implement everything. But the price of that is, we have to learn how to get the framework to do those things for us.
And, personally, the problems don't end there--I think I'd quit programming before going back to any Java-based hat-on-top-of-JDBC. Scala's Anorm/Slick have given me enough of the "there's a better way" to make going back really unpalatable.
For what it's worth, Akka is even more relevant to what I'm doing.
Play, for me, gives me good tools for doing stuff, and I can make individual services as big or as small as I want.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Of course, you still need to know how Python Does Things, and The Thousand Ways To Deploy An App, and Package Management and so on, but for this trivial example it's a lot more conceptually lean than the semi-equivalent offered above. I don't need to know about `Bootstrap<Configuration>` or a `JModernConfiguration`.It's fair to point out that there will be a corresponding text file or option somewhere else, but…
public class HelloWorld { public static void main(String[] args) {
get("/hello", (request, response) -> {
return "Hello World!";
});
}
}TFA mentioned this was how Modern Java Web Dev With Instrumentation is Done (worth mentioning that Javaland instrumentation is world class), so just going by the examples he provided.
My example on the other hand uses Spark, a micro framework that is not very flexible and hides a lot of the complexity, meaning that if your own solution becomes more complex you may have to abandon Spark entirely.
I've seen that dichotomy in every web framework I've encountered.
I don't think it has much to do with which language per se but more to do with what the language community considers acceptable. You can write mostly head-ache free frameworks filled with "magic" in Java like the rest of them, but it's not a strong cultural value.
To turn to the microframeworks example, I can't speak to Spark but in Ruby land it is not hard to flesh out your sinatra app into a more complex beast should the need arise - converting Sinatra half way to a mini Rails is not something I would recommend, but mostly because you lose easy-library support and ease-of-update down the road (you shouldn't be writing your own custom framework period, sort of thing), and not necessarily because of a lack of flexibility.
You import some stuff... check. You create an instance... check. You define a route... check. You define a method to implement the route... check. You return a String... well the example returns a map, and converts it to JSON. You start the app in a main method... check.
Sure the java is a little more wordy and there are some extra params which are not used (the IDE would fill those in automatically when you implement the interface), but the complexity is the just same as far as I can see.
require 'sinatra'
get '/' do
"Hello World!"
endBlocking IO cannot have predictable latency under load at very least, you are left at the mercy of OS thread scheduler. Due to various reasons (e.g. mutator threads should not block GC and compiler ones) thread priorities are honored.
I'd argue that a well written NIO (and virtually there are no good open source NIO impl) will beat flat out any blocking. NIO is both faster and offers better/predictable latency under load.
Most impl. use heap ByteBuffer, then parsing requires state machines and often they are simplified by copying the buffers. The blocking IO doesn't really need a state machine as the stack serves that purpose. Then there is some reactive alike pattern (submitting tasks to an ExecutorService) that costs some more latency. Certainly, it's easier to work with and reason about, yet the more hand-outs there are the worse the performance/latency is. There are minor issues like the choice of a good queue. It is an important one as java lacks MultiProducer/SingleConsumer queues out of the box, or even single producer/single consumer. Java does have MP/MC queues (CLQ is an outstanding one) but one has to pay some extra price (incl. false sharing sometimes) to use them.
Ultimately the blocking IO cannot be "faster" than NIO per se since under the hood it uses poll(2)[0] with one socket. Before that it copies the java byte[] to a new location - for smaller byte[] it's the stack. Technically one can blow up the JVM if the stack is very tiny while entering socket.getOutputStream().write(byte[])
Lastly Selector.wakeup() has a stupid issue that involves entering a synchronized block each time even if there is an outstanding wake-up request already. Wakeup requests are implemented via pipes on linux (and a socket pair on Windows) that requires kernel mode switch. During the wakeup all the threads attempting to carry the task block on that very selector for no real reason. It can be played around with a CAS, so only one thread actually enters the monitor.
I will repeat myself blocking IO doesn't have predictable latency and cannot be enforced. In the end it's all about the latency as bandwidth can be bought, more machines deployed but you can't buy latency.
[0]http://linux.die.net/man/2/poll
Some internal stuff on heap vs direct buffer: http://stackoverflow.com/a/11004231
Only couple of downsides: 1) there appears to be the lack of bounded queues and it's a non-trivial one. Bounded queues are important to ensure proper back-pressure on 'producers' and/or killing slow peers. 2) encoding pipeline may require serializing the same message multiple times when sending to multiple clients even if the serialization results into the same byte stream. However this is really a minor issue.
Like I've said I'm pleasantly surprised.
These tests were a particular kind of network traffic, and were testing for max throughput across many connections. Minimizing latency, smaller message sizes, and/or fewer connections can make the decision to use NIO vs standard IO libraries come down in different places. (Not to mention that you cannot program the standard IO libraries in a no alloc form).
DBObject r = collection.find(query);
It blocks while getting the results of the query. If I do something like this: for (int x=0; x < 100000; x++) {
new Thread(() -> DBObject r = collection.find(query))).start();
}
it's going to start 100,000 threads and freeze my computer. However, with Fibers I can do: for (int x=0; x < 100000; x++) {
new Fiber(() -> DBObject r = collection.find(query))).start();
}
and it will work fine since these are lightweight threads (like Go goroutines). I guess my main question is, can I use arbitrary unmodified synchronous code like this to run in Fibers or would the library have to be modified to support it? In this case, would someone have to update MongoDB library to add support for Fibers?If library provides asynchronous APIs, it would yield great performance when integrated with Quasar fibers. If not (like JDBC), it would work as well as it does on regular threads, but won't interfere with all the other great stuff fibers can do.
The opposite canonical example being a static, small-file web server. Short connections. How many files can you serve per second?
Java is not my main language, but I liked the Advanced Topic: Blocking vs Non-blocking section and in general have been following Parallel Universe technology stack.
If anyone is interested more in the async vs actors, there is a nice new podcast with Ron Pressler, Fred Hebert (Learn You Some Erlang For Great Good author), Kevin Hamond and Zachary Kessin
http://mostlyerlang.com/2014/05/15/037-parellel-universe-wit...
There is a discussion about concurrency, how Quasar works underneath (hint: there is an interesting bytecode transform that takes place during loading), shared state, Erlang, Clojure and Datomic. Anyway, highly recommend.
public class WebAppConfig extends ResourceConfig {
private final String[] mimeTypes;
public WebAppConfig() throws IOException {
//load static resource from htdocs dir
Collection<File> files = FileUtils.listFiles(new File("./htdocs"), null, true);
ArrayList<String> mimeTypeList = new ArrayList<String>();
for (File file : files) {
final byte[] contents = FileUtils.readFileToByteArray(file);
Resource.Builder resourceBuilder = Resource.builder();
resourceBuilder.path(file.getAbsolutePath().split("/htdocs/")[1]);
final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
String mimeType = Files.probeContentType(Paths.get(file.toURI()));
if (!mimeTypeList.contains(mimeType)) {
mimeTypeList.add(mimeType);
}
methodBuilder.produces(mimeType)
.handledBy(new Inflector<ContainerRequestContext, byte[]>() {
@Override
public byte[] apply(ContainerRequestContext req) {
return contents;
}
});
registerResources(resourceBuilder.build());
}
//load dynamic resources implementing interface Webpage
register(MultiPartFeature.class);
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.example.mycompany"))));
Set<Class<? extends Webpage>> webpageClasses = reflections.getSubTypesOf(Webpage.class);
for (Class<? extends Webpage> webpageClass : webpageClasses) {
registerResources(Resource.builder(webpageClass).build());
}
mimeTypes = mimeTypeList.toArray(new String[0]);
}
public String[] mimeTypes() {
return mimeTypes;
}
}
...
public synchronized void start() throws Exception {
WebAppConfig config = new WebAppConfig();
HttpServer httpServer =
GrizzlyHttpServerFactory.createHttpServer(URL, config, false);
CompressionConfig compressionConfig =
httpServer.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
compressionConfig.setCompressionMinSize(1);
compressionConfig.setCompressableMimeTypes(config.mimeTypes());
httpServer.start();
wait();
}With SDR, you have an @Entity, and a @Repository for that entity, and SDR handles the whole HTTP part, i.e. you don't need to write a @Controller to expose the repository.
Just wondering if Jersey has anything similar.
IMO I would rather use a single threaded server and manage synchronicity explicitly with callbacks, composable promises, comprehensions, monads, and "other functional shenanigans" vs having to sync shared state across threads and manage thread pools.