Freemarker sucks, dependency on javax.swing, Wouldn’t run on GAE

I would say freemarker sucks.
Yes it does. A template engine has dependency on javax.swing !!
Isnt that surprising?

Today, I was trying to deploy a Stripe/Freemarker hello world app on GAE and I got following.


java.lang.NoClassDefFoundError: javax.swing.tree.TreeNode is a restricted class. Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at freemarker.core.TextBlock.isIgnorable(TextBlock.java:375)
at freemarker.core.TemplateElement.postParseCleanup(TemplateElement.java:240)
at freemarker.core.MixedContent.postParseCleanup(MixedContent.java:76)
at freemarker.core.FMParser.Root(FMParser.java:2961)
at freemarker.template.Template.(Template.java:149)
at freemarker.cache.TemplateCache.loadTemplate(TemplateCache.java:448)
at freemarker.cache.TemplateCache.getTemplate(TemplateCache.java:361)
at freemarker.cache.TemplateCache.getTemplate(TemplateCache.java:235)
at freemarker.template.Configuration.getTemplate(Configuration.java:487)
at freemarker.core.Environment.getTemplateForInclusion(Environment.java:1465)
at freemarker.core.Include.accept(Include.java:157)
at freemarker.core.Environment.visit(Environment.java:210)
at freemarker.core.MixedContent.accept(MixedContent.java:92)
at freemarker.core.Environment.visit(Environment.java:210)
at freemarker.core.Environment.process(Environment.java:190)
at freemarker.template.Template.process(Template.java:237)
at freemarker.ext.servlet.FreemarkerServlet.process(FreemarkerServlet.java:452)
at freemarker.ext.servlet.FreemarkerServlet.doGet(FreemarkerServlet.java:391)
.........
........

Yes, you can not use freemarker on GAE, at least not without hacking it.

I found a patch here, seems that it would solve above exception.

http://groups.google.com/group/google-appengine-java/browse_thread/thread/dd84e44f604498c4

Who knows that it wouldn’t have dependency on more classes. we can just hope for good.

updates
Nope, above solution isn’t going to work all the time.
I had a quick look at the code, I think that the culprit is here.


abstract public class TemplateElement extends TemplateObject implements TreeNode

From the code, it seems that TemplateElement implements TreeNode
Just because it needs contract similar to TreeNode but it does not have any thing to do with swing API. (You already knew that)
Instead of implementing TreeNode, author could have created a new interface which exposes similar contract.

Do we implement any interface which exposes similar contract that we need? Context matters. EJB spec has some interface with methods that a servlet want doesn’t mean it can be implemented by a servlet.

Hope, devs would fix it in next release.
The issue is discussed in mailing list here http://n4.nabble.com/Dependeny-on-javax-swing-td978818.html

At the end, I would like to say, I like freemarker and that’s why I wrote even a hello world stripe application in freemarker.

Update 26/03/2010

Friends at freemarker has released a Freemarker GAE prerelease which can be downloaded here. It should work on GAE.  Any one interested in running freemarker on GAE should try it and report issues if any.

see  freemarker on GAE too.

update 28/04/2010

No, still freemarker-gae-pre2 will not work on GAE, I have tested it on GAE 1.3.2.  You will get one or both of the following exceptions

java.lang.VerifyError: (class: freemarker/ext/jsp/FreeMarkerJspApplicationContext, method: signature: ()V) Incompatible argument to function

OR

java.lang.NoClassDefFoundError: Could not initialize class freemarker.ext.jsp.PageContextFactory

See this thread and this thread . The issue has been reported to GAE team here vote for it.

Waiting for the freemarker or GAE team to come up with explanation/solution.

Advertisements

DDD Without any ORM tool, is it possible !!

DDD Without any ORM tool, is it possible !!

When reading DDD book and trying out it on a sample project that doesn’t use any ORM tool. I came across a question, is it possible to strictly implement DDD without any ORM tool !

Is there any one here who has implemented DDD on any real project that doesn’t use any ORM but pure JDBC only?

