Friday, September 30, 2011

Upgrading to Rails 3.1 from Rails 3.0.4 with MySQL on Heroku

I ran into a few issues when trying to update my Rails 3.0.4 app to Rails 3.1.0.  I was using a MySQL database (all vanilla stuff) and heroku.  This all worked fine.  I wanted to try SCSS and found that Rails 3.1 has built in support for it; so, I decided to upgrade.  Here's what I did:


Watched the railscast for upgrading: http://railscasts.com/episodes/282-upgrading-to-rails-3-1  Which instructed me to follow these steps:

  1. Change Gemfile rails version to 3.0.10
  2. bundle update
  3. make sure it still works
  4. Change Gemfile rails version to 3.1.0
  5. Comment out line in development.rb: config.action_view.debug_rjs
  6. bundle update
  7. make sure it still works
This is where I got my first issue.  It said the mysql2 gem was too old (mine was < 0.3).  I change the Gemfile to use the newest version and ran 'bundle update' again.  

Then there was another issue related to the mysql2 bundle pointing to the correct library.  This is a common issue running on OS X I guess.  Here's the fix and the link where I got it: http://freddyandersen.wordpress.com/2010/10/03/mysql-5-5-snow-leopard-and-rails/

sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/ruby/gems/1.9.1/gems/mysql2-0.3.7/lib/mysql2/mysql2.bundle
At this point I can run the app as normal locally.  The next step was to push to heroku.  I created a separate heroku location in case I ran into issues or if they used a different stack for 3.1 vs 3.0.x.  I'll skip those steps.  The error I got when I pushed was: `rescue in establish_connection': Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.) (RuntimeError)
Unbeknownst to me, heroku actually uses postgress and not mysql.  I guess it just worked before.  I didn't really want to change my local stuff if I didn't need to so I found a solution here: http://stackoverflow.com/questions/6410623/heroku-error-when-launch-rails3-1-app-missing-postgres-gem
The actual fix was to just add the below to the Gemfile and run bundle with the '--without production' flag:
group :production do
  gem 'pg'
end
After that pushing to heroku worked fine.
P.S. I must have run heroku db:migrate at some point, but I can't remember when.  I think it was before I got the postgress error.

Pretty Print XML in Java

I got my solution from http://stackoverflow.com/questions/1264849/pretty-printing-output-from-javax-xml-transform-transformer-with-only-standard-ja

import javax.xml.transform.OutputKeys;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

Source xmlInput = new StreamSource(new StringReader(xml));


StreamResult xmlOutput = new StreamResult(new StringWriter());
transformer.transform(xmlInput, xmlOutput);
System.out.println(xmlOutput.getWriter().toString());

Thursday, August 4, 2011

Simple Session Timeout Handling with Seam/JSF/Facelets

I took Christian's great post http://relation.to/Bloggers/ImplementingGracefulSessionTimeoutWithSeamJSFAndJQuery and simplified it for my use.  My solution uses the same session checking mechanism, but assumes all pages should be handled the same, and that we just want to kick the user back to the landing page instead of the fancy stuff Christian did. Leave a comment if you need any of the code explained.

I'm assuming you're using Facelets, so you have some layout.xhtml (or whatever) that all your pages are using.  Just add this to the <head>:

<s:remote include="httpSessionChecker"/>
<script type="text/javascript">
var sessionChecker = Seam.Component.getInstance("httpSessionChecker");


   function alertTimeout(newSession) {
       if (newSession) {
           clearInterval(sessionTimeoutInterval);
           window.location = '#{facesContext.externalContext.request.contextPath}';
           alert('Your session has expired.  You have been logged out.');
       }
   }


        var sessionTimeoutInterval = setInterval('sessionChecker.isNewSession(alertTimeout)', '#{httpSessionChecker.timeout}'*1000+3000);
</script>


