Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, April 23, 2013

Using FreeMarker Templates in a Grails App

I've started in a new team at my job.  We're creating an admin system that is going to take the functionality of several disparate systems and put them all under one UI.  Since we're writing a whole new app from scratch that will interface with existing systems, we had our choice of technologies (within reason) and frameworks.  We ended up choosing Grails because we figured it would be easy to integrate with our other systems and provide us with easy to create RESTful services.

One of our requirements was to use FreeMarker to generate the HTML of our UI.  This is a  requirement because we're using FreeMarker in other areas and we've created a development tool that uses FreeMarker in addition to other front end technologies (JS, SASS).

The problem is that Grails wants to use GSPs (Grails Server Pages), which are like JSPs (and, in fact, compile down to JSPs).  Grails has the ability to incorporate third-party plugins into your project, and there's a FreeMarker plugin for Grails.  Unfortunately, the plugin was made for Grails 1.2 and we're trying to use Grails 2.2.1.  I tried for two days to try to get the FreeMarker plugin to work, but it just didn't seem to do anything.  It was a frustrating situation.

Having read a lot of Grails documentation over the last few days, I found that you could configure Grails similarly to how you configure a Spring application.  You put that configuration in the resources.groovy file.

import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver

// Place your Spring DSL code here
beans = {
 freemarkerConfig(FreeMarkerConfigurer) {
  templateLoaderPath = "/"
 }
 viewResolver(FreeMarkerViewResolver) {
  cache = "false"
  prefix = "bin/freemarker"
  suffix = ".ftl"
  exposeSpringMacroHelpers = "true"
 }
}


Spring configuration is, of course, XML and this is a Grails closure.  That part wasn't hard to convert.  You can find an example of how to configure FreeMarker in a Spring app looks like, here.  The only other thing we had to do was to put the line below into our BuildConfig.groovy file.

dependencies {
 ...
 runtime "org.freemarker:freemarker:latest.release"
 ...
}

Now, the only thing we had to figure out was where to put the FreeMarker templates.  At first, we had them in our views folder where the GSPs went, but we were getting 404s when we ran the app.  After some debugging (thanks Roy for helping debug!) we figured out that the template loader was looking for the templates in the web-app folder.  That was easy enough to fix, we copied our templates from the views folder over to the web-app folder.  After that, everything worked just fine!

So, to recap, we added a typical Spring configuration to the resources.groovy file, added the FreeMarker jar as a runtime dependency in the BuildConfig.groovy file and put our templates into the web-app folder (in the folder configured in the prefix of the viewResolver).

The solution was frustratingly simple after we figured it out.  I wrote this post because I researched and experimented on whether this was possible or not for over two days without any success.  Hopefully this helps anyone else who is trying to use FreeMarker in their Grails app.

If you're like me, though, you want to see more.  Here's an example of a generic Controller:

class ApplicationController {

    static defaultAction = "show"

    GrailsApplication grailsApplication

    def show() {
        [model: [version: getAppVersion()]]
    }

    private getAppVersion() {
        def metadata = grailsApplication.metadata
        return metadata['app.version']
    }
}

It has one public method, show.  We want that when you navigate to /app-name/application or /app-name/application/show that it displays the version of the app.  I created a template, /web-app/application/show.ftl.  Now, the template contents are:

hello world<br>
${model.version}


When I navigate to /app-name/application/show, I get:




Which is as expected.  Pretty slick.  We're still at the beginning, but this should allow us to borrow front -end devs from other teams since they'll already understand the view technology and we'll be using the same tools that their teams use.

Thursday, April 26, 2012

Project Euler


I've always had a fondness for math.  I've always been pretty good at solving math problems too.  Today, a friend at work made me aware of Project Euler.  For those of you who don't know (probably most of you), Project Euler is "a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve".  Man, solving math problems with programming?  Where do I sign up?

So, I've begun my struggle to get through the 381 problems listed on the site.  Problems 1 and 2 were easy, things that we had to do in college.  Problem 3 is a little tougher, but still pretty easy.  That's how far I've gotten in an hour.  I'm going to keep going though, I'll update the blog with my progress occassionally.

Spoiler alert: I'm posting answers to problems 1 and 2 below.  Don't read if you're going to attempt this.  I'm using Java as my language of choice to solve these problems.

Problem 1:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

I first solved this recursively, but was getting stack overflow errors, so I went to the simpler method of brute force.

private static int MAX = 1000;
private static int calculate() {
int sum = 0;
for(int index = 0; index < MAXindex++)
if(index % 3 == 0 || index % 5 == 0)
sum += index;
return sum;
} //end of calculate method

Problem 2:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...  By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

private static int MAX = 4000000;
private static int calculate() {
int sum = 0;
int first = 1;
int second = 2;
while(second <= MAX) {
int temp = first + second;
if(second % 2 == 0)
sum += second;
first = second;
second = temp;
} //end of while loop
return sum;
} //end of calculate method

There you have it.  Notice that I haven't posted the results of running these.  Gotta leave something to you guys!

Friday, October 7, 2011

Return to Java

 If you read my blog, you'll know that I just started a new job last week.  The new job is using Java and I've spent the last week getting re-familiar with the language and tools.  It's been a week of reading a lot of text books and using Eclipse heavily for the first time in several years.