Before few days, I had a question on how to paginate and lazy load non root objects http://tech.groups.yahoo.com/group/domaindrivendesign/message/15925

Various alternatives and answers came up, but why do I need to find an alternative ! I don’t need to do any thing specific when using hibernate and just depend on the lazy loading support provided by it.

I want to paginate because I don’t want to load entire graph of few thousand objects into memory and when using hibernate and lazy loading that’s not an issue. With NO-ORM, I can achieve similar thing by hand coding dynamic proxies for lazy loading, and let repositories handle it.

However the second point is more important.

The second question is related to repositories, transitive persistence and dirty checking.
The DDD book (Chapter 6 – repositories) says “it allows freely switching persistence strategies at any time.”

Is it really possible and easy without modifying domain at all !

How about dirty checking and persistence by reachability without any ORM ?
When you save/update an aggregate root, entire graph should be saved and/or updated. How the repository will determine which objects are modified/inserted or deleted?

Probably you will need some thing like isNew() isStale() inside every entities to find out if it needs to be included as part of insert/update. And set flags when ever any setter or any other method changes state of the object. I have seen similar thing in a project which uses DDD with JDBC.

Several answers came up

Get the data from the database and determine updates, deletes, and inserts in code.

This may not be the best routine, but I use a boolean flag to determine what needs persisted. I have a property in each entity called .IsDirty. When anything inside the aggregate root needs persisted, I use the root’s repository and call root.Persist and I go through the root. The root repository then loops through each entity and tests the .IsDirty flag

Do you see any pattern in this answers ?

  • It says either modify your domain model or write some thing like your little ORM to do this things.
  • That says DDD is tightly bound to ORM and “Freely switching of persistence technology” means switching from one ORM to another (it could be your own).

How about Delete?
Lets say root has a collection of associated entities (In my example MessageFolder has Collection of messages)

I can do some thing like
MessageFolder.remove(Message message)

That would remove message from the collection. When saving the MessageFolder, how the repository can find out what messages are deleted? Either message folder need to maintain a collection of removed messages or repository need to have old message folder for comparision. The first option forces me to modify MessageFolder, that mean domain model became aware of underlying persistence technology. The second option would need to load old entity which would affect performance.

It might be possible to switch to ORM from a No-ORM application but what about switching to NO-ORM from ORM ! Does that mean I will have to add custom behavior to my entities to figure out weather they are new or modified or deleted.

These are few questions that I am not able to answer my self and seeking some expert thoughts. If you have done DDD for a real life project that does not use any ORM, please comment.

Some people said CQRS and Domain events can solve this problem, however I am yet to find a working example.

There is a sample DDD application created by DDD community. The sample application uses Hibernate in persistence layer.
I wish some day DDD community would release a sample application that works on pure JDBC. As still there are lots of companies who use bare JDBC and no ORM at all.

Look at the thread http://tech.groups.yahoo.com/group/domaindrivendesign/message/16021

CentOS: Server refused to allocate pty

The Problem
When I tried to login to my VPS using putty, It gave me message.

Server refused to allocate pty

And then I was not able to execute any commands.

The solution
Execute following two commands, and it should solve the problem.


/sbin/MAKEDEV pty
/sbin/MAKEDEV tty

I am using lxadmin, so I logged into lxadmin and run above commands from command center.
That’s it ! It works.

Foreign key violation when saving embedded forms

The problem

For one of my symfony based project, I required to create embedded forms.

I have following schema


propel:

user:
id: ~
name: {type: varchar(100)}
password: {type: varchar(100)}

registrations:
id: ~
user_id: {type: integer, foreignTable: user, foreignReference: id, required: true}


Schema shown above is not complete, it just shows important fields only.
I generated model and form classes using propel:build-all task, and then embedded UserForm into RegistrationsForm as follow.


class RegistrationsForm extends BaseRegistrationsForm
{
public function configure()
{
unset($this['user_id']);
$user = $this->getObject()->getUser();
$userform = new UserForm($user);
$this->embedForm("User", $userform);
}
}

