piątek, 5 maja 2017

[memo] Accessing files in a web application

Sometimes the easiest things are also the easiest to miss (or to forget :-) ). Therefore, in order to have this once and for all in one place - the quickest guide how to access files in a servlet environment (Spring Boot application in my case).

1. Classpath resource

A file that is present in a classpath (typically /WEB-INF/classes, /WEB-INF/lib).
Can be anything, most probably a configuration file that is packed with WAR during package preparation stage. In case of good old Maven - all of the resources (by default src/main/resources) will end up in the classpath. Access - via context class loader.
For example:

2. Web resource 

All of the web application files - including static content (images, styles, html, ...) and files that are loaded into classpath (JARs from /WEB-INF/lib etc.) can be accessed this way. The only requirement is the presence of a ServletContext. 
PRO TIP: In a Spring application, the ServletContext can be simply autowired into a service requiring it. 
For example: 
As a last word - be __very__ cautious when planning to use ServletContext.getRealPath(). Why? Just take a look here: http://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it

wtorek, 11 kwietnia 2017

Java 8 for late-adopters ;-)

I've just realised that Java 8 is already 3 years old! For a general-purpose language version, this happens to be a lot.

What's even more striking is that there are still a lot of projects that haven't been migrated to the newest (but already mature) version. There are in fact many projects that still use first "real" JRE, that is version 5 which introduced generics, enums, autoboxing, improved concurrency and all of the stuff nowadays recognised as a minimum standard.

Why is that? Well, sometimes is because cost of migration, especially for big, monolithic systems, is deemed to large. Sometimes that may be true. However, often the cost is overestimated or the benefits are underestimated. Therefore in this short post I'd like to present some Java 8 features that in my opinion can really bring substantial benefits and at the same time provide good arguments to justify the migration:

1. Lambdas aka functional programming for the masses.

Yes, we have Guava's Function. Yes, it's a bit of functional programming. But let's just compare this:
and this:

How cool is that ? And it's only a beginning! Java 8 added a real functional programming  API, as advanced as it can be taking into account object-oriented nature of the language and dreaded "backwards compatibility".
In order to fit some functional programming into Java, following concepts had to be introduced:
  • functional interfaces - basically a "type" for a "function"
  • new "->" notation, with following syntax rules:
    • types of the parameters are optional
    • parentheses around the parameter are optional if you have only one parameter
    • curly braces are optional (unless multiple statements are present)
    • return” keyword is optional in case of a single expression that returns a value
  • method references (with "::" operator)
It's really a lot of fun and a lot less of a boilerplate code. You simply need to try it for yourself :-) 

2. Streams and parallel collections

Basically streams (implementing Stream interface, who would guess?) are Iterators on steroids. Why on steroids? Because streams support:
  • out of the box parallel execution!
  • map / filter / reduce pattern
  • functional "iteration" as old friend - forEach method
  • primitive (Int / Double / Long) counterparts for even greater performance
Map / filter / reduce together with lambdas effectively eradicates the need for Guava's FluentIterable and consortes. Sorry! The standard library always wins!
Built-in parallelization and lazy evaluation brings the need to collect, join, group or partition. This is also provided. Nice! Just take a look at this example - joining User names:

3. Joda (well, almost) date / time

The only thing that can be said is at last! LocalTime, LocalDate, LocalDateTime and ZonedDateTime along with a reasonable API (copied from Joda :-) ). Plus fast-and-easy creation (now(), toInstant()). Especially the last one is nice, allowing for a fast migration:
 I wish this had been added years ago!

4. Misc (Optional, Base64 and others)

  • Everyone knows (or at least should know) the Optional class. Now available in the standard library! 
  • Everyone had at least once a need to use Base64. Now available in the standard library as well! 
  • Tuples! At last!
  • No more Permanent Generation (one JVM parameter less, heh)
Maybe it's not something that would change one's life, but definitely something that should have been in Java, like, since beginning.

Java 8 brings a lot. Really, in my opinion it's the first "REAL" update since version 5.0. There is much more than mentioned in this short post, I encourage everyone to go and try (and then try to persuade the management to migrate projects as well...).

poniedziałek, 19 marca 2012

33rd Degree - the first day

Fresh impressions right after the first day of the conference (in case someone's not familiar with - 33degree).

First general talk by Raffi Krikorian of Twitter, focused on their move away from RoR to a JVM-based solution. What's more important - not purely Java but Scala as well! I'm no Ruby expert so I learnt some baffling things about it, like one thread per Ruby process model and incredibly faulty GC ;) All in all, his final thought was that RoR is one of the most productive environment for web apps, but not suited to scale. On the other hand, once your product needs to scale and perform you probably have all the money needed to rewrite it.
As a side note - who'd guess few years ago that Java will be perceived as a key tool to achieve better performance? :)