The first thing that I've noticed again is how versatile Java is.  This week, I've played with some server side code, technical layer type code (API to a database) and client side code (web servlets, okay, not really client side, but web side anyway).  I get more and more excited about using Java again every day, even every hour it seems sometimes.  I've already got big plans to build a game engine and other stuff like that using Java.

When I started with Wyde, I had those same big ideas, but it just wasn't viable with the tools available.  First, just to develop with the IDE, you need a license.  That's fine if I'm using my work laptop, but I don't think that Wyde would have liked me getting a limitless license on my personal computer.  Plus, I'd have to compile it down to C++ using Visual Studio, which I didn't have access to on my own PC.

Man, Java is so much easier.  The best IDE (Eclipse) is free.  Most of the other good tools and frameworks are free.  Google has server space for your apps that is free.  Once again, I can't state how exciting this is.

Now, don't get me wrong, working for Wyde was one of the best experiences in my life.  I learned a lot about projects, business, insurance and myself during my time there.  I know that I can lead teams, run and participate in projects and design components in a larger application.  All of that I learned at Wyde.  Even if my knowledge of Wyde's proprietary language isn't particularly useful, the technical, personal and management skills that I learned there are invaluable to growing my career.

I think that I'm getting a little off topic, so I'd like to conclude this post by giving you all a link to my AppSpot and saying that you should check back there often.  Right now it's just a little "Hello world" app, but soon it will be so much more.  I'm planning something big that I hope you all will enjoy.  I will, of course, keep updating my blog with updates to the app that I'm building, but more frequent updates will come from my Twitter or Facebook pages.

Monday, October 3, 2011

Job Change

Those of you who know me personally probably have heard the news already, but here it goes: I've started a new job!  This time it's for real, unlike last time.  :)

The decision to leave the company that I'd been with for nearly five years was a difficult one.  There have been many frustrations over the years there, but the number one reason that I chose to leave (at least at the start of the process) was travel.  I've been travelling almost constantly for work for five years now.  I've had a couple of slow periods where I would get to stay home for a month or two, but overall, I'd say that I have spent about fifty percent of my time with Wyde on the road.  By itself, travelling isn't that bad.  I do enjoy visiting new places and meeting new people, but with a family (and especially two small children), travelling is very taxing.  Now, don't misunderstand me, I'm not saying that my family makes it hard to travel; I'm saying travelling makes it hard on my family.  I just couldn't live with it any longer.

The other thing to understand is that I wasn't looking for a new job.  One of the things that I hate the most in life is job hunting!  When I graduated from college, it took me ten months to find a job in my field!  Ten months!  Granted, that was at a particularly tough part of the recession, but the hardest part is getting your hopes up and then being rejected.  I couldn't count how many times I heard, "we're very interested," or, "we'll be in touch," or any other saying that leaves a candidate with hope just to have it all come to nothing.  A couple of times I had been told that they wouldn't give me a formal offer right away, but that I would get one within the week, but never heard back from them.  Well, I'm getting a little off topic here, so I digress.

My point is that I wasn't looking.  I've been getting a call from headhunters about once a quarter for the past year or two and I would go through the motions, maybe have an interview or two and then not hear anything.  I took it all in stride, not getting my hopes up for any of it.  This last time, about a month ago, I had another head hunter call that went a little differently.  The recruiter handed me right off to the interested company and they wanted to interview me right away and in person.  I was, unfortunately, out of town, but they were cool and we scheduled for the next week.  They acted fast and got me an offer the same week that I had the second interview.  Now, I'm not going to go into the details of what happened next, but there was a counter offer and then a counter-counter offer and I ended up accepting the new company's counter-counter offer.  That's another thing that I wasn't trying to do (get a bidding war over me going), but it's nice to feel wanted!

So, what's different now that wasn't when I'd gotten other interviews?  Well, for one, the new company has a different outlook on what it takes to be a good developer.  They feel, similarly to how I feel, that if you know the theory/concepts of object-oriented programming that a language is easy to learn.  It's surprising to me how most other companies don't grasp that.  I hadn't done Java programming since college and this company was willing to take the risk based on my interview and hire me as a Java developer!  I was amazed!  Another reason is that I am more experienced now than I was out of college.  Duh, right?  Well, I didn't really fully realize that until I started talking to this company and they asked me certain questions that a newbie might not know about.

You may have noticed that I haven't mentioned the name of my new company.  The reason is that I'm not sure how they would take me writing a blog about this whole thing.  Maybe after I've worked here for some time I'll share with you all that information, but for now I'll keep it quiet.

Another main benefit to switching jobs is that I get to work using Java again.  I've been reading training manuals now for a while and the more I read the more I remember why I liked Java.  It's also made me realize how important a good design is to having a successful product.  I'm just going to leave it at that.

So, it's exciting news!  At the same time that I'm sad about leaving Wyde and leaving the friends that I made there, I'm happy for this new opportunity to return to Java and do something different.  It's a good opportunity to grow my skillset and to see how other companies do this consulting thing.  Also, yay for no travel! :P

PS: It still amazes me that Word likes "travelling", but Firefox wants it to be "traveling".