Saturday, December 6, 2014

How to increase JBoss Server memory and heap size when running JBoss with Eclipse Server Plugin

1. in Server view, double click on the selected configured JBoss runtime

2. click on Open launch configuration

3. in the VM arguments section, change to the desired settings

4. Click OK when finish editing the VM arguments.


Done!!

Wednesday, December 3, 2014

How to increase Web Pool to handle more requests in JBoss AS7

Web Pool is important in an Application Server,
if it is not configure properly, the server performance would be affected when huge number of requests coming into the server.

By default, the web pool in JBoss is not created.
Below are the steps to create Web Pool in JBoss

Steps
1. open <JBoss_HOME>/standalone/configuration/standalone.xml

2. find subsystem for "urn:jboss:domain:threads:1.1"

3. add thread factory to the subsystem

<thread-factory name="http-connector-factory" thread-name-pattern="HTTP-%t" priority="9" group-name="uq-thread-pool"/>

4. create an executor in the subsystem

<unbounded-queue-thread-pool name="uq-thread-pool">
    <thread-factory name="http-connector-factory" />
    <max-threads count="10" />
    <keepalive-time time="30" unit="seconds" />
</unbounded-queue-thread-pool>

5. search for connector name="http"

6. bind the executor created in step 3 to the http connector

<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" executor="uq-thread-pool" />

reference: https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.3/html/Administration_and_Configuration_Guide/sect-Connector_Configuration.html


Done!!


Monday, November 17, 2014

How to replace HTML tag with ant

To replace a word or character with Ant,
we can use the following command.

<replaceregexp file="{FILE_TO_REPLACE}"
    match="{WORD_TO_REPLACE}"
    replace="{WORD}" flags="g" byline="true" />

But the above command can use to replace words withouth xml/html reserved characters only.
To replace words with xml/html reserved characters,

Steps:
1. encode the xml/html reserved words before putting into the the <replaceregexp /> command.
eg, <a>link</link>  =>  &lt;a&gt;link&lt;/a&gt;

2. put the encoded words into <replaceregexp />
eg,

<replaceregexp file="{FILE_TO_REPLACE}"
    match="&lt;a&gt;link&lt;/a&gt;"
    replace="&lt;a&gt;new_link&lt;/a&gt;" flags="g" byline="true" />


Done!!

Saturday, November 8, 2014

Scheduling with EJB

There is an easier way to schedule a job with EJB.
What we need is the EJB implementation and most important is the action method to be run.

@Stateless(name="serviceLookupName", mappedName="serviceLookupName")
public MyEjbServiceImpl {

    @Override
    @Schedule(dayOfMonth = "*", hour = "00", minute = "01")
    public void myScheduledMethod() {
       
        // action to run

    }
}


The advantage of this EJB schedule is easy to implement,
as just need to add the @Schedule annotation to an EJB method.

But the disadvantage is the scheduled time is hard to change,
if user wishes to change the time for the scheduler to run,
the source code need to be changed, recompile, and deploy.

for more information about the scheduler, please refer the official page.


Done!!

Thursday, November 6, 2014

reading java.util.List in velocity template

Assuming a list pass to the Velocity context.


List list = new ArrayList();
list.add("item1");
list.add("item2");
list.add("item3");

VelocityContext context = new VelocityContext();
context.put("list", list);


To get the list value,
below is the syntax in Velocity template

$list.get(0)

$list.get(1)

$list.get(2)


Done!!

Wednesday, November 5, 2014

How to convert sql date to util date


private String convertSqlDateToUtilDate(java.sql.Timestamp sqlDate) {

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

Calendar utilDate = Calendar.getInstance();

utilDate.setTimeInMillis(sqlDate.getTime());

return sdf.format(utilDate.getTime());

}

Tuesday, October 28, 2014

Loop index in Apache Velocity

To get the loop index in Velocity template,
we need to initiate a temporary index variable, and increase the variable count by 1 after every occurrence in the loop.

#set( $count = 1 )
<table>
#foreach( $customer in $customers )
    <tr>
        <td>$count</td>
        <td>$customer.name</td>
        <td>$customer.age</td>
    </tr>
#set( $count = $count + 1 )
#end
</table>

the idea is what we have in the for loop.
int count = 1;
for(Customer c : customerList) {
    print(...);
    count++;
}


Done!!

How to disable row selection in PrimeFaces datatable