Next two talks - Ken Sipe's "Complexity of Complexity" and Venkat Subramaniam's
"Pointy haired bosses and pragmatic programmers: Facts and Fallacies of Software Development" were typical "generic", entertaining talks as encountered on each and every conference. I don't mean to say the talks were bad, not at all! I personally fancy such presentation, not only filled with geek-jokes and funny slides but also sharing general wisdom stemming from experience in the software development business. It's sometimes akin to looking at a "old scar", like first project that was "overarchitectured" or filled with unnecessary design patterns, just because developers have recently learned them (let's refactor to factory! everything! [diabolic laugh]). Simply put - I enjoyed them but I can't say I learnt a lot.

Next it became harder, as conference split on 4 tracks and I had to blindly choose what to attend. Retrospectively, my picks were 50/50, just as the calculus of probability would say.

"Build Trust in Your Build to Deployment Flow!" was disappointing. I expected something about DevOps/Continuous Deployment and got "Artifactory" feature walk-on. It has some advantages as compared to other artifact repositories (like Maven's Nexus), but it'd not call it DevOps-centric. Unless I'd like to attract some attention by using a trendy buzzword ;)

Sadek Drobi's "Non blocking, composable reactive web programming with Iteratees" was a good, technical demonstration of some Scala's Play capabilities. And those are definitely impressive! Unfortunately presenter assumed participants' deep knowledge of Scala, so from time to time I had problems catching up.

The last presentation was "import continuous.delivery." by Toomas Römer (of ZeroTurnaround). Next attempt in my "quest for holy DevOps". As his predecessor Toomas focused on presenting a product of his company - LiveRebel. However this time I was able to see how it can be nicely integrated within semi-automatic build/deployment/promotion flow. Good job ZeroTurnaround!


Two lessons learned today:
1. Worth to take a deeper look at the Scala, even though ugly Pascal-like syntax :) There are some very interesting ideas behind the language and it's "web arm" - Play.
2. ZeroTurnaround products can sweeten DevOps implementation a bit. Functionally the same can be achieved with a bunch of shell scripts and cron jobs, but why bother? ;)

wtorek, 4 października 2011

Is software development akin to ice cream making?

Surprisingly much more than could be suspected.
As nicely explained by Martin Fowler on his blog here, famous ThoughtWorks "stole" its operation model from a ice cream company. He describes the model as founded on three pillars. They're as follows:
1. Sustainable Business - this one is fairly obvious and boils down to "you need money to survive in business". However, one special thing is noted by Martin: "revenue is like oxygen - you need it in order to live but it isn't what you live for". I like it :)
2. Professional Excellence - seems to be obvious as well. One should always strive to do the best possible job. What's interesting, Martin argues that this sometimes involves *not doing* what customer wants. Particularly, he elaborates about features that don't pass their (internal!) usefulness evaluation. Now this is something different than I've experienced! Additionally Martin claims this pillar includes improving not only how his company works, but also the industry as a whole. He believes that if his company invents/finds something interesting or makes a breakthrough, it should share. My belief is that some *big* IT companies could benefit from this pillar a lot.
3. Social Justice - contrary to the first impression this not about giving out stuff for free ;) It's rather another incarnation of (in)famous Google phrase "don't be evil". Martin's explanation here is that a company should care more than simply "if they pay we will do". He strongly advises that each piece of work done should be valuable to customers and society. What surprised me was his claim that ThoughtWorks had rejected many profitable and technically interesting contracts because of negative third pillar impact. Well, again - that's something that didn't occur too frequently in my practice ;)

Personally, I'm fascinated. In Martin's words TW sounds like a perfect mix of two differnt company types: start-up (technically savvy, interesting top-notch projects, caring about sth more than money) and corporation (financially stable, believing in good processes). I encourage everybody to read full Martin's post and establish own opinion.

piątek, 15 lipca 2011

Stay SOLID!

From time to time, in a break between fierce battles with code, requirements and time each of us starts asking questions more sophisticated than "how to write another freakin' routine". One of the most frequently repeated is how to check if a OO code is really well designed (and later implemented).
Let's forget for now about the "big" architecture and concentrate on the "small" one - single components/packages. Some advices and concepts (as DRY or GRASP) can be found here and there - for example in excellent book "Effective Java" by Josh Bloch. Additionally, tons of useful yet short articles are published by recognized authors as Martin Fowler or Robert "Uncle Bob" Martin.
The latter one created short, concise list of Object Oriented Design principles under the clever name - SOLID. In short, those are as follows:
  • S(RP) - Single responsibility principle - "an object should have only a single reason to change".
  • O(CP) - Open/closed principle - “ability to extend class behaviour without modifying it”.
  • L(SP) - Liskov substitution principle - "subtypes must be substitutable for their base classes, without modifying program's correctness".
  • I(SP) - Interface segregation principle - "create fine grained interfaces for specific purposes".
  • D(IP) - Dependency inversion principle - "depend on abstractions, not on concretions"
SOLID is few years old, but still managed to gain some attention, so web is filled with articles discussing all principles in details. One particularly interesting resource is old Uncle Bob blog post here. Also, Lost Techies has an article filled with Java examples.

Looking from experience's point of view, after some years of code crunching SOLID principles come intuitively. SRP, OCP are basic concepts understood quite early. DIP is adopted swiftly after meeting DI containers. LSP looks a bit more complex, but is in fact substantial when dealing with complex models with inheritance.
All in all, it's good to keep SOLID as a reference. Reviews can only benefit from using such simple yet useful checklist :-)