It works when updating an existing Registration, but when creating new registration, user_id is not set on new Registration, so no association is made between Registration and user and it gave exception of foreign key constraint violation.

The solution

So what was I doing wrong?


$user = $this->getObject()->getUser();
$userform = new UserForm($user);

This was the wrong way to create new UserForm. It works when updating an existing registration, because the user is already associated with Registration so $this->getObject()->getUser() will return an instance of User.

It won’t work when creating new Registration as $user = $this->getObject()->getUser(); will return null.
You need to check if User is null, then create a new user and set it on Registration.

Correct code


class RegistrationsForm extends BaseRegistrationsForm
{
public function configure()
{
unset($this['user_id']);
$user = $this->getObject()->getUser();
if(is_null($user)) {
$user = new User();
$this->getObject()->setUser($user);
}

$userform = new UserForm($user);
$this->embedForm(“User”, $userform);
}
}

That’s it.. it works like a charm.

ubuntu: install multimedia codecs without internet connection

Problem: You can’t play certain audio/video formats, because required codecs are not installed. So you need to install this extras but again, your machine don’t have direct internet connection.

Solution:
I am still looking for solution. if you have any, let me know.

I think this can solve it http://crashsystems.net/2009/01/keryx-tutorial/
Still trying out and not sure, if it provide an alternative.

Javascript CSV parser