This is not a official/proper way to disable the row selection in <p:dataTable />
But a workaround since there is no way to disable the row selection at the moment.

assuming we have the following dataTable.
<p:dataTable
    value="#{myBean.resultList}"
    selection="#{myBean.selection}"
    var="var"
    ..... />

    <p:column selectionMode="multiple" />
    <p:column .... />

</p:dataTable>

To disable row selection in the above <p:dataTable />
we need to add <p:ajax /> into the <p:dataTable />

Thursday, October 23, 2014

How to check system configured properties in Liferay

There are a lot of  properties/attributes configured in Liferay.
All these configured System Properties and Portal Properties could be accessed through Server Administration.

1. Login as Liferay Administrator

2. Liferay 6.1.x
    Go to > Control Panel > Server > Server Administration > Properties

Wednesday, October 22, 2014

How to set max date and min date in <p:calendar />

The maxdate and mindate attribute is extremely useful for setting available date range for user selection.

e.g.
-Expiry date of an item should not be less than today.
-Date of birth should not be future date.

So how to set maxdate and mindate in PrimeFaces calendar component?

1. create the java.util.date object in backingBean
private Date currentDate = new Date();

public Date getCurrentDate() {

    return currentDate;
}

2. set the java.util.date object as mindate or maxdate
<p:calendar value="#{bean.expiryDate}" mindate="#{bean.currentDate}" />
 

<p:calendar value="#{bean.birthDate}" maxdate="#{bean.currentDate}" />


Done!!

Tuesday, October 21, 2014

How to display dynamic PDF document with <p:media /> component

From the PrimeFaces showcase, the media component used to display PDF document
But the showcase uses a static PDF document.

In real life, we might want to display different PDF documents by different use cases,
or a runtime generated PDF document.

To achieve the above purpose, we need to use the value attribute in <p:media /> component by passing in a StreamedContent from backingBean.

1. BackingBean method that return StreamedContent.
public StreamedContent getPdfDocument() {  

     // logic to generate the PDF  

    return new DefaultStreamedContent(pdfInByteArrayInputStream, "application/pdf");
}


2. display the PDF content with <p:media /> component.

<p:media value="#{myBean.pdfDocument}" width="100%" height="500px" player="pdf" />


Done!!

Tuesday, October 14, 2014

How to shutdown Liferay with warning and timeout to the users

There is a smarter way to shutdown Liferay.
Where Liferay allowed the system administration to enter the shutdown time and warn all logged in users regarding shutdown of the Portal.
Thus, all logged in users can quickly save their works without losing any data.

Platform: Liferay 6.2.x

Steps:
1. Login as Liferay Admin
2. Admin > Control Panel > Configuration > Server Administration > Shutdown

Wednesday, August 27, 2014

How to define Default Action in PrimeFaces

This is to define what action to be executed when the "Enter" is press.

There is easy-to-use component in PrimeFaces to get this done.


<p:defaultCommand target="btn2" />

<p:commandButton id="btn1" action="#{myBean.action1}" />
<p:commandButton id="btn2" action="#{myBean.action2}" />
<p:commandButton id="btn3" action="#{myBean.action3}" />

with the above code, when user press on "Enter", action to be executed is #{myBean.action2} that bind to <p:commandButton id="btn2" />


Done!!

Thursday, August 14, 2014

How to quickily clone an object in java

To quickly clone an java object, including all the children and relationships.
may consider to use SerializationUtils in Apache Commons Lang.

it's just easy with  1 line of code

MyObject newObject = (MyObject) SerializationUtils.clone(objectToClone);


Done!!

Thursday, August 7, 2014

Liferay admin password used in Liferay Web Service

Recently discovered that the Liferay admin's password used for the Liferay remote services.
must be without "@".

Liferay API will extract from "@" until the "/" to be the target service host.

eg. adminPassword@127.0.0.1:8080/api/axis
meaning from the above example, 127.0.0.1:8080 will be extracted as the target host.

somehow if the adminPassword contains "@", the API will extract from the adminPassword.

eg: adminP@ssword@127.0.0.1:8080/api/axis
now the host becomes @ssword@127.0.0.1:8080.

with this adminP@ssword, Liferay API will throw an unknownHostException.

conclusion, @ not allowed in the Liferay Admin password to be used in Liferay web service.


Done!!

Wednesday, August 6, 2014

