Changing MySQL timezone on Amazon RDS

Recently, I purchased a MySQL Amazon RDS instance and began using it.

Before , I was using a MySQL server instance installed by myself on the same EC2 micro-instance which was already the application server. Useless to say performance was poor.

So I did a backup and restore to RDS. It is a fine service, allowing you to move MySQL and Oracle databases to the care of a company that administers them and backs them up competently and in huge number, and charges a not-unreasonable price for it.

I am from Italy and develop that app for italian users only. At first I didn’t notice dates are stored in UTC. I confess… I follow the bad practice of not storing dates and timestamps as UTC, and relying on the rdbms default time zone for serving most clients (Italy = only one timezone).

Unfortunately RDS does not support changing the default timezone, it is a read only parameter in the parameters group. However… looking around params a little bit, I found that one named init_connect. It allows execution of arbitrary SQL code on each connection just opened to DB. You can now imagine what’s the trick!

First, I wrote a stored procedure:

DELIMITER 
CREATE PROCEDURE mysql.store_time_zone () 
IF NOT (POSITION('rdsadmin@' IN CURRENT_USER()) = 1) THEN 
   SET SESSION time_zone = 'Europe/Rome'; 
END IF 
DELIMITER;

Then I set the init_connect parameter to:

CALL mysql.store_time_zone

I did it from RDS control panel in console.aws.amazon.com, however if you prefer using cli tools like this:

$ rds-modify-db-parameter-group PARAMGROUP --parameters "name=init_connect, value='CALL mysql.store_time_zone', method=immediate"$ rds-describe-db-parameters PARAMGROUP --source=User
DBPARAMETER Parameter Name Parameter Value Source Data Type Apply Type Is Modifiable
DBPARAMETER init_connect CALL mysql.store_time_zone user string dynamic true

Wait a few minutes for new params to be applied to your instance and…. it’s done! Each query / connection will set the right timezone before being executed.

It’s possible you’ll have to set the right permissions for the procedure, e.g. :

GRANT EXECUTE ON PROCEDURE `mysql`.`store_time_zone` TO 'some_user'@'some_host';

JSF 2.0 composite components

25 February 2013 Leave a comment

JavaServer Faces JSF 2

Today I want to share a simple “hello-world” on creating custom reusable GUI components with JSF2.

The first step consists in writing the component (called composite) itself, here it is:

<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:ui="http://java.sun.com/jsf/facelets"
   xmlns:f="http://java.sun.com/jsf/core"
   xmlns:h="http://java.sun.com/jsf/html"
   xmlns:composite="http://java.sun.com/jsf/composite">
    <composite:interface>
        <composite:attribute name="fooBar" />
    </composite:interface>
    <composite:implementation>
        Hello #{cc.attrs.fooBar} !
    </composite:implementation>
</html>

Clean and simple, isn’t it? cc.attrs is a convention to access component’s parameters (‘fooBar’ in this case).

Wait… I didn’t tell where it should be placed! In a standard Java EE 6 project configuration you can have a path like this:

/myProject/src/main/webapp/resources/myCompositeComps/helloworld.xhtml

where “resources” is the jsf resources standard directory, “myCompositeComps” is your custom named sub-directory and “helloworld” is the name you will use to use your composite component, think about it as a “custom tag”.

Our component is created. Now… let’s use it! Here’s a snippet from my production code:

<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
   xmlns:ui="http://java.sun.com/jsf/facelets"
   xmlns:f="http://java.sun.com/jsf/core"
   xmlns:h="http://java.sun.com/jsf/html"
   xmlns:p="http://primefaces.org/ui"
   xmlns:composites="http://java.sun.com/jsf/composite/myCompositeComps"
   template="/templates/default.xhtml">

    <ui:define name="content">
        <p:dialog 
            header="Test composites!" 
            widgetVar="myWidget" 
            id="myWidgetID">

            <composites:helloworld fooBar="test" />

        </p:dialog>
    </ui:define>

</ui:composition> 

As you can see:

– “composites” is the namespace I used in my JSF page (it could be “foobar” or what you prefer)

– “helloworld” is the composite component name (it’s the filename, too)

– “fooBar” is the component’s attribute

– my document is a JSF page and the comp is called inside a p:dialog ( a Primefaces GUI component ) for showing you a more real example

– fooBar attribute could have been something more complicated than a simple string, for example a POJO

