This is almost straight forward implementation just follow few steps.
Step 1. Get the page url u want to print I am thinking I am on the same page
of which I wanted to print the content . Then I can get the url like this
PortletURL url = PortletURLUtil.getCurrent(renderRequest, mimeResponse or renderResponse);
else you can create the url of the page like this
PortletURL printPageURL = renderResponse.createRenderURL();
and set the required parameter related to youur page plus these extra parameters
printPageURL.setWindowState(LiferayWindowState.POP_UP);
printPageURL.setParameter("viewMode", Constants.PRINT);
sample url will look like this :
PortletURL printPageURL = renderResponse.createRenderURL();
printPageURL.setWindowState(LiferayWindowState.POP_UP);
printPageURL.setParameter("struts_action", "ur_stuts_action_path");
printPageURL.setParameter("ur_param_1", "ur_param_value_1");
printPageURL.setParameter("viewMode", Constants.PRINT);
printPageURL.setParameter("print", String.valueOf(true));
Step 2:
create a boolean variable print with default value false.
eg:
boolean print = ParamUtil.getBoolean(request,"print");
Step 3: Add this code on your page.
<c:choose>
<c:when test="<%= print %>">
<script type="text/javascript">
function printArticle() {
print();
}
</script>
</c:when>
<c:otherwise>
<script type="text/javascript">
function <portlet:namespace />printPage() {
window.open('<%= printPageURL.toString()%>', '', "directories=0,height=480,left=80,location=1,menubar=1,resizable=1,scrollbars=yes,status=0,toolbar=0,top=180,width=640");
}
</script>
</c:otherwise>
</c:choose>
Step 4: Add this code
<c:choose>
<c:when test="<%= print %>">
<span style="float:right">
<liferay-ui:icon image="Print" url="javascript:onclick=printArticle();" label="<%= false %>" />
</span>
</c:when>
<c:otherwise>
<span style="float:right">
<liferay-ui:icon image="Print" url='<%= "javascript:" + renderResponse.getNamespace() + "printPage();" %>' label="<%= false %>" />
</span>
</c:otherwise>
</c:choose>
Thats it
Enjoy !!!
Thursday, October 29, 2009
For preview without saving the article in Journal
Hi today I want to share how to implement preview without saving web-content in liferay.
Step 1:
Add following line
<input type="button" value="<liferay-ui:message key="preview" />" onClick="<portlet:namespace />previewArticleNoStructure();" />
Step 2:
write the following function
function <portlet:namespace />previewArticleNoStructure() {
document.<portlet:namespace />fm2.action = "<%= themeDisplay.getPathMain() %>/journal/view_article_content?<%= Constants.CMD %>=<%= Constants.PREVIEW %>&groupId=<%= String.valueOf(groupId) %>&articleId=<%= HttpUtil.encodeURL(articleId) %>&version=<%= version %>&languageId=" + document.<portlet:namespace />fm1.<portlet:namespace />languageId.value + "&type=" + document.<portlet:namespace />fm1.<portlet:namespace />type.value;
document.<portlet:namespace />fm2.target = "_blank";
document.<portlet:namespace />fm2.title.value = document.<portlet:namespace />fm1.<portlet:namespace />title.value;
document.<portlet:namespace />fm2.xml.value = <portlet:namespace />getArticleContentNoStructure();
document.<portlet:namespace />fm2.submit();
}
Step 3:
Write this function
function <portlet:namespace />getArticleContentNoStructure(){
var xsd = "<root available-locales=\"en_US\" default-locale=\"en_US\">";
xsd += "<static-content language-id=\"en_US\">";
xsd += "<![CDATA[";
xsd += window. xsd += "]]>";
xsd += "</static-content>";
xsd += "</root>";
return xsd;
}
that's it .
Enjoy!!!
Step 1:
Add following line
<input type="button" value="<liferay-ui:message key="preview" />" onClick="<portlet:namespace />previewArticleNoStructure();" />
Step 2:
write the following function
function <portlet:namespace />previewArticleNoStructure() {
document.<portlet:namespace />fm2.action = "<%= themeDisplay.getPathMain() %>/journal/view_article_content?<%= Constants.CMD %>=<%= Constants.PREVIEW %>&groupId=<%= String.valueOf(groupId) %>&articleId=<%= HttpUtil.encodeURL(articleId) %>&version=<%= version %>&languageId=" + document.<portlet:namespace />fm1.<portlet:namespace />languageId.value + "&type=" + document.<portlet:namespace />fm1.<portlet:namespace />type.value;
document.<portlet:namespace />fm2.target = "_blank";
document.<portlet:namespace />fm2.title.value = document.<portlet:namespace />fm1.<portlet:namespace />title.value;
document.<portlet:namespace />fm2.xml.value = <portlet:namespace />getArticleContentNoStructure();
document.<portlet:namespace />fm2.submit();
}
Step 3:
Write this function
function <portlet:namespace />getArticleContentNoStructure(){
var xsd = "<root available-locales=\"en_US\" default-locale=\"en_US\">";
xsd += "<static-content language-id=\"en_US\">";
xsd += "<![CDATA[";
xsd += window.
xsd += "</static-content>";
xsd += "</root>";
return xsd;
}
that's it .
Enjoy!!!
Thursday, September 10, 2009
Reading tempelates in liferay
Hi Friends,
I have seen many new comers to liferay seems to be struggling regarding the email tempelates.
So I thought why not put the whole procedure in a document which can help. For this reason I am
writing this post may be it is quite simple for many but will be quite helpful for the new comers.
Brief Overview:
If we see in existing liferay source code then we can find the email tempelates regarding
create account and forgot password in com/liferay/portlet/admin/dependencies/ and they are read from there.
In 1 case I can tell you from UserLocalServiceImpl and corresponding entry for each tempelate is there in
portal.properties
Enough theory time to do your self:
1.Just create a folder in ext-impl may be u can choose this path
ext-impl\src\com\mytempelate
2.Write a simple tempelate
eg:
Dear [$TO_NAME$],<br /><br />
Hi this is my first tempelate.<br /><br />
Sincerely,<br />
[$FROM_NAME$]
save this as my_first_tmpl.tmpl
3.make an entry in portal-ext.properties
for our example like this :
ext.myfirst.tempelate=ext-impl\src\com\mytempelate\my_first_tmpl.tmpl
This is just a normal key value pair.
4.Now time to read your tempelate
String firstTemeplate = PrefsPropsUtil.getContent(user.getCompanyId(),"ext.myfirst.tempelate");
or
String firstTemeplate = ContentUtil.get("ext-impl\src\com\mytempelate\my_first_tmpl.tmpl");
5. We can easily replace the content :
String firstTemeplate= StringUtil.replace(firstTemeplate, new String[] {"[$TO_NAME$]","[$FROM_NAME$]"
}, new String[] {
"any_name","any_name"
});
Thats it !!!
I have seen many new comers to liferay seems to be struggling regarding the email tempelates.
So I thought why not put the whole procedure in a document which can help. For this reason I am
writing this post may be it is quite simple for many but will be quite helpful for the new comers.
Brief Overview:
If we see in existing liferay source code then we can find the email tempelates regarding
create account and forgot password in com/liferay/portlet/admin/dependencies/ and they are read from there.
In 1 case I can tell you from UserLocalServiceImpl and corresponding entry for each tempelate is there in
portal.properties
Enough theory time to do your self:
1.Just create a folder in ext-impl may be u can choose this path
ext-impl\src\com\mytempelate
2.Write a simple tempelate
eg:
Dear [$TO_NAME$],<br /><br />
Hi this is my first tempelate.<br /><br />
Sincerely,<br />
[$FROM_NAME$]
save this as my_first_tmpl.tmpl
3.make an entry in portal-ext.properties
for our example like this :
ext.myfirst.tempelate=ext-impl\src\com\mytempelate\my_first_tmpl.tmpl
This is just a normal key value pair.
4.Now time to read your tempelate
String firstTemeplate = PrefsPropsUtil.getContent(user.getCompanyId(),"ext.myfirst.tempelate");
or
String firstTemeplate = ContentUtil.get("ext-impl\src\com\mytempelate\my_first_tmpl.tmpl");
5. We can easily replace the content :
String firstTemeplate= StringUtil.replace(firstTemeplate, new String[] {"[$TO_NAME$]","[$FROM_NAME$]"
}, new String[] {
"any_name","any_name"
});
Thats it !!!
Thursday, August 13, 2009
Customizing url and changing default landing after login
Introduction:
Currently when ever we are login in we are getting path like
http://localhost:8080/web/guest/home
First we will try to simplify this url
eg:
Suppose I made a community with name Fquad then I want to access
it as http://fquad.com rather than http://fquad.com:8080/web/guest/home
How to achieve it??
we need to follow few simple steps for it
Step 1: Go to c:\WINDoWS\System32\drivers\etc or search for host file
in host file add a line like this
127.0.0.1 www.fquad.com
Step 2: Stop the sever and start it and try to access the application with
url http://fquad:8080/web/guest/home , if working fine go to step 3
Step 3: Now create a community with name Fquad.
Step 4: Create 2 pages in Fquad community 1 public page and other private page.
Step 5: Go to manage pages of Fquad community click the setting tab and then click
the Virtual Host tab then you can see Public Virtual Host text field fill it with
www.fquad.com
Step 6: Now try to access application using url http://fquad:8080/
Step 7: To remove :8080 is simple just change connector port in tomcat/conf/server.xml
search for line Connector port="8080" protocol="HTTP/1.1 and change 8080 to 80 thats it.
Sometimes it is required to land directly to private page of a community then in portal-ext.properties
add 1 line , portal-ext.properties exist under tomcat\webapps\ROOT\WEB-INF\classes if not there create it
default.landing.page.path=/group/fquad
Currently when ever we are login in we are getting path like
http://localhost:8080/web/guest/home
First we will try to simplify this url
eg:
Suppose I made a community with name Fquad then I want to access
it as http://fquad.com rather than http://fquad.com:8080/web/guest/home
How to achieve it??
we need to follow few simple steps for it
Step 1: Go to c:\WINDoWS\System32\drivers\etc or search for host file
in host file add a line like this
127.0.0.1 www.fquad.com
Step 2: Stop the sever and start it and try to access the application with
url http://fquad:8080/web/guest/home , if working fine go to step 3
Step 3: Now create a community with name Fquad.
Step 4: Create 2 pages in Fquad community 1 public page and other private page.
Step 5: Go to manage pages of Fquad community click the setting tab and then click
the Virtual Host tab then you can see Public Virtual Host text field fill it with
www.fquad.com
Step 6: Now try to access application using url http://fquad:8080/
Step 7: To remove :8080 is simple just change connector port in tomcat/conf/server.xml
search for line Connector port="8080" protocol="HTTP/1.1 and change 8080 to 80 thats it.
Sometimes it is required to land directly to private page of a community then in portal-ext.properties
add 1 line , portal-ext.properties exist under tomcat\webapps\ROOT\WEB-INF\classes if not there create it
default.landing.page.path=/group/fquad
Wednesday, August 12, 2009
Give a try to ContactListener in ext environment
step 1. create a class that extends ModelListener .
eg. If want to extend ContactListener and want to do some action onAfterCreate then
public class CustomContactListener extends ContactListener {
public void onAfterCreate(BaseModel model) throws ModelListenerException {
try {
super.onAfterCreate(model)
//your code
System.out.println("Conatct info after update: " + contact.getContactId() + ":" + contact.getFirstName());
}
catch (Exception e) {
throw new ModelListenerException(e);
}
}
}
step 2. Make an entry in portal-ext.properties
value.object.listener.com.liferay.portal.model.Contact=\
com.liferay.portal.model.ContactListener,\
com.liferay.portal.model.CustomContactListener
do ant deploy and update contact table entry and check in console whether updated data is coming or not.
eg. If want to extend ContactListener and want to do some action onAfterCreate then
public class CustomContactListener extends ContactListener {
public void onAfterCreate(BaseModel model) throws ModelListenerException {
try {
super.onAfterCreate(model)
//your code
System.out.println("Conatct info after update: " + contact.getContactId() + ":" + contact.getFirstName());
}
catch (Exception e) {
throw new ModelListenerException(e);
}
}
}
step 2. Make an entry in portal-ext.properties
value.object.listener.com.liferay.portal.model.Contact=\
com.liferay.portal.model.ContactListener,\
com.liferay.portal.model.CustomContactListener
do ant deploy and update contact table entry and check in console whether updated data is coming or not.
Tuesday, August 11, 2009
Using Json in Liferay
Introduction:
We have 2 Service tiers..
The Local tier - this tier has no permission checks and is simply a clean cut implementation of the business logic of the service.
i.e. you set local-service="true" when you created the entity.
e.g.
UserLocalServiceUtil.updateActive(long userId, boolean active) (re, no permission check is made, use with caution).
The Remote Tier - this tier is designed to include your permission checks and finally calls the underlying Local service to actually perform the service operation. This tier is also the one on which ALL web-service methods are generated. All the HTTP, JSON, and SOAP are backed by the methods found in this tier.
i.e. you set remote-service="true" when you created the entity AND you implemented methods in [Entity]ServiceImpl.java rather than leaving it blank.
e.g.
UserServiceImpl.updateActive(long userId, boolean active) (i.e., makes a permission check internally):
public User updateActive(long userId, boolean active)
throws PortalException, SystemException {
if ((getUserId() == userId) && !active) {
throw new RequiredUserException();
}
UserPermissionUtil.check(
getPermissionChecker(), userId, ActionKeys.DELETE);
return userLocalService.updateActive(userId, active);
}
SO, all webservice methods which call their implementation of "updateActive" on the UserService are backed by this method. Also, this means that the caller must be authenticated in order to be tested for permissions... otherwise the call will fail. So, you need to be authenticated, AND you need to have permission.
How does a JSON method get authenticated when it's called through and ajax call? All our JSON services are passed through an AutoLogin Filter which handles the authentication based on authorization cookies.
Abstraction for using Json in Liferay:
Step 1. generate service layer for your entity with remote-service="true"
eg.
Step 2. In [entity]ServiceImpl write a method which you want to call using Json.
eg. updateName(userName) throws Exception{//your code goes here}.
Step 3. Do ant build-service -Dservice.file=your_service_xml_path from ext/ext-impl
Step 4. Do ant deploy from ext.
Step 5. Check file ext-web/docroot/html/js/liferay/ext_service_unpacked.js is updated with your method or not.
Note: In liferay version 5.2.x onwards this file is "ext_service.js".
Step 6. Include js like this in file in which you want to call json.
Step 7. Call method like this
eg:
function updateName(userName) {
var params = {
userName: userName
};
Liferay.Service.your_entity_namespace.entity_name.updateName(params);
}
We have 2 Service tiers..
The Local tier - this tier has no permission checks and is simply a clean cut implementation of the business logic of the service.
i.e. you set local-service="true" when you created the entity.
e.g.
UserLocalServiceUtil.updateActive(long userId, boolean active) (re, no permission check is made, use with caution).
The Remote Tier - this tier is designed to include your permission checks and finally calls the underlying Local service to actually perform the service operation. This tier is also the one on which ALL web-service methods are generated. All the HTTP, JSON, and SOAP are backed by the methods found in this tier.
i.e. you set remote-service="true" when you created the entity AND you implemented methods in [Entity]ServiceImpl.java rather than leaving it blank.
e.g.
UserServiceImpl.updateActive(long userId, boolean active) (i.e., makes a permission check internally):
public User updateActive(long userId, boolean active)
throws PortalException, SystemException {
if ((getUserId() == userId) && !active) {
throw new RequiredUserException();
}
UserPermissionUtil.check(
getPermissionChecker(), userId, ActionKeys.DELETE);
return userLocalService.updateActive(userId, active);
}
SO, all webservice methods which call their implementation of "updateActive" on the UserService are backed by this method. Also, this means that the caller must be authenticated in order to be tested for permissions... otherwise the call will fail. So, you need to be authenticated, AND you need to have permission.
How does a JSON method get authenticated when it's called through and ajax call? All our JSON services are passed through an AutoLogin Filter which handles the authentication based on authorization cookies.
Abstraction for using Json in Liferay:
Step 1. generate service layer for your entity with remote-service="true"
eg.
Step 2. In [entity]ServiceImpl write a method which you want to call using Json.
eg. updateName(userName) throws Exception{//your code goes here}.
Step 3. Do ant build-service -Dservice.file=your_service_xml_path from ext/ext-impl
Step 4. Do ant deploy from ext.
Step 5. Check file ext-web/docroot/html/js/liferay/ext_service_unpacked.js is updated with your method or not.
Note: In liferay version 5.2.x onwards this file is "ext_service.js".
Step 6. Include js like this in file in which you want to call json.
Step 7. Call method like this
eg:
function updateName(userName) {
var params = {
userName: userName
};
Liferay.Service.your_entity_namespace.entity_name.updateName(params);
}
Monday, August 10, 2009
Creating simple struts Portlet in liferay in 5 min
In struts portlet as compare to Jsp portlet we need to add 2 extra xml files
1.struts-config.xml
2.tiles-defs.xml
We have to modify follwing xml files.
These xml files are located under "ext/ext-web/docroot/WEB-INF"
2.1. portlet-ext.xml
--------------------
<portlet>
<portlet-name>Sample</portlet-name>
<display-name>Sample Struts Portlet</display-name>
<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>
<init-param>
<name>view-action</name>
<value>/ext/sample/view</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
2.2. liferay-portlet-ext.xml
----------------------------
<portlet>
<portlet-name>Sample</portlet-name>
<struts-path>ext/sample</struts-path>
<use-default-template>false</use-default-template>
</portlet>
2.3. liferay-display.xml
------------------------
add
<portlet id="Sample" />
inside
<category name="category.sample">
2.4. struts-config.xml
----------------------
<action path="/ext/sample/view" forward="portlet.ext.sample.view" />
2.5. tiles-defs.xml
-------------------
<definition name="portlet.ext.sample" extends="portlet" />
<definition name="portlet.ext.sample.view" extends="portlet.ext.sample">
<put name="portlet_content" value="/portlet/ext/sample/view.jsp" />
</definition>
(create the following two jsp files under "/ext/ext-web/docroot/html/portlet/ext/sample")
2.6. init.jsp
-------------
<%@ include file="/html/portlet/init.jsp" %>
2.7. view.jsp
-------------
<%@ include file="/html/portlet/ext/sample/init.jsp" %>
Simple Struts Portlet!
2.8 Language-ext.properties
---------------------------
Add a new entry in the above file,
javax.portlet.title.Sample=Sample Struts Portlet
1.struts-config.xml
2.tiles-defs.xml
We have to modify follwing xml files.
These xml files are located under "ext/ext-web/docroot/WEB-INF"
2.1. portlet-ext.xml
--------------------
<portlet>
<portlet-name>Sample</portlet-name>
<display-name>Sample Struts Portlet</display-name>
<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>
<init-param>
<name>view-action</name>
<value>/ext/sample/view</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
2.2. liferay-portlet-ext.xml
----------------------------
<portlet>
<portlet-name>Sample</portlet-name>
<struts-path>ext/sample</struts-path>
<use-default-template>false</use-default-template>
</portlet>
2.3. liferay-display.xml
------------------------
add
<portlet id="Sample" />
inside
<category name="category.sample">
2.4. struts-config.xml
----------------------
<action path="/ext/sample/view" forward="portlet.ext.sample.view" />
2.5. tiles-defs.xml
-------------------
<definition name="portlet.ext.sample" extends="portlet" />
<definition name="portlet.ext.sample.view" extends="portlet.ext.sample">
<put name="portlet_content" value="/portlet/ext/sample/view.jsp" />
</definition>
(create the following two jsp files under "/ext/ext-web/docroot/html/portlet/ext/sample")
2.6. init.jsp
-------------
<%@ include file="/html/portlet/init.jsp" %>
2.7. view.jsp
-------------
<%@ include file="/html/portlet/ext/sample/init.jsp" %>
Simple Struts Portlet!
2.8 Language-ext.properties
---------------------------
Add a new entry in the above file,
javax.portlet.title.Sample=Sample Struts Portlet
creating simple jsp portlet in Liferay
For creating simple Jsp portlet in Liferay we have to modify following files.
Following xml files are located under "ext/ext-web/docroot/WEB-INF"
1.1. portlet-ext.xml
--------------------
Add entry for your portlet
<portlet>
<portlet-name>Sample</portlet-name>
<display-name>JSP Portlet Introduction</display-name>
<portlet-class>com.liferay.util.bridges.jsp.JSPPortlet</portlet-class>
<init-param>
<name>view-jsp</name>
<value>/html/portlet/ext/jsp_portlet/view.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
1.2. liferay-portlet-ext.xml
----------------------------
Make an entry for your portlet.
<portlet>
<portlet-name>Sample</portlet-name>
</portlet>
1.3. liferay-display.xml
------------------------
Make an entry for the category in which you want to display your portlet.
<category name="category.sample">
<portlet id="Sample" />
</category>
1.4. view.jsp
-------------
create this file under "ext/ext-web/docroot/html/portlet/ext/jsp_portlet"
and put some contents
do "ant deploy" from "ext-web"
1.5 Language-ext.properties
---------------------------
(under /ext/ext-impl/src/content)
Add two new entries in the above file, this helps us in I18N
javax.portlet.title.Sample=Sample JSP Portlet
category.sample=Example
do "ant deploy" from "ext-impl"
Following xml files are located under "ext/ext-web/docroot/WEB-INF"
1.1. portlet-ext.xml
--------------------
Add entry for your portlet
<portlet>
<portlet-name>Sample</portlet-name>
<display-name>JSP Portlet Introduction</display-name>
<portlet-class>com.liferay.util.bridges.jsp.JSPPortlet</portlet-class>
<init-param>
<name>view-jsp</name>
<value>/html/portlet/ext/jsp_portlet/view.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
1.2. liferay-portlet-ext.xml
----------------------------
Make an entry for your portlet.
<portlet>
<portlet-name>Sample</portlet-name>
</portlet>
1.3. liferay-display.xml
------------------------
Make an entry for the category in which you want to display your portlet.
<category name="category.sample">
<portlet id="Sample" />
</category>
1.4. view.jsp
-------------
create this file under "ext/ext-web/docroot/html/portlet/ext/jsp_portlet"
and put some contents
do "ant deploy" from "ext-web"
1.5 Language-ext.properties
---------------------------
(under /ext/ext-impl/src/content)
Add two new entries in the above file, this helps us in I18N
javax.portlet.title.Sample=Sample JSP Portlet
category.sample=Example
do "ant deploy" from "ext-impl"
Sunday, July 19, 2009
How to use Custom-sql in Liferay?
Step-1:
------
Create the file default-ext.xml under ext-impl/src/custom-sql (cerate custom-sql folder if it is not there)
<?xml version="1.0"?>
<custom-sql>
<sql file="custom-sql/book.xml" />
</custom-sql>
(You can refer default.xml under portal source)
Step-2:
------
Create the file queries.xml, under the same folder, which will contain all the application specific queries as name / value pairs.
<?xml version="1.0"?>
<custom-sql>
<sql id="ur_id">
<![CDATA[
SELECT
{Book.*}
FROM
Book
WHERE
(Book.title like ?)
]]>
</sql>
</custom-sql>
Step-3:
------
Add your entry in portal-ext.properties
custom.sql.configs=\
custom-sql/default.xml, \
custom-sql/default-ext.xml
Step-4:
------
Create the file "BookFinderImpl.java" under service/persistence and do the required imports
public class BookFinderImpl extends BasePersistenceImpl implements
BookFinder{
}
Step-5:
------
Do ant build-service, so that the necessary interface is generated.
Step-6:
------
Now write the actual logic to access the custom SQL. You need to update the BookFinderImpl
we developed in the previous step.
// the name of the query
public static String GET_QUERY = "id_given_in_queries.xml";
// the method which will be called from the ServiceImpl class
public List getBooks(String pattern) throws SystemException {
Session session = null;
try {
// open a new hibernate session in normal case when you are opening session for same entity
session = openSession();
// In case of other entity you set the session first like below then open the session
setSessionFactory((SessionFactory)PortalBeanLocatorUtil.getBeanLocator().locate(TagsAssetModelImpl.SESSION_FACTORY));
session = openSession();
// pull out our query from book.xml, created earlier
String sql = CustomSQLUtil.get(GET_QUERY);
// create a SQLQuery object
SQLQuery q = session.createSQLQuery(sql);
//In normal case : In our case book use this
q.addEntity("Book", BookImpl.class);
//In other case : In our case TagsAsset use like this
q.addEntity(TagsAssetModelImpl.TABLE_NAME, TagsAssetImpl.class);
// Get query position instance
QueryPos qPos = QueryPos.getInstance(q);
// fill in the "?" value of the custom query
// this is same like forming a prepared statement
qPos.add(pattern);
// execute the query and return a list from the db
return (List)q.list();
/*
// use this block if you want to return the no. of rows (count)
int rows = 0;
Iterator itr = q.list().iterator();
if (itr.hasNext()) { Long count = itr.next();
if (count != null) { rows = count.intValue(); } }
return rows;
*/
} catch (Exception e) {
throw new SystemException(e);
} finally {
closeSession(session);
}
}
Make the necessary additional imports.
import java.util.List;
import com.ext.portlet.library.model.Book;
import com.ext.portlet.library.model.impl.BookImpl;
import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.util.dao.orm.CustomSQLUtil;
Note:
To get the result between a start and end index, you have to use,
QueryUtil.list(q, getDialect(), begin, end);
in the place of
q.list();
where, you will pass the parameters (begin and end) from your ServiceImpl class.
Step-7:
------
write the method in BookLocalServiceImpl.java
public List searchBook(String title) throws PortalException,
SystemException, RemoteException {
// return bookPersistence.findByTitle(title);
return BookFinderUtil.getBooks("%" + title + "%");
}
Step-8:
------
run "ant build-service" again passing the service.xml file as parameter.
This will update the corresponding interface with the new method defined.
Step 9:
-------
Now go ahead and call BookLocalServiceImpl method from your jsp or java normally how you call other methods
Thanks
------
Create the file default-ext.xml under ext-impl/src/custom-sql (cerate custom-sql folder if it is not there)
<?xml version="1.0"?>
<custom-sql>
<sql file="custom-sql/book.xml" />
</custom-sql>
(You can refer default.xml under portal source)
Step-2:
------
Create the file queries.xml, under the same folder, which will contain all the application specific queries as name / value pairs.
<?xml version="1.0"?>
<custom-sql>
<sql id="ur_id">
<![CDATA[
SELECT
{Book.*}
FROM
Book
WHERE
(Book.title like ?)
]]>
</sql>
</custom-sql>
Step-3:
------
Add your entry in portal-ext.properties
custom.sql.configs=\
custom-sql/default.xml, \
custom-sql/default-ext.xml
Step-4:
------
Create the file "BookFinderImpl.java" under service/persistence and do the required imports
public class BookFinderImpl extends BasePersistenceImpl implements
BookFinder{
}
Step-5:
------
Do ant build-service, so that the necessary interface is generated.
Step-6:
------
Now write the actual logic to access the custom SQL. You need to update the BookFinderImpl
we developed in the previous step.
// the name of the query
public static String GET_QUERY = "id_given_in_queries.xml";
// the method which will be called from the ServiceImpl class
public List
Session session = null;
try {
// open a new hibernate session in normal case when you are opening session for same entity
session = openSession();
// In case of other entity you set the session first like below then open the session
setSessionFactory((SessionFactory)PortalBeanLocatorUtil.getBeanLocator().locate(TagsAssetModelImpl.SESSION_FACTORY));
session = openSession();
// pull out our query from book.xml, created earlier
String sql = CustomSQLUtil.get(GET_QUERY);
// create a SQLQuery object
SQLQuery q = session.createSQLQuery(sql);
//In normal case : In our case book use this
q.addEntity("Book", BookImpl.class);
//In other case : In our case TagsAsset use like this
q.addEntity(TagsAssetModelImpl.TABLE_NAME, TagsAssetImpl.class);
// Get query position instance
QueryPos qPos = QueryPos.getInstance(q);
// fill in the "?" value of the custom query
// this is same like forming a prepared statement
qPos.add(pattern);
// execute the query and return a list from the db
return (List
/*
// use this block if you want to return the no. of rows (count)
int rows = 0;
Iterator
if (itr.hasNext()) { Long count = itr.next();
if (count != null) { rows = count.intValue(); } }
return rows;
*/
} catch (Exception e) {
throw new SystemException(e);
} finally {
closeSession(session);
}
}
Make the necessary additional imports.
import java.util.List;
import com.ext.portlet.library.model.Book;
import com.ext.portlet.library.model.impl.BookImpl;
import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.util.dao.orm.CustomSQLUtil;
Note:
To get the result between a start and end index, you have to use,
QueryUtil.list(q, getDialect(), begin, end);
in the place of
q.list();
where, you will pass the parameters (begin and end) from your ServiceImpl class.
Step-7:
------
write the method in BookLocalServiceImpl.java
public List
SystemException, RemoteException {
// return bookPersistence.findByTitle(title);
return BookFinderUtil.getBooks("%" + title + "%");
}
Step-8:
------
run "ant build-service" again passing the service.xml file as parameter.
This will update the corresponding interface with the new method defined.
Step 9:
-------
Now go ahead and call BookLocalServiceImpl method from your jsp or java normally how you call other methods
Thanks
Friday, July 10, 2009
Playing with portletURL in Liferay
With out tld :
============================================================================================
1.To get currentURL :
PortletURL url = PortletURLUtil.getCurrent(renderRequest, mimeResponse or renderResponse)
============================================================================================
============================================================================================
2.To make clone of a URL :
PortletURL url = PortletURLUtil.clone(portletURL, mimeResponse or renderResponse)
============================================================================================
=============================================================================================
3.creating PortletURL from actionResponse :
PortletURL renderURL = ((ActionResponseImpl) actionResponse).createRenderURL();
===============================================================================================================
============================================================================================================
4.creating PortletURL from renderResponse :
a.For RenderURL:
PortletURL renderURL = renderResponse.createRenderURL();
b.For actionURL:
PortletURL actionURL = renderResponse.createActionURL();
============================================================================================================
5.Using TLD's in Liferay :
a.
<portlet:renderURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:renderURL>
b.
<portlet:actionURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:actionURL>
============================================================================================
1.To get currentURL :
PortletURL url = PortletURLUtil.getCurrent(renderRequest, mimeResponse or renderResponse)
============================================================================================
============================================================================================
2.To make clone of a URL :
PortletURL url = PortletURLUtil.clone(portletURL, mimeResponse or renderResponse)
============================================================================================
=============================================================================================
3.creating PortletURL from actionResponse :
PortletURL renderURL = ((ActionResponseImpl) actionResponse).createRenderURL();
===============================================================================================================
============================================================================================================
4.creating PortletURL from renderResponse :
a.For RenderURL:
PortletURL renderURL = renderResponse.createRenderURL();
b.For actionURL:
PortletURL actionURL = renderResponse.createActionURL();
============================================================================================================
5.Using TLD's in Liferay :
a.
<portlet:renderURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:renderURL>
b.
<portlet:actionURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:actionURL>
Thursday, May 28, 2009
Using Hooks in Liferay for customizing jsp
Using hooks customizing jsp page of a existing liferay portlet.
In this example I am taking portlet asset-publisher.
Step 2: Go to asset-publisher-hook create folder docroot and build.xml file.
Content of build.xml should be like this:
<project name="hook" basedir="." default="deploy">
<import file="../build-common-hook.xml">
</project>
Step 3: Go to asset-publisher-hook/docroot create folder with name WEB-INF.
Step 4: Now under WEB-INF create a file liferay-hook.xml and a folder with name jsps.
Step 5: In liferay-hook.xml write following code.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 5.1.0//EN" "http://www.liferay.com/dtd/liferay-hook_5_2_2.dtd">
<hook>
<custom-jsp-dir>/WEB-INF/jsps </hook>
Step 6:Under jsps create folders html/portlet/portlet_name in our case portlet_name is asset-publisher.
Step 7:Under portlet_name create the same structure for the page which we want to modify.
Eg. In asset-publisher we will try to modify full_content.jsp then structure will be
html/portlet/asset-publisher/display/full_content.jsp
Step 8:Customize the jsp file.
Step 9:Go to plugins/hook
Do ant deploy
Step 10:Check the changes on server
Subscribe to:
Posts (Atom)