Soft Delete with JPA and EclipseLink

Assuming I have the following table.

And my entity
@Entity
@Table(name="ITEM")
public class Item {
    private Long itemId;
    private String itemName;
    private Integer itemStatus;

    // getter and setter
}

for AUDITING purpose, hard delete is not encouraged.
thus, when deleting a record, the ITEM_STAUS changes to 2 (deleted).

and I have the following status code
0 - active
1 - inactive
2 - deleted

Monday, August 4, 2014

javax.faces.project_stage

There is a new feature introduced in JSF2.x,
Which is the javax.faces.PROJECT_STAGE in the web.xml.

When creating a new JSF2.x project, the default value is “Development”.
When going into Production environment, the value should be changed to “Production”
To reduce logs, and avoid re-download of static resources (js, css, images, etc), and all the static resources will be cached in the client machine.

Besides, if this parameter remove from web.xml, the default value is "Production"

reference,
https://blogs.oracle.com/rlubke/entry/jsf_2_0_new_feature2
https://weblogs.java.net/blog/driscoll/archive/2009/09/28/jsf-20-reminder-project-stage


Done!!

Wednesday, July 30, 2014

How to pass parameters through URL in JSF

To pass parameters through URL in a web application, is to append the parameters into the base URL.

eg, www.google.com?parameter1=value1&parameter2=value2&parameter3=value3.

in JSF, it is nice to pass only 1 parameter through the URL.
When more than 1 parameter pass through the URL, an exception will happen.
Whenever "&" symbol appears in the URL, the exception will happen.

to resolve this problem, what we need to do is to encode the "&" symbol or manually append with the encoded value "&amp;"

eg, www.google.com?parameter1=value1&amp;parameter2=value2&amp;parameter3=value3.


Done!!

Sunday, July 6, 2014

How to get Company Id in Liferay

To check company Id in Liferay, we can check from Portal Instance

1. Login as Liferay Administrator.

2. Go to > Control Panel > Server > Portal Instance


Last but not least, the default Company ID in Liferay 6.1.x is 1, default Company ID in Liferay 6.2.x is 10157.


Done!!

Sunday, June 8, 2014

How to show wider year range in PrimeFaces Calendar

By default, the year range is 10 years before and 10 years after.

as shown above, this year is 2014, the year range can only in between 2004-2024.

to display wider range, need to enable the yearRange attribute.

<p:calendar id="pfc1"
    yearRange="c-50:c+10"
    showOn="button"
    navigator="true" />

with the above yearRange settings, the year can display up to 50 years before and 10 years after.
Meaning current year -50 and current + 10.


Done!!

Monday, May 26, 2014

How to invoke javascript from Managed Bean in PrimeFaces

In PrimeFaces, we can invoke a javascript function from managed bean.
One of the good example is to keep dialog open when validation exception.

Besides, other javascript function can be called.
code in xhtml

<p:commandButton value="Call JS from MB" action="#{myBean.callJsFromMB}" />

code in managed bean

public void callJsFromMB() {
    // other business logic or validation
    RequestContext.getCurrentInstance().execute("alert('test')");
}


Done!!

Sunday, May 25, 2014

Adding Footer and Header into PDF with iText

iText version - 2.1.7

Header/Footer only
Document document = new Document();
HeaderFooter header = new HeaderFooter(new Phrase("This is header"), false);
HeaderFooter footer = new HeaderFooter(new Phrase("This is footer"), false);
document.setHeader(header);
document.setFooter(footer);


Header/Footer with page number
Document document = new Document();
HeaderFooter header = new HeaderFooter(new Phrase("This is header"), true);
HeaderFooter footer = new HeaderFooter(new Phrase("This is footer"), true);
document.setHeader(header);
document.setFooter(footer);


Header/Footer with font
Document document = new Document();
Font font = new Font(Font.TIMES_ROMAN, 11);  // font family, font size
HeaderFooter header = new HeaderFooter(new Phrase("This is header", font), true);
HeaderFooter footer =new HeaderFooter(new Phrase("This is footer", font), false);
document.setHeader(header);
document.setFooter(footer);


Done!!

Saturday, May 17, 2014

How to integrate SlidesJS into JSF2

SlidesJS is an image slider that is nice and easy to implement.
To implement SlidesJS into JSF2.x application, just need to download the required files and follow the steps below.

1. copy all the required files into resources folder.

Wednesday, May 14, 2014

