venerdì 13 giugno 2014

Grails and external processes

Often we need to call external scripts from our web application. As an example, i'm developing a web app in Grails which needs to get some data from external sources. In my specific case, i decided to create some php scripts (which i can modify and edit quicker in response to external changes) to gather some informations. So my webapp will call these scripts and these scripts will pass the results back to Grails, as a json params for a Grails controller call.

Grails provide some incredibly easy ways to create and launch external processes. Simply define a string and call execute on it and you will have started an external process!


def command = "php " + pathToPhpFolder + "/my_script.php $myParam1 $myParam2";
command.execute();


This is the simpler approach, but it is not perfect because you may have problems with the params you pass, especially if they contains spaces. So a more safer (but still very easy) way is this:

def command = ["php", pathToPhpFolder + "/uploader.php", myParam1, myParam2];
command.execute();

These way all the parameters will be passed exactly as parameters, even if they contains spaces.

Process control

You may want to manage the external process and, for example, kill it if it goes in timeout. Here is the easy way:

def process = command.execute();
process.waitForOrKill(MY_TIMEOUT);

These instructions will launch the process and wait for a MY_TIMEOUT time before killing the process. The only things not exactly nice is that if the process timeouts, you will not have any exception so you may need to implement a way to determine if the process completed correctly or if it was killed (i use a status variable).

That's all!

Now that you have read my article, i would like to show you another thing: i've developed an app to help increase customers registration and customers conversion.

You can find it at appromocodes.com

Nessun commento:

Posta un commento