July 30th, 2010
In one of our projects, we had to create PDF documents from HTML. The iText renderer was an excellent solution to do that. However, the tricky part was that the cover page had to be of portrait orientation and the rest of the document, of landscape orientation. After doing a fair share of searching on the web, I came across the Documentation for CSS3 Paged Media.
This could be achieved by creating an @page rule with a page name and then, using the page name in the element, which was going to enclose the body, for which we needed a particular style.
For example, since I needed the landscape mode on the inner pages, I had to create a @page rule in the CSS file as
@page content{
size: A4 landscape;
}
And a css selector,(say a div, which was going to enclose such pages)
div .content{
page: content;
}
If the HTML was something like,
<content in portrait mode>
<div class=”content”>
My contents here
</div>
<content in portrait mode>
“My contents here” would appear in a landscaped page.
Hope this helps
Vivek
vivek[at]IntelliGrape.com
http://in.linkedin.com/in/svivekkrishna
Tags: CSS3, Paged Media, PDF generation
Posted under HTML-UI-CSS, Java tools | No Comments »
July 30th, 2010
Hi All,
Here is how you can implement a new transaction in an already executing transaction in Grails which uses nothing but Spring framework’s Transaction mechanism as an underlying implementation. Spring provides @Transactional annotations to provide declarative transactions. We can use the same in our Grails project to achieve the transactional behavior.
Here is the scenario: You have two basic domain classes i.e. Country and State. You try to transactionally save the Country object which in turn creates a State object, however, you want to put the creation of State in a new independent transaction so that even if the outer transaction responsible for creating a Country fails, the inner transaction responsible for creating a State must always succeed in case there are no errors in the inner transaction.
Here is the code:
import org.springframework.transaction.annotation.*
Class MyService {
static transactional = false
def anotherService
@Transactional
def createCountry() {
def country = new Country(name:"India")
country.save(flush:true)
anotherService.createState()
throw new RuntimeException("Error thrown in createCountry()")
}
}
import org.springframework.transaction.annotation.*
class AnotherService {
static transactional = false
@Transactional(propagation = Propagation.REQUIRES_NEW)
def createState() {
def state = new State("Delhi")
state.save(flush:true)
}
}
Now in this scenario, State object always gets persisted whereas the transaction for creating Country object fails and no Country object is created.
Here are few gotchas regarding the above transactions:
1.) First of all, for Propagation.REQUIRES_NEW to work as intended, it has to be inside a new object i.e. a new service in our example. If we had put the createState() method in the MyService there would be no new transaction spawned and even no State object would be created. This is Spring’s proxy object implementation of transactions and you can read more about it here:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#transaction-declarative-annotations.
Please pay special attention to the “NOTE” sub-section.This is what it states:
“In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.”
2.) Secondly, all the @Transactional methods should have a public visibility i.e. createCountry() and createState() methods should be public methods, and not private or protected. This again is Spring’s @Transactional annotations implementation and you can read about it at the same link as provided above. Note the right side-bar titled “Method visibility and @Transactional“.
Well, once you keep note of these gotchas I guess you are all set to make good use of @Transactional annotations and its full power.
Cheers !!!
- Abhishek Tejpaul
abhishek@intelligrape.com
[IntelliGrape Software Pvt. Ltd.]
Tags: @Transactional, Annotations, Grails Declarative Transactions, Grails Transactions, Propagation.REQUIRES_NEW, Spring Transactions
Posted under Database, Grails, Groovy | No Comments »
July 26th, 2010
Hi Friends,
I was going through grails docs, encountered a method called load(), found it really useful thought would share with you. What load() does is, it creates a proxy object and doesn’t retrieve the record from the database until property other than id is accessed.
Let us consider a scenario, where we have id of a Object “subject” and students of that subject needs to be listed. So we would generally do something like as given below:
Subject subject = Subject.get(subjectId)
Student.findBySubject(subject)
In the above code, we had to load subject unnecessarily where its ‘id’ should have been sufficient. Now, with load no extra queries are required.
Subject subject = Subject.load(subjectId) //creates a proxy object, not retrieved from database
Student.findBySubject(subject)
And same when used with criteria queries
Student.list{
eq('subject', Subject.load(subjectId))
...
}
Thanks to the grails development team for all their efforts!
Cheers!!
~~Amit Jain~~
amit@intelligrape.com
http://www.IntelliGrape.com
Tags: Grails, load, proxy
Posted under Grails | No Comments »
July 23rd, 2010
| Auto complete .com Address |
Ctrl+Enter |
| Auto complete .net Address |
Shift+Enter |
| Auto complete .org Address |
Ctrl+Shift+Enter |
| Back |
Alt+Left |
| Bookmark All Tabs |
Ctrl+Shift+D |
| Bookmark This Page |
Ctrl+D |
| Bookmarks |
Ctrl+B |
| Copy |
Ctrl+C |
| Cut |
Ctrl+X |
| Clear Recent History |
Ctrl+Shift+Del |
| Downloads |
Ctrl+Shift +Y |
| Error Console |
Ctrl+Shift+J |
| Forward |
Alt+Right |
| Close Tab |
Ctrl+W |
| Close Window |
Ctrl+W |
| New Tab |
Ctrl+T |
| New Window |
Ctrl+N |
| Next Tab |
Ctrl+Tab |
| History |
Ctrl+H |
| Open File |
Ctrl+O |
| Page Info |
Ctrl+I |
| Paste |
Ctrl+V |
| Page Source |
Ctrl+U |
| Previous Tab |
Ctrl+Shift+Tab |
| Print |
Ctrl+P |
| Redo |
Ctrl+Y |
| Reload |
F5 or Ctrl+R |
| Reload (override cache) |
Ctrl+Shift+R or Ctrl+F5 |
| Save Page As |
Ctrl+S |
| Select All |
Ctrl+A |
| Select Location Bar |
Alt+D |
| Select Tab (1 to 8 ) |
Alt + ( 1 to 8 ) |
| Select Last Tab |
Alt+9 |
| Toggle Full Screen |
F11 |
| Toggle Private Browsing |
Ctrl+Shift+P |
| Undo |
Ctrl+Z |
| Undo Close Tab |
Ctrl+Shift+T |
| Zoom In |
Ctrl + + |
| Zoom Out |
Ctrl + - |
| Zoom Reset |
Ctrl+0 |
_______________________________
Hitesh Bhatia
hitesh@intelligrape.com
http://in.linkedin.com/in/bhatiahitesh
_______________________________
Tags: firefox, internet, keyboard shortcuts, mozilla
Posted under Uncategorized | No Comments »
July 23rd, 2010
Recently in a Grails project that I am currently working on, the client wanted to have few functionalities of our web application on iPhone as well. We are using Enums heavily in our project and the iPhone development cannot recognize from looking at the tables that few fields are Enums so those need to be one of value of Enum. So they use to store some different value in it as the datatype of Enums in table is varchar the sql doesn’t mind storing the different values.
So after looking at here and there for Enum datatypes for sql we found a very easy solution to do that. We altered few tables like this
alter table documents change document_priority document_priority enum('Critical','Major','Blocker','Backlog') default 'Major';
For adding an Enum column you just need to do something like
alter table documents add column enum('Critical','Major','Blocker','Backlog')
after doing this the user can see that which values the field expect so iPhone development team also get to know what should they do. But it does not restrict user to other values in it though if user tries to add some other value in it the sql will set it to blank(” “). It still doesn’t serves our purpose because in application there is no blank Enum. The solution for this is in the sql_mode. So we set the sql_mode
SET sql_mode = STRICT_TRANS_TABLES
So can see the sql_mode of your database like this
SELECT @@global.sql_mode, @@session.sql_mode;
I hope this helped for some people the only thing I miss in this. I dont get the solution for this in Hibernate. May be there is a solution for this either in Hibernate or in Grails. Looking for the better solution that can be done in the application itself.
## Uday Pratap Singh ##
uday@intelligrape.com
http://www.IntelliGrape.com/
http://in.linkedin.com/in/meudaypratap
Tags: Enum in mysql, Java enums with sql, sql modes, strict values in sql
Posted under Database | No Comments »
July 22nd, 2010
Hi All,
Here are the few basic steps that you need to follow in order to achieve the in-memory session replication between two or more Tomcat 6 instances.
This blog refers the Apache Tomcat documentation as found here: http://tomcat.apache.org/tomcat-6.0-doc/cluster-howto.html.
The Tomcat documentation provides more detailed explanation of the Clustering concepts as well as the definition of tags, attributes etc. used in server.xml file.
Step 1: Include the <distributable> tag in web.xml file i.e. you can simple write the following line in your deployment descriptor(i.e. web.xml):
Please read the following link to know more about this tag: http://wiki.metawerx.net/wiki/Web.xml.Distributable
Step 2: Add the following lines of XML in the server.xml file inside the <Engine> element/tag:
<Engine name="Catalina" defaultHost="localhost">
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager"
expireSessionsOnShutdown="false"
notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService"
address="228.0.0.4"
port="45564"
frequency="500"
dropTime="3000"/>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
address="auto"
port="4000"
autoBind="100"
selectorTimeout="5000"
maxThreads="6"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor
className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
tempDir="/tmp/war-temp/"
deployDir="/tmp/war-deploy/"
watchDir="/tmp/war-listen/"
watchEnabled="false"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
.
.
.
.
</Engine>
Please note that there might be some other elements such as <Host>, <Realm> etc. inside the <Engine> element. Also, for each tomcat instance the value defined for the ‘port’ attribute of the <Receiver> tag must be unique.
And, that’s all. You now have a basic session-replication in place. Your sessions are replicated amongst all the tomcat instances which are part of your cluster.
NOTE: Please make sure if you make any changes to the “context.xml” file, you have to delete the following xml file located in the <TOMCAT_HOME>/conf/Catalina/localhost/{yourAppName}.xml. If you don’t delete this file, then your changes will be ignored and the settings defined in this file will take effect.
Cheers!!!
Abhishek Tejpaul
abhishek@intelligrape.com
[Intelligrape Software Pvt. Ltd.]
Posted under Grails | No Comments »
July 21st, 2010
In one of our recent projects, we needed to save the HTTP session in the database.
This blog refers the Apache documentation as found here: http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html
These are the following steps that need to be followed:
Step 1: Create a database named tomcat (as shown in our example in Step 3 below) or any other name as specified in the ‘connectionURL’ attribute of the <Store> element.
Step 2: Create the following table in the newly created database:
create table sessions (
session_id varchar(100) not null primary key,
valid_session char(1) not null,
max_inactive int not null,
last_access bigint not null,
app_name varchar(255),
session_data mediumblob,
KEY kapp_name(app_name)
);
Step 3: Copy the context.xml file available at the global level at this location: <TOMCAT_HOME>/conf to your application’s META-INF folder and replace the <Manager> element with the following:
<Manager className='org.apache.catalina.session.PersistentManager'
saveOnRestart='false'
minIdelSwap='0'
maxIdleSwap='0'
maxIdleBackup='1'>
<Store className="org.apache.catalina.session.JDBCStore"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/tomcat?user=username&password=password"
sessionTable="sessions"
sessionIdCol="session_id"
sessionDataCol="session_data"
sessionValidCol="valid_session"
sessionMaxInactiveCol="max_inactive"
sessionLastAccessedCol="last_access"
sessionAppCol='app_name' />
</Manager>
If these settings are placed in the ‘<TOMCAT_HOME>/conf/context.xml‘, it will have a global effect on all the applications running on the server. For an application specific setting, you can place a newly created “context.xml” file in the <APP_HOME>/META-INF sub-folder inside the webapps folder.
Please note that attributes used in the <Store> element make use of the table columns as created in the database in Step 2.
Step 4: Set the following system properties named – ‘org.apache.catalina.session.StandardSession.ACTIVITY_CHECK‘ to ‘true‘.
For further information on this, read the ‘Persistent Manager Implementation’ section at this link : http://tomcat.apache.org/tomcat-6.0-doc/config/manager.html
Step 5: Make sure you have placed the MySql jar in the <TOMCAT_HOME>/lib folder.
Now you can try to hit the application’s URL and check the database table to see the newly persisted session. Please note that it takes around 60 seconds to see the stored session in the database so you might have to wait a bit. You can have multiple instances of tomcat running your application pointing to the same database and can share this persisted session in case any of the tomcat instance crashes.
NOTE: Please make sure if you make any changes to the “context.xml” file, you have to delete the following xml file located in the <TOMCAT_HOME>/conf/Catalina/localhost/{yourAppName}.xml. If you don’t delete this file, then your changes will be ignored and the settings defined in this file will take effect.
Cheers!!!
Abhishek & Imran
abhishek@intelligrape.com | imran@intelligrape.com
[Intelligrape Software Pvt. Ltd.]
Tags: Grails, HTTP session, JDBCStore, session persistence, tomcat
Posted under Database, Grails | No Comments »
July 15th, 2010
On most of my grails projects, I am used to let grails handle database schema creation for me. However, there is a project where the database is shared between multiple applications. In that project, we have to check-in our table creation/modification script as a SQL file, which is later executed by a DBA.
However, there are cases, where I do need to create new domain classes and check-in the DDL scripts separately.
I use a not-so-commonly known Grails command/script schema-export to help me deal me with this situation without much fuss of writing the DDL script myself.
After creating my domain class as I want, I simply execute the following command to get the table creation script for me:
> grails schema-export
For example:
> grails schema-export com.blah.Person
The DDL script in this case will be created in the project root as com.blah.Person.sql.
If you simply want to see the script on the console:
> grails schema-export Person stdout
If you want DDL script for all the domain classes
> grails schema-export
The DDL script in this case is created as {PROJECT_ROOT}/target/ddl.sql file.
Hope this helps!
-Deepak
Posted under Database, Grails | No Comments »
July 14th, 2010
Rcconf is a tool that we recently discovered. This tool allows you to manage your start-up applications easily.
We found this tool when me and my colleague Aman were trying to identify the processes that we never use but they do eat up a lot of our system resources. We found this link very useful: http://www.debianadmin.com/manage-linux-init-or-startup-scripts.html.
The other way to manage system start-up applications is as the page suggests, by using update-rc.d, but rcconf provides an interface which is easy to understand and use.
To install rcconf, run the following command on your command line:
sudo apt-get install rcconf
To run rcconf, you’ll need sudo privileges:
sudo rcconf
The application looks like :

* means that application is a part of startup
Use spacebar to uncheck the application
Save the settings and restart your linux box. I removed unused applications like postgres, tomcat, monit, bluetooth etc.
And my system does feel a bit faster
Regards
~~Himanshu Seth~~
http://www.IntelliGrape.com
Tags: Linux, rcconf, startup applications
Posted under Linux, System | No Comments »
July 14th, 2010
While using searchable plugin for the first time, I wasn’t aware that lucene implements only lexicographic comparisons for searching on indexed values (even on numeric fields). Before I learned this, I kept on wondering why a Person of age 6 always appeared in search results when I look for People more than 20 years of age. The solution was to define a transient field ageIndexValue in domain class Person and implement its getter as:
String getAgeIndexValue() {
return org.apache.lucene.document.NumberTools.NumberTools.longToString(this.age)
}
Also, you will need to change the search query from
q=age:[20 TO *] to q=ageIndexValue:[0000000000000u TO *]
where, 0000000000000u == org.apache.lucene.document.NumberTools.NumberTools.longToString(20L)
~Aman Aggarwal
aman@intelligrape.com
http://www.IntelliGrape.com/
Tags: Grails, long, lucene, number, numbertools, numeric, plugin, search, searchable
Posted under Grails | No Comments »