How to change Liferay Portlet title with jQuery

In some cases, we might want to change the Portlet title, So that the title is more meaningful the the Portlet content.
eg. screen navigates from search page to maintenance page.


$('#idOfDeployedPortlet').find('.portlet-title-text').html('new title');


idOfDeployedPortlet - portlet id deployed in Liferay, if you do not know how to get the deployed portlet id, please refer this post.
new title - Title to be passed in for the target page.

Sunday, May 11, 2014

Synchronization between data model and data dictionary in Oracle SQL Developer Data Modeler

This post is regarding how to synchronize data model and the connected data dictionary in Oracle SQL Developer Data Modeler.

Besides reverse engineering, Oracle SQL Developer Data Modeler is able to synchronize the existing data model with the connected or defined Data Dictionary.
Meaning it's able to update the data model when there are new updates in the schema or vice versa.

Steps to synchronize new updates from schema to data model.

1. Click on Synchronize Model with Data Dictionary

Wednesday, April 30, 2014

How to reverse engineer existing schema with Oracle SQL Developer Data Modeler

Oracle SQL Developer Data Modeler is a very nice tool.
It's very useful on creating Data Model design; besides, it could also help us to reverse engineer the existing schema into Data Model design.
Below are the steps to reverse engineer an existing schema into Data Model.

Steps
1. Goto Data Dictionary Import Wizard
    File > Import > Data Dictionary

2. Choose a Data Dictionary to import
    Choose a configured Data Dictionary from the right table with Connection Name and Connection Details.
    If the expected Data Dictionary is not there, then follow this link to create it.

Monday, April 28, 2014

How to enable CKEditor in PrimeFaces Extension

The CKEditor is not enabled by default when adding PrimeFaces Extension into PrimeFaces application.

There is only a textarea if the CKEditor is not enabled.

Thus, to enable the CKEditor, an additional jar needs to be included -- resources-ckeditor.jar
After added the resources-ckeditor.jar, the CKEditor displayed like below.

resources-ckeditor.jar could be downloaded here.
Besides, remember to check the correct version of PrimeFaces Extension using in the system to avoid any unexpected issues.

Update for PrimeFaces5.1
- List of library required to use CKEditor with PF5.1


Done!!

Friday, April 25, 2014

How to define Category for custom portlet in Liferay

When we deploying portlets into Liferay portal, somehow we need to define new Category Name for our customized portlets instead of just place all the portlet under Sample.
Below are the steps how to define new Category in Liferay portal.

1. Open liferay-display.xml
<?xml version="1.0"?>
<!DOCTYPE display PUBLIC "-//Liferay//DTD Display 6.1.0//EN" "http://www.liferay.com/dtd/liferay-display_6_1_0.dtd">

<display>
 <category name="category.sample">
  <portlet id="primefaces" />
 </category>
</display>

Thursday, April 17, 2014

Possible ways to hide/show Portlet border in Liferay

There are several ways to hide/show portlet border in Liferay.
1. Configure in every portlet.
To show/hide portlet border in every individual portlet, detailed steps shown in previous post.

2. Configure in theme;
All portlets within the configured theme will be show/hide border by default.
add the following line into liferay-look-and-feel.xml
the value is either true or false.
<theme id="myTheme" name="myTheme" >
    <settings>
        <setting key="portlet-setup-show-borders-default" value="true|false" />
    </settings>
     .............................................
     .............................................
</theme>

3. Configure in portal-ext.properties;
All portlets will be show/hide border by default
add the following line into portal-ext.properties
the value is either true or false.

theme.portlet.decorate.default=true|false



Done!!

Sunday, April 13, 2014

Adding second, minute, hour, day to java.util.date


long secondInMilis  = 1000;
long minuteInMilis  = secondInMilis * 60;
long hourInMilis  = minuteInMilis * 60;
long dayInMilis  = hourInMilis * 24;

Date add1Second = new Date(new Date().getTime() + secondInMilis);
Date add10Second = new Date(new Date().getTime() + (10 * secondInMilis));

Date add1Minute = new Date(new Date().getTime() + minuteInMilis);
Date add10Minute = new Date(new Date().getTime() + (10 * minuteInMilis));

Date add1Hour = new Date(new Date().getTime() + hourInMilis);
Date add10Hour = new Date(new Date().getTime() + (10 * hourInMilis));