var expr = /,(?=(?:[^\"]*\”[^\"]*\”)*(?![^\"]*\”))/g;
var array = str.split(expr);

it works for me


function parseLineCSV(lineCSV) {
// parse csv line by line into array
var CSV = new Array();

// Insert space before character ",". This is to anticipate 'split' in IE
// try this:
//
// var a=",,,a,,b,,c,,,,d";
// a=a.split(/\,/g);
// document.write(a.length);
//
// You will see unexpected result!
//
lineCSV = lineCSV.replace(/,/g," ,");

lineCSV = lineCSV.split(/,/g);

// This is continuing of 'split' issue in IE
// remove all trailing space in each field
for (var i=0;i
<lineCSV.length;i++) {
lineCSV[i] = lineCSV[i].replace(/\s*$/g,"");
}

lineCSV[lineCSV.length-1]=lineCSV[lineCSV.length-1].replace(/^\s*|\s*$/g,"");
var fstart = -1;

for (var i=0;i=0) {
for (var j=fstart+1;j<=i;j++) {
lineCSV[fstart]=lineCSV[fstart]+","+lineCSV[j];
lineCSV[j]="-DELETED-";
}
fstart=-1;
}
}
fstart = (lineCSV[i].match(/^"/)) ? i : fstart;
}

var j=0;

for (var i=0;i
<lineCSV.length;i++) {
if (lineCSV[i]!="-DELETED-") {
CSV[j] = lineCSV[i];
CSV[j] = CSV[j].replace(/^\s*|\s*$/g,""); // remove leading & trailing space
CSV[j] = CSV[j].replace(/^"|"$/g,""); // remove " on the beginning and end
CSV[j] = CSV[j].replace(/""/g,'"'); // replace "" with "
j++;
}
}

return CSV;
}

It works for me, I got it from here http://purbayubudi.wordpress.com/2008/11/09/csv-parser-using-javascript/

SVN commit failed: Property “svn:needs-lock” needed

Error description: Can not commit binary files into SVN repository.

Error message:
A repository hook failed
svn: Commit failed (details follow):
svn: MERGE request failed on 'XYZ'
svn: Commit blocked by pre-commit hook (exit code 2) with output:
ERROR: Commit failed for the following reasons:
Property "svn:needs-lock" needed for file "xyz binary file".
Must match regex '.*'.

Look at http://subversion.tigris.org/faq.html#binary-files to see how does subversion handles binary files.

When a file consists of binary data, it’s often difficult or impossible to merge two sets of changes made in parallel by different users. For this reason, Subversion 1.2 and later offers a feature known as locking, often known as “reserved checkouts” in other version control systems.

Once a file is locked by an user, another user can not commit it.

svn:needs-lock property
If the property is attached to a file (the value is irrelevant), then the file will have read-only permissions. When the user locks the file and receives a lock token, the file becomes read-write. When the lock is released—either explicitly unlocked, or released via commit—the file returns to read-only again.

Binary files must have this property, otherwise it can not be committed. the value of this property is irrelevant.

Look at http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html it explains SVN locking model

Solution
Add the svn:needs-lock property to the file in question. The SVN property can be set using SVN client like tortoise or using SVN propset sub command from command prompt.

svn propset svn:needs-lock '*' file name

For more information on SVN properties, look at http://svnbook.red-bean.com/en/1.4/svn.advanced.props.html

That’s it, try to commit it.

Eclipse project missing java builder

Description: Eclipse can not build the project, because  project is missing default builder.  It happens most of the time when checking out project from SVN or CVS.

Solution:  You need to add the default Java builder into .project file.

Verify that following lines are present in .project file of the eclipse project. If it is not present in the file, copy it from here and save the file.

Adding default Java builder


<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>

That’s it! select the Java builder from project propertiese > builder, clean and build the project again. you should be able to build the project now.

SSLHandshakeException: When trying trying to access a HTTPS URL

I was trying to access a HTTPS URL using java.net.HttpURLConnection and got following error.

Error
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Most of the time, this exception occurs when you are using selfsigned certificate.

Reason:  The host that you are trying to connect has an self signed certificate, and that certificate is not in your truststore.

Description:
Actually I am using the tomcat server and I have enabled HTTPS connector. I have created a selfsigned certificate for the tomcat.

I have a standalone Java program which connects to the server and downloads file over HTTPS. But when I try to connect to the server, it threw SSLHandshakeException.

Solution:  Solution to resolve this exception is to import the selfsigned certificate into the system truststore.
Below steps explains how to do it.

Step-1: Export the certificate.

Export your self signed certificate using keytool utility provided with JDK.open the command prompt and change current directory to JAVA_HOME/bin. Now run following command.

keytool -export -alias tomcat -storepass changeit  -file tomcat.cer

It will create a tomcat.cer file in the current directory.

Note: You may need to modify -alias and -storepass options if required. Default keystore  password is ‘changeit’.

Step-2: Import the certificate into truststore.

keytool -import -alias tomcat -file tomcat.cer -keystore <path to JAVA_HOME>\jre\lib\security\cacerts
or
keytool -import -alias tomcat -file tomcat.cer -keystore ..\jre\lib\security\cacerts

It will ask you to enter keystore password. Default password is ‘changeit’.  when it ask, ‘Trust this certificate?’, type yes and press enter.

Step-3: Verify that the certificate is added successfully

keytool -list -keystore C:\j2sdk1.4.2_16\jre\lib\security\cacerts

It will list all the certificate. verify that the certificate you just added is present in list.

That’s it! now run your program again.

Could not perform XSLT transformation. Make sure PHP has been compiled/configured to support XSLT.

Error when running symfony on wamp server.

Description:   I was trying to run the symfony PHP framework. I tried to build the model using command
php symfony propel:build-model.

And it gave error Could not perform XSLT transformation. Make sure PHP has been compiled/configured to support XSLT.

Environment: Wamp server 2.0, PHP 5.2.5, Apache 2.2.6.

Reason: PHP-XSL extension is not enabled. By default, Wamp server doesnt enable php-xsl php extension. and php-xsl is required.

Solution: Enable php-xsl extension.

left click on WAMP’s tray icon and than in PHP>PHP extensions select php-xsl and enable it.But there is one more php.ini file, which WAMP won’t change, we need to do it by hand, open: C:\wamp\bin\php\php5.2.5\php.ini and remove “;” from the line

;extension=php_xsl.dll

And then restart the server. Try to run the build command again.

Some useful links to get symfony running properly on wamp.

http://trac.symfony-project.org/wiki/SymfonyOnWAMP

http://anandshahil11.wordpress.com/symfony-php-framwework-installation-on-windows-wamp/