For Seam Remoting, add the jboss-seam-remoting.jar to your project and this to your web.xml:

 <servlet>
  <servlet-name>Seam Resource Servlet</servlet-name>
  <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Seam Resource Servlet</servlet-name>
  <url-pattern>/seam/resource/*</url-pattern>
 </servlet-mapping>



Create the HttpSessionChecker (modified from Christian's):


@Name("httpSessionChecker")
@Scope(ScopeType.APPLICATION)
public class HttpSessionChecker {

@WebRemote
    public boolean isNewSession() {
return ServletContexts.instance().getRequest().getSession().isNew();
    }

public int getTimeout() {
return ServletContexts.instance().getRequest().getSession().getMaxInactiveInterval();
}
}

For simplicity and safety, your best bet is to match all of the timeout times.  You want to match your web.xml, components.xml, and the server timeout.  Here's 30 minutes for all of them (a normal default):

  • your web.xml
 <session-config>
  <session-timeout>30</session-timeout>
 </session-config>
  • components.xml
<core:manager concurrent-request-timeout="500"
conversation-timeout="1800000" conversation-id-parameter="cid"
parent-conversation-id-parameter="pid" />
  • C:\jboss-5.1.0.GA\server\default\deployers\jbossweb.deployer\web.xml
   <session-config>
      <session-timeout>30</session-timeout>
   </session-config>

That should be it.  Now if they leave any page for 30 minutes, it will redirect them to the landing page, and alert them that their session expired.  Its not fancy, but its a good default to start with.

Wednesday, June 29, 2011

Las Vegas Startup Weekend June 2011

http://lasvegas.startupweekend.org/

I attended on the Technical track.  I think it was about 50% Technical and the rest were mixed backgrounds.  It was a lot of fun and I learned a lot.  I even got to meet Tom from MySpace and Kevin Rose (milk.com, digg.com, etc).  Kevin is much taller than you might expect.  I've only seen him on The Random Show with Tim Ferriss.

It was interesting to be in demand.  Many of the folks pitching ideas were vying for me to work with them.  Initially, it didn't seem like there were any standout ideas; so, I struggled to pick where I wanted to work.  I was proven wrong by presentation day.  I think I just didn't get the other ideas.

I ultimately chose to work with bloomworlds.com on a Family Friendly Android App Store.  They had already done a good amount of work on the business model and website for this prior to the weekend; so, we were not eligible for the competition :(  The main piece that they wanted me to fill was the app store client, which is an android app.  This was an exciting challenge to learn how to write android apps in 2 days.  We eventually got the functionality we wanted working by presentation time, but constant internet connection issues killed the demo.  It was great working with them, and I'll likely continue to work with them to finalize a beta release.

The main purpose for this post was to list out my lessons-learned.

  • Kill the presentation.  The groups that really jazzed up the presentation got the best crowd reaction.  This didn't necessarily translate into winning however, but it gives a great sense of accomplishment.
  • If you want to win, target the judges.  This kind of sucks, but the judges are going to be interested in stuff they're involved in.  If you look at stuff they don't get or don't care about, nothing else really matters.
  • You don't need a flushed out idea to pitch.  A lot of folks did, but many just had an idea and went with it.  The more you have the better, but it is relatively low risk to pitch.  If you don't get any takers, you can scrap the idea and work with another group.
  • Make sure you have some environment stuff ready.  My group had everything already, but other groups had to set all that up.  
  • Keep the group together.  My group split for a while so they could get better internet.  This made it more difficult to fix communications between theirs and my stuff.
  • Along with environment setup, internet was a killer.  The WiFi was constantly breaking and slow.  It also killed our demo.
  • The amount that was able to be built when focusing the entire weekend on one thing was amazing.  I plan to use this same method for my own en devours from now on.
  • Have business cards.
  • Don't get distracted by other people or stuff that doesn't matter for the presentation.  This is not a problem for me, because I'm laser focused.  Everyone else reminded me of the chumps in my old CS lab the day before the FTP Client/Server project was due for Dr. Tan.  Maybe stop worrying about the other teams' html and worry about fixing your database.
Overall, I met great people, got inspired, and learned a ton.  Well worth $75.

Saturday, May 28, 2011

Warrior Day 20

Weight: 189
BF: 19.4%
Muscle: 152.33
Fat: 36.67

I had a very good week this week.  My post cheat weekend weight was 195.6.  I was able to get some kind of workout in every day.  I created a meal plan that is about 1200 calories 40/30/30 protein/carbs/fat and stuck to it every day.  With naps, I was able to average 7 hours of sleep per day.

I look better too.  I have sun burn right now, otherwise I would post pictures.  Maybe I'll wait until I get to 185 so it will be a 10lb difference.  The workout I do 10 pull ups, 100 pushups, 100x50lb kettle bell swings is really working well too.  My chest, triceps, biceps, shoulders, and back are all shaping nicely.  On the other days, I'm doing tabata sprints (got up to 10.5 mph) and myotatic crunches.

Today is cheat day.  I'm pumped as always, but I could probably go another week without one if I tried.  I've had this dilema before on slow-carb.  I tried it a couple times and it always fails.  By Tuesday, I'm completely off the train, and I ruin the whole week.  It might be different on Warrior, but I'd rather not risk it.

I'll be looking to eat chocolate, taco bell tacos, funions, chicken fried rice, and alcohol.  I'll try to keep my hydration up, get some fiber throughout the day, and put in some hard workouts.  I might try to max out on pull ups, push ups, kettle bells.

My "warrior meal" is (not eaten in this order):

  • 4 eggs
  • 3 servings of green beans
  • 2 servings of kidney beans
  • 1 serving of almonds
  • 5oz chicken
  • fresh spinach (with the chicken as a salad)
  • 2 slices of ham
  • 1 serving of carrots

I know that 6 pounds in 20 days is no big deal, but this is the first week I've done it correctly.  If I can get a few more weeks like this one, I'll be solid.

Friday, May 20, 2011

JSF sharing across multiple WARs in JBoss/Tomcat

This will be where I keep notes until I have a final solution. Then I'll reformat.

If someone decides that your application should be split up between more than one WAR, but they need to share some data such as User information (even just a logged in token or something), you have to find your own solution as this is not supported by the J2EE spec.  So far I've decided to do some sharing by making one of the WARs (we'll likely have 4 by the end) the one that holds the shared content.  I'll call it 'war1'.  In JBoss/Tomcat, this will give it a context name of '/war1'.  So, in 'war2', we need to look up the /war1 context and grab info out of its session.  I'll give some more detail.

In JBoss/Tomcat, there is a property in the server.xml called crossContext.  Depending on your JBoss/Tomcat version, it may be split into separate config files.  For example, in my JBoss 5.1, the actual config file is C:\jboss-5.1.0.GA\server\default\deploy\jbossweb.sar\context.xml.  You'll need to set this property to true.  The default is true in JBoss 5.1.  I don't know about other versions or standalone Tomcat.  Setting crossContext=true will allow us to lookup contexts from other contexts.

To set something in the shared context, I've done this: (this is in war1)

HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.getSession().getServletContext().getContext("/war1").setAttribute("shared", shared);


In war2, we get it out similarly:

HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
ServletContext medicalportal = request.getSession().getServletContext().getContext("/war1");
Object s = medicalportal.getAttribute("shared");


Ideally, I would like to have a context dedicated to sharing: /shared.  Then all wars would go to the same spot for sharing.  This is all in an EAR; so, we have a jar with some JSF code.  We can shove the shared context accessing code there so that we can have code like this:

FacesUtility.setSharedAttribute("name", value);
Object value = FacesUtility.getSharedAttribute("name");


An over-the-top solution but way cool would be to have a JSF variable resolver that would look in the shared context for beans.  ...  Actually, that might not be over the top.  It would make the code much less complex.

Warrior Day 12

Weight: 191.4
BF%: 20.7
Muscle: 151.78
Fat: 39.62