Date add1Day = new Date(new Date().getTime() + dayInMilis);
Date add10Day = new Date(new Date().getTime() + (10 * dayInMilis));


Done!!

How to increase memory and heap size in Eclipse

The default configuration in Eclipse is maximum memory 512mb, and heap size 256mb.
But that is normally not enough especially running server plugin in Eclipse, eg, Tomcat, JBoss

To run the server plugin smoothly, we need to increase the memory and heap size as below.

1. Open eclipse.ini in <Eclipse_installation_dir>

2. edit the memory and heap size to expected settings


Done!!

Saturday, March 29, 2014

How to change fonts in Eclipse

1. Open Preferences dialog
    Window > Preferences

2. Go to Colors and Fonts
    General > Appearance > Colors and Fonts

3. Choose Java > Java Editor Text Font

4. Edit

5. Choose preferred font, size, color

6. OK > OK


Done!!

Wednesday, March 26, 2014

How to generate styled PDF in Liferay PrimeFaces Portlet with iText

In the previous post,
How to generate PDF in Liferay PrimeFaces Portlet with iText shows how to generate a PDF document, unfortunately, the generated PDF is not able to handle style class.

eg,
<!DOCTYPE HTML><html><body>Generate <strong>PDF</strong> Test</body></html>
can be generated without any problem. 

but, 
<!DOCTYPE HTML><html><body>Generate <span style='color: red;'>PDF</span> Test</body></html>
is unable to generate the text with red color.

Sunday, March 23, 2014

JSTL namespace in JSF2.x

Remember to use "http://java.sun.com/jsp/jstl/core" instead of "http://java.sun.com/jstl/core" in JSF2.x

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:c="http://java.sun.com/jsp/jstl/core">    

    ................................

</ui:composition>


Done!!

How to support multiple languages for Portlet category in Liferay

As a CMS, Liferay allows us to deploy our custom portlet, and also define category for the custom portlet.

We can actually define category for all my custom portlets. eg, My Category Name.
Besides, we also can make the custom category name to support multi-languages with resource bundle.

Steps:

Wednesday, March 12, 2014

java.lang.ClassNotFoundException: com.sun.crypto.provider.SunJCE from [Module "deployment.ROOT.war:main" from Service Module Loader]

Where using Liferay 6.1.1 with JBoss AS 7.1.1, the following exception could be happen.

17:38:10,244 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/].[jsp]] (http-localhost-127.0.0.1-8080-2) Servlet.service() for servlet jsp threw exception: java.lang.ClassNotFoundException: com.sun.crypto.provider.SunJCE from [Module "deployment.ROOT.war:main" from Service Module Loader]
 at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190) [jboss-modules.jar:1.1.1.GA]
 at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468) [jboss-modules.jar:1.1.1.GA]
 at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456) [jboss-modules.jar:1.1.1.GA]
 at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398) [jboss-modules.jar:1.1.1.GA]
 at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120) [jboss-modules.jar:1.1.1.GA]

Tuesday, March 4, 2014

How to resolve jQuery conflict in Liferay

In some cases, we need to install jQuery in Liferay especially the custom theme to achieve some UI features.
But that could be conflict with jQuery that come along with custom portlet.
eg, RichFaces portlet, PrimeFaces portlet, IceFaces portlet.

as long as we add the following line of code in Liferay theme,
then the conflict could be resolved.

jQuery.noConflict(true)


Done!!

Sunday, March 2, 2014

How to pass parameters with <a4j:jsFunction />

<a4j:jsFunction /> allowed us to send JSF ajax request with javascript function.

sample
<a4j:commandButton
    value="TEST"
    action="#{myBean.action}"
    oncomplete="myJsFunction();" />


<a4j:jsFunction name="myJsFunction" action="#{myBean.jsAction}" />


But the above implementation has a limitation,
where not allowed us pass parameter(s) to #{myBean.jsAction}

