This website uses cookies to ensure you get the best experience. Learn More.
Custom Java Tools for Liferay 6.0 Script Engine
package com.myscriptutil; public interface MyScriptUtil { public String operationOne(); public String operationTwo(String name); }
package com.myscriptutil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; public class MyScriptUtilImpl implements MyScriptUtil { @Override public String operationOne() { return "Hello out there!"; } @Overrid public String operationTwo(String name) { _log.debug("Inside of Operation Two"); return "Hello " + name + "!"; } private static Log _log = LogFactoryUtil.getLog(MyScriptUtilImpl.class); }
Create a file named applicationContext.xml in the docroot/WEB-INF directory and add the following:
applicationContext.xml
docroot/WEB-INF
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="com.liferay.samples.ScriptUtil" class="com.liferay.samples.ScriptUtilImpl" /> </beans>
We need to make an update to web.xml to be sure Liferay creates a BeanLocator object and reads our bean definitions.
web.xml
<?xml version="1.0"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <listener> <listener-class>com.liferay.portal.kernel.spring.context.PortletContextLoaderListener</listener-class> </listener> </web-app>
At this point, we're ready to deploy our hook and make our custom utility available for use. Up to here, we've followed the steps from Ray's blog exactly and we could make use of our utility in Veloctiy using the syntax he describes. However, if we want to use our utility in the script engine, we'll have to use a slightly different syntax.
Once the hook has successfully deployed, log into the portal as an administrator and navigate to the Control Panel. From the Control Panel, navigate to the Server Administration section and then the Script tab.
Select Groovy from the Language dropdown and replace the contents of the Script field with:
myUtil = com.liferay.portal.kernel.bean.PortletBeanLocatorUtil.locate("my-script-util-hook", "com.myscriptutil.MyScriptUtil") println(myUtil.operationOne()) println(myUtil.operationTwo("Joe Bloggs"))
Execute the script and you should see output on the screen. If you're not using 6.0 EE SP2, you may not see the output directly on the screen, you may need to check the log file for your output.
If you want to see the log statement we added, you'll need to update the log levels. Click on the Log Levels tab on the Server Administration page and then select Add Category. In the box, type: com.myscriptutil and then set the log level dropdown to DEBUG. Click Save and then go back to the Script tab and run the script again. This time you should get a log message in the log file.