Multiple web applications with JBoss and Apache

25 February 2013 Leave a comment

 

I’ve been struggling for about a week with JBoss and Apache.JBoss AS 7 logo

 

I admit I am not exactly an expert when it comes to deploy web applications in production environment. This is the first time I tried to deploy more than one web application on the same web / application server using Apache2+ JBoss 7.1.1.

 

I already had one web application deployed…

 

First of all, here’s the Apache site configuration (/etc/apache2/sites-available/mydefaultapp):

 

<VirtualHost *:80>
        ServerName      www.mydefaultapp.it
        DocumentRoot /var/www/mydefaultapp
        <Directory /var/www/mydefaultapp>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        SetEnvIf Request_URI "/foto/*" no-jk
        JkMount / ajp13
        JkMount /* ajp13
</VirtualHost>

 

On the other hand, the relevant part of JBoss configuration is inside the standalone.xml configuration file (web subsystem):

 

<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false">
     <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
     <connector name="ajp" protocol="AJP/1.3" scheme="http" socket-binding="ajp"/>
     <virtual-server name="default-host" enable-welcome-root="false" default-web-module="mydefaultapp">
         <alias name="localhost"/>
         <alias name="www.mydefaultapp.it"/>
     </virtual-server>
</subsystem>

 

Finally, I had a “per-war” configuration file named “jboss-web.xml” inside WEB-INF directory of my project. It simply was:

 

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
   <security-domain>java:/jaas/mydefaultapp</security-domain>
   <context-root>/</context-root>
</jboss-web>

 

This…. works! So, in these days another application needed to be deployed and associated to its own dns name (domain). What do I have to do for making my new web app coexist with the old one? Well, first of all I tried to deploy the “new” war… FAIL!

 

INSTALL: Failed to process phase INSTALL of deployment “foo.war” Caused by: org.jboss.msc.service.DuplicateServiceException: Service jboss.web.deployment.default-host./.realm is already registered

 

Well, actually the “jboss-web.xml” of the second war which I am deploying is the same of “mydefaultapp”, the first application already deployed, except for the security-domain name. I mean, the context-root “/” is duplicate. Indeed the documentation is there to be read! You can have multiple war with the same context root deployed, only if they bind to different “virtual hosts”. So I changed my file to be like so:

 

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
   <security-domain>java:/jaas/secondapp</security-domain>
   <context-root>/</context-root>
   <virtual-host>www.secondapp.com</virtual-host>
</jboss-web>

 

Second try…. broken again! 😦

 

Now the error claims it can’t find “www.secondapp.com” service.

 

Gooooogling around and…. I discover that I need to add the virtual server configuration relative to secondapp to JBoss, that was so obvious, so… here it is:

 

<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false">
   <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
   <connector name="ajp" protocol="AJP/1.3" scheme="http" socket-binding="ajp"/>
   <virtual-server name="default-host" enable-welcome-root="false" default-web-module="mydefaultapp">
      <alias name="localhost"/>
      <alias name="www.mydefaultapp.it"/>
   </virtual-server>
   <virtual-server name="secondApp" enable-welcome-root="false" default-web-module="secondApp">
      <alias name="www.secondapp.com"/>
   </virtual-server>

 

Even that… did not work! JBoss keeps telling me: “hey! I can’t find any http://www.secondapp.com web service.”. But I just created it!

 

After a lot of time spent on looking for examples and specific documentation, and about a thousand test configuration, I found by myself that “virtual-host” value must equal the “virtual-server” name attribute!

 

So it should be, in my case:

<virtual-host>secondApp</virtual-host>

instead of:

<virtual-host>www.secondapp.com</virtual-host>

Obviously, in my production environment, I had to create another Apache2 site configuration (sites-available / sites-enabled) for the “secondApp”, identical to the firstApp’s one except for the ServerName.

 

P.S. : I deliberately didn’t explain how to configure mod_jk in Apache2, there are tons of tutorials on that.

 

How to add Swap to EC2 micro instances

2 February 2013 Leave a comment

About an year ago I decided to move a few Coldfusion legacy web applications to a cheaper infrastructure.

Amazon web services Elastic Compute Cloud ( EC2 ) looked like a good choice. It offers a one year “free tier”, that means you can run some basic services for FREE for one year! For example, you can create a “micro istance” and run Linux on it for 750 hours/month. Even without free tier it’s really cheap but… is it enough?

I was mainly interested in creating a server host running Apache + Railo + MySQL . So I did it… there are tons of “how-to” documents and tutorials about that on the net.

My apps ran fine for one year til this week, when my customers started to complain. Occasionally, Railo’s embedded tomcat crashed without an apparent good reason, according to the log files. I won’t tell you all details of my debugging day, however, this thread really helped me to find out the truth.

Actually I did suspect the problem was in memory… let’s face it: you’ve got only 600MB RAM… what can you do with it, seriously? The answer is: a lot! Linux is an awesome OS when it comes to resources usage and management. Despite of that, the Ram was always full (near 300MB for Railo, 200 MB for MySQL), so… first thing I did was moving MySQL. Where? AWS got the solution: it’s called RDS, and it’s another Amazon service for hosting a fully functional Relational DBMS. After that change, I gave more breath to the Railo application server by assigning more memory (heap+non heap) to its jvm.

This worked for a while but soon I was still having the same issue. (D’OH!)

Going ahead in searching Goooogle and reading that post took me to a scary question…. “do I have a swap partition ?” Every linux purist knows that running systems without it is as dangerous as opening hell’s gates.

But WHY? Why Aws guys don’t equip their ec2 instances with a default swap space??

Well, there’s an answer and it’s related to costs. EBS storage mechanism charges you for every bit you read and write to and from disk. Every I/O operation make you spend money, so if you have a very “swappy” instance, you will be charged significantly for it, so creating the swap partition should be a ‘conscious’ operation.

Now please shut up and look how that is done:

1. switch to root with sudo su - ( in ubuntu, e.g.)

2. type the following command ( count is the desired block size )
dd if=/dev/zero of=/swapfile bs=1M count=1024

3. Setup the swap file with the command:
mkswap /swapfile

4. Enable the swap file:
swapon /swapfile

5. Make this change persistent by adding the following entry into /etc/fstab:
/swapfile swap swap defaults 0 0

PDF reports in Java

22 January 2013 Leave a comment

portfolioanalyst_overview_002What if you need to generate a PDF report in Java?

Wait, wait, wait…. what if you need to generate a simple PDF in Java?

Well, with this question in mind, I looked for a solution for printing an invoice from my enterprise Java software.

Gooooogling “create pdf in java” shows results pointing to the fabulous iText .

It’s just that: programmatically creating PDF using the Java language. Wonderful…. paragraph.addParagraph( new Paragraph(“Hello!”) );  …. and so on!

Uhm… reflecting on it a second time… I realize that’s not exactly what I want. How it would be nice to have a Coldfusion-like PDF generator: I can show a HTML page to the user, then add a magic tag and…. voilà! PDF is nice and ready!

Unfortunately, I didn’t find anything similar to that. Finally a good solution came up in my searches, and it looked like just what I needed for my invoices. I’m talking about Jasper Reports .

I am always skeptic when I introduce a new framework in my project. I do consider a lot of things:  will it be light or heavy? How much time will I need to learn it? (learning curve) And what about maven repos?

With these and other things in mind, I tried Jasper Reports and you know what?  I am very satisfied with it! It’s an open source solution, widely used by many Java developers.

The first big pro is iReport : the WYSIWYG report designer. I just downloaded and opened it and I was ready to draw lines and goodies and place fields where I want in a brand new layout.

Here’s how the whole thing works:

1. You create your report template using iReport: in my case I had a layout consisting of a header with invoice header, a body with product rows and a static footer.

2. iReport saves your template as a “jrxml” file. It’s pure XML guys, you can open and modify it with a simple notepad… in fact, you don’t even need iReport to create the template!

3. Then you need to import your jrxml file into your project, in a place where it can be read by your code.

4. Printing your PDF report is just three lines of code:

JasperReport jasperReport = JasperCompileManager.compileReport(templateAbsolutePath);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, paramsMap, datasource );
JasperExportManager.exportReportToPdfStream(jasperPrint, ec.getResponseOutputStream());

Ehehehe :-)) I made it too simple…  What are ‘paramsMap’ and ‘datasource’ ?

Well, paramsMap is a simple HashMap<String,Object> for static parameters (e.g.  “invoiceNumber” => “4” ).

The “datasource” is an implementation of JRDataSouce interface. That interface has two simple methods to implement: next() and getFieldValue(JRField jrField). It’s necessary for providing rows to the report.

And this is the only important thing to keep in mind: a report with zero rows will not be printed! You need to have at least one row in the body or your report won’t be printed by JR. This caveat makes difficult to generate documents that aren’t reports. A report expects a collection of rows, so if you’re trying to display a simple hello world report (empty datasource) with static text you’ll see a frustrating white page.

JR provides a lot of datasource implementations, for example JRXmlDataSource. I created my own datasource because I wanted to have more control on data binding.

Finally you can write your awesome report to a variety of targets such as: screen, a printer, PDF, HTML, Microsoft Excel, CSV or XML files.

That’s all folks, I’m sure there’s a lot more to know and understand about JasperReports, I simply wanted to blog my “one-day-experience” using it and going from zero to a nice pdf report in no time.

Copying bean properties via reflection

7 January 2013 Leave a comment

Yesterday I was working on my Java EE project, when I felt the need to copy content from one bean to another.

So I have two instance of this JPA entity bean:
@Entity
@Table( name="foo", uniqueConstraints = @UniqueConstraint(columnNames="code") )
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
private String name;
private String code;
// ...
}

Ok, now I want to write a createOrUpdate() method in my DAO.

The use case is:

– creation of first = new Foo() and set (code=’BAR’) (name=’something…’);

– persist() the new foo;

– creation of second = new Foo() (out of JPA persistence context) and set (code=’BAR’) (name=’someone else…’);

– update of the existent foo (step 1) with the data from the just created one… HOW?

As the dumb I am, I just try to merge(second). Obviously it doesn’t work because “code” property is not the primary key. So JPA tries to create a new record and fails because of the unique constraint on “code”.

My createOrUpdate(Foo f) can be written two ways:

1. first I try to retrieve the Foo to edit from the DB, via a search query. If there are no results, then I call persist(), Else I set to the new “second” object (out of persistence context) the ID property of the retrieved object, so they have the same identity (the equals method of each Foo just compares the id), then I merge(f).

That’s a little tricky, IMHO.

2. Instead of copying the id property to the new object, I copy all the other properties to the detached entity, just like:

– entityRetrievedFromQuery.setCode( f.getCode() );

– entityRetrievedFromQuery.setName( f.getName() );

…

Java ReflectionI don’t want to do it manually for 100.000 properties so…. reflection is here to help!

I want some utility for looping over a generic Object properties and copy each one from the object “from” to the object “to”.

I want to exclude specific property names, too.

For bean properties copying there’s already the excellent BeanUtils ( from apache commons ), which unfortunately does not have anything for exclude specific properties from copy process. So I just wrote my own class with method:

public static void copyEntityProperties(Object fromObj, Object toObj, String[] excludedProperties) {
Class<? extends Object> fromClass = fromObj.getClass();
Class<? extends Object> toClass = toObj.getClass();
try {
  BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
  BeanInfo toBean = Introspector.getBeanInfo(toClass);
  PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
  List<PropertyDescriptor> fromPd = Arrays.asList(fromBean.getPropertyDescriptors());
  for (PropertyDescriptor propertyDescriptor : toPd) {
    propertyDescriptor.getDisplayName();
    PropertyDescriptor pd = fromPd.get(fromPd.indexOf(propertyDescriptor));
    if (pd.getDisplayName().equals(propertyDescriptor.getDisplayName())
     && !pd.getDisplayName().equals("class")
     && !Arrays.asList(excludedProperties).contains(pd.getDisplayName())) {
       if(propertyDescriptor.getWriteMethod() != null) {
         propertyDescriptor.getWriteMethod().invoke(toObj, pd.getReadMethod().invoke(fromObj));
       }
     }
   }
 } catch (IntrospectionException e) {
  e.printStackTrace();
 } catch (IllegalArgumentException e) {
  e.printStackTrace();
 } catch (IllegalAccessException e) {
  e.printStackTrace();
 } catch (InvocationTargetException e) {
  e.printStackTrace();
 }
}

This is very similar to this SO answer: http://stackoverflow.com/questions/835416/how-to-copy-properties-from-one-java-bean-to-another/7845841#7845841 with the clause for excluding properties, in addition.

I will use it like:

ReflectionUtils.copyEntityProperties(foo, existent, new String[]{“id”});

and it works like a charm! 🙂

Create your own website, free on WordPress.com.Create your own website.
Start free