This issue could be resolved by adding <a4j:param /> under <a4j:jsFunction />
The <a4j:param /> associates to a property in managed bean, and inject the param value into managed bean before the action being fired.
Thus, the action (#{myBean.jsAction}) can get the param1 value from the getter.

Tuesday, February 25, 2014

How to programmatically clear the JPA cache

When I used my JPA with EclipseLink as the implementation together with JBoss AS7.1.1.
I'm facing some issues.

One of the issue is the JPA cache not refresh by itself. 

Scenario:
When a new entity inserted into DB with JPA (EclipseLink).
and the new record is verified already inserted into database.

Then immediately I made a SELECT ALL query to this entity.
=> SELECT a FROM ENTITY a

But unfortunately, the newly inserted record is not appeared in the search result. 

to resolve this issue, I used the following line code the clear the JPA cached entities.


// the clear the entire JPA cache
entityManager.getEntityManagerFactory().getCache().evictAll();


// clear only selected entity from the JPA cache
entityManager.getEntityManagerFactory().getCache().evict(ENTITY.class);



Done!!

Saturday, February 22, 2014

Velocity without template(.vm) file

Velocity can be used without a .vm file.
The original template string could be stored in other places, eg. database, or coded in java class.

But there are slightly different to merge the template string with the passed in parameters.

Below is the sample code.
// template string coded in java class or retrieve from database
String templateString = "Using $project $name without vm file.";

// initialize Velocity
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
context.put("project", "Jakarta");

String output = new StringWriter();

// evaluate the template string and merge them together
Velocity.evaluate(context, output, "log or null", templateString);
System.out.println("output: " + output);

***to use Velocity with .vm file, we use template.merge( context, output )
***to use Velocity without .vm file, we use Velocity.evaluate( context, output, logTag, templateString )


Done!!

Wednesday, February 19, 2014

Case insensitive JPQL

There is no case insensitive comparison in SQL.
Thus, to write a case insensitive SQL, we have to first change the both parameter and value to same case.

The same concept is apply to JPQL as well.

below is the example of case insensitive JPQL.

String caseInsensitiveJPQL = " SELECT a FROM ENTITY a "

caseInsensitiveJPQL += " WHERE UPPER(a.PARAM1) = '" + value1.toUpperCase() "' ";


in the above example, I convert both PARAM1 and value1 to upper case.


Done!!

Sunday, February 9, 2014

How to attach source code for a third party jar file in Eclipse

This is to make the debugging easier in Eclipse by viewing the 3rd party source and also adding break point when in debug mode.

Steps
1. R-click on selected project > Properties

2. Go to source attachment
    Java Build Path > Libraries > choose jar to attach source > Edit

No &nbsp; in xhtml

In html or jsp, we use "&nbsp;" to make a space,
But in xhtml, "&nbsp;" is not taking any effect.

To make a space in xhtml, should use &#160;

for more information about Character Entities Reference, please go here.


Done!!

Monday, February 3, 2014

How to set up Velocity in Liferay?

To use Velocity in Liferay Portlet, we must fulfill the Velocity dependencies.
As Liferay already make sure of Velocity in layouts and themes, thus we just need to import Velocity's required jar into our customized Portlet.

This post is actually referring to Adding liferay libraries to customized portlet classpath and this is the extension of this post.

required jar files to use Velocity are
commons-lang.jar
oro.jar
velocity.jar


Done!!

Monday, January 27, 2014

Loading Velocity template in JSF

When loading Velocity template with the default setting.
The following exception might be hit
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource

Even I used the Class Resource Loader, still hitting the same exception.

The exception solved when used File Resource Loader together with the system Real Path.
String myTemplatePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/WEB-INF/mytemplatepath");

Properties p = new Properties();
p.setProperty( "file.resource.loader.path", myTemplatePath);
Velocity.init(p);

Template template = Velocity.getTemplate( "mytemplate1.vm" );

p/s: assuming all .vm files are kept under <webapp>/WEB-INF/mytemplatepath folder.

Done!!

Wednesday, January 22, 2014

How to support multiple languages for Liferay Page

By default, Liferay supporting English with locale en_US.
In some cases, we might want our Portal to support multiple languages in order to support visitors from other countries.

Thus, the objective of this post is to show how to support multiple languages in Liferay Pages.

Steps:
1. login in as Administrator into Liferay.

2. open "Manage Page" dialog by clicking Manage > Page

Sunday, January 19, 2014

Liferay Portlet Title Internationalization

By default, the Portlet title is in English with locale en_US.
To support internationalization, we can provide the Portlet title in different languages with the following steps.

Steps:
1. Login to Liferay as Administrator.

2. on the target Portlet, click on Options > Look and Feel

Thursday, January 16, 2014

How to generate PDF in Liferay PrimeFaces Portlet with iText

The objective of this post is to show how to generate PDF with iText in Liferay PrimeFaces Portlet.
The idea is to generate the PDF stream with iText and then download it with <p:fileDownload />.

Platform:
Liferay 6.1.1
PrimeFaces 3.5
iText 2.0.8 and core-renderer-R8

Steps:
1. Create the content in PDF stream with iText
    public byte[] getPdfStream() {
      byte[] pdf = null;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      String html = "<!DOCTYPE HTML><html><body>Generate PDF Test</body></html>";
      try {
              ITextRenderer itextRenderer = new ITextRenderer();
              itextRenderer.setDocumentFromString(html);
              itextRenderer.layout();
              itextRenderer.createPDF(baos);
              pdf = baos.toByteArray();
      }
      catch (Exception e) {
       e.printStackTrace();
      }
    }


2. Prepare the StreamedContent as <p:fileDownload /> value
    public StreamedContent getPdfFile() throws Exception {
     PortletResponse portletResponse = (PortletResponse) FacesContext
      .getCurrentInstance().getExternalContext().getResponse();
     HttpServletResponse res = PortalUtil
      .getHttpServletResponse(portletResponse);
     res.setHeader("Content-Disposition", "attachment; filename=\""
          + "test-kian.pdf" + "\"");//
     res.setHeader("Content-Transfer-Encoding", "binary");
     res.setContentType("application/pdf");

  res.flushBuffer();
  OutputStream out = res.getOutputStream();
  out.write(getPdfStream());

     return null;
    }


3. Download the PDF with <p:fileDownload /> in xhtml
<p:commandButton value="download PDF" ajax="false">
    <p:fileDownload value="#{myBean.pdfFile}" />
</p:commandButton>

4. To generate styled PDF, please refer How to generate styled PDF in Liferay PrimeFaces Portlet with iText


Done!!

Monday, January 13, 2014

PrimeFaces DataTable Selection Event

Following is the list of available events for row selection when using <p:dataTable />

No. Event Purpose/Usage
1 rowSelect Select a row by clicking on the row
2 rowUnselect Unselect a row by clicking on the row
3 rowSelectCheckbox Select a row by checking the selection checkbox
4 rowUnselectCheckbox Unselect a row by unchecking the selection checkbox
5 toggleSelect Select/Unselect all rows by clicking on the header checkbox
6 rowDblselect Select/Unselect a row when D-click



Done!!

Friday, January 10, 2014

Getting Liferay Signed in user in XHTML

Check the session is signed in in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].signedIn}

Get the signed in user in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].user}

Get the signed in user's properties in XHTML
#{facesContext.externalContext.requestMap['THEME_DISPLAY'].fullName}

#{facesContext.externalContext.requestMap['THEME_DISPLAY'].lastLoginDate}

Tuesday, January 7, 2014

How to configure memory for Oracle SQL Developer

To increase maximum memory to use

1. Navigate to <SQL_Developer_Installation_Dir>/sqldeveloper/bin
2. Open sqldeveloper.bat with notepad
3. edit the Xmx vm option

To increase maximum Perm size to use

1. Navigate to <SQL_Developer_Installation_Dir>/sqldeveloper/bin
2. Open sqldeveloper.conf with notepad
3. edit the MaxPermSize vm option


Done!!

Saturday, January 4, 2014

How to define Permission for a role in Liferay

1. Login as Administrator

2. Go to > Control Panel > Portal > Roles

3. Click on a Role, eg. My Role

Wednesday, January 1, 2014

EclipseLink Static weaving with Ant

<?xml version="1.0"?>
<!DOCTYPE project>

<project name="staticWeaving" default="weaving">  

<target name="define.task"
description="New task definition for EclipseLink static weaving" >
<taskdef
name="weave"
classname="org.eclipse.persistence.tools.weaving.jpa.StaticWeaveAntTask">
<classpath refid="project.class.path" />
</taskdef>
</target>

<target name="weaving" description="perform weaving." depends="define.task">
<weave
source="original-jpa.jar"
target="weaved-jpa.jar"
persistenceinfo="${jpaProjectHome}\classes">
<classpath refid="project.class.path" />
</weave>
</target>

<path id="project.class.path">
   <pathelement path="eclipselink.jar/"/>
  <pathelement path="hibernate-jpa-2.0-api-1.0.1.Final.jar"/>
</path>

</project>

LinkWithin

Related Posts Plugin for WordPress, Blogger...