Tuesday, March 11, 2014

Liferay Important Code Snippets Part-II

Introduction:

Liferay Important code snippets is some use full code which we use in liferay development regularly this will help to the Liferay developers to use in development.
I just collected these code snippets from forums and some snippets which I already developed one.

Get Back URL of portlet

Write code in JSP page


<%=themeDisplay.getPortletDisplay().getURLBack()%>


Download file

Write code in portlet action class

HttpServletResponse httpResponse = PortalUtil.getHttpServletResponse(resourceResponse);
HttpServletRequest httpRequest = PortalUtil.getHttpServletRequest(resourceRequest);
ServletResponseUtil.sendFile(httpRequest,httpResponse ,fileName, is,contentType);


Navigate JSP page from action URL

Write code in JSP page
<portlet:actionURL var="doBusinessLogicActionURL" windowState="normal">
<portlet:param name="<%=ActionRequest.ACTION_NAME%>" value="doBusinessLogic"/>
</portlet:actionURL>

or

<portlet:actionURL name="doBusinessLogic" var="doBusinessLogicActionURL" windowState="normal">
<portlet:param name="<%=ActionRequest.ACTION_NAME%>" value="doBusinessLogic"/>
</portlet:actionURL>

<aui:a href="<%=doBusinessLogicActionURL%>">Previous</aui:a>

Write following code in Portlet Action Class

public class PortletAction extends MVCPortlet {

            public void doBusinessLogic(
                                    ActionRequest actionRequest, ActionResponse actionResponse)
                        throws IOException, PortletException {
                        //Write you all business Logic here

                        System.out.println("====doBusinessLogic===");
                        actionResponse.setRenderParameter("mvcPath", "/html/hello.jsp");
                //actionResponse.setRenderParameter("jspPage", "/html/hello.jsp");
                       
            }
}

Get selected values from select box using AUI Script

<aui:select name="testSelect" id="testSelect" label ="Test Select">
            <aui:option selected="true" value="ALL">All</aui:option>
            <aui:option  value="YES">Yes</aui:option>
            <aui:option  value="NO">No</aui:option>
</aui:select>    
<aui:script>
AUI().use('aui-base', function(A){
A.one("#<portlet:namespace/>testSelect").on('change',function(){
var selectedValue = A.one('#<portlet:namespace/>testSelect').get('value');
 alert(selectedValue);
});
});
</aui:script>


AUI Click Function

<aui:button name="clickMe" id="clickMe" value="Click Me"></aui:button>    
<aui:script>
AUI().use('aui-base', function(A){
A.one("#<portlet:namespace/>testSelect").on('clcik',function(){
 alert("This click Event from AUI");
});
});
</aui:script>


Get My Account and Control panel URL for User


themeDisplay.getURLControlPanel();
themeDisplay.getURLMyAccount();


Open window

function <portlet:namespace />openFileEntryTypeSelector() {
Liferay.Util.openWindow(
                                    {
                                 dialog: {
                                    width: 680
                                                },
            id: '<portlet:namespace />fileEntryTypeSeclector',
            title: '<%= UnicodeLanguageUtil.get(pageContext, "document-types") %>',
            uri: '<portlet:renderURL windowState="<%= LiferayWindowState.POP_UP.toString() %>"><portlet:param name="struts_action"
value="/document_library/select_file_entry_type" /><portlet:param name="groupId" value="<%= String.valueOf(scopeGroupId) %>" /><portlet:param
name="includeBasicFileEntryType" value="1" /></portlet:renderURL>'
});
}


Create AUI reference

var A = AUI();


Load AUI script Using Script Tag

<aui:script use="aui-dialog,aui-swf">
</aui:script>


AUI Video Player

<aui:script use="aui-base,aui-video">
            new A.Video(
            {
            contentBox: '#<portlet:namespace />previewFileContent',
            fixedAttributes: {
            allowfullscreen: 'true',
            bgColor: '#000000',
            wmode: 'opaque'
            },
<c:if test="<%= Validator.isNotNull(ogvPreviewFileURL) %>">
ogvUrl: '<%= ogvPreviewFileURL %>',
</c:if>
poster: '<%= videoThumbnailURL %>'
<c:if test="<%= Validator.isNotNull(mp4PreviewFileURL) %>">
, url: '<%= mp4PreviewFileURL %>'
</c:if>
}).render();
</aui:script>


AUI Audio Player

<aui:script use="aui-audio,swfdetect">
var audio = new A.Audio(
{
contentBox: '#<portlet:namespace />previewFileContent',
fixedAttributes: {
allowfullscreen: 'true',
wmode: 'opaque'
}
<c:if test="<%= Validator.isNotNull(mp3PreviewFileURL) %>">
, url: '<%= mp3PreviewFileURL %>'
</c:if>
});
<c:if test="<%= Validator.isNotNull(oggPreviewFileURL) %>">
if (!A.UA.gecko || !A.SWFDetect.isFlashVersionAtLeast(9)) {
audio.set('oggUrl', '<%= oggPreviewFileURL %>');
}
</c:if>audio.render();
</aui:script>


Liferay Provide function  declaration

<%String taglibUrl = "javascript:" + renderResponse.getNamespace() + "sortEntries('" + folderId + "', 'title','" + reverseOrderByType + "')";
            %>
<liferay-ui:icon message="title" url="<%= taglibUrl %>"/>
<aui:script>
            Liferay.provide(
                        window,
                        '<portlet:namespace />sortEntries',
                        function(folderId, orderByCol, reverseOrderByType) {
                                    //script here
                        },
                        ['aui-base']
            );
</aui:script>


Add file entry

File file=uploadPortletRequest.getFile("file")
ThemeDisplay themeDisplay =
 (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
ServiceContext serviceContext =
 ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);
String contentType = uploadPortletRequest.getContentType("file");
String changeLog = ParamUtil.getString(actionRequest, "changeLog");
fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
themeDisplay.getScopeGroupId(),0,"myfileNem",contentType,"myFileTitle","my file description",changeLog,file, serviceContext);


Download file Link


FileEntry fileEntry=DLAPPLocalServiceUtil.getfileEntryId(fileEntryId);

<div>
<liferay-ui:icon
image="download"
label="<%= true %>"
message='<%= LanguageUtil.get(pageContext, "download") + " (" + TextFormatter.formatKB(fileEntry.getFileVersion().getSize(), locale) + "k)" %>'
url="<%= DLUtil.getPreviewURL(fileEntry, fileEntry.getFileVersion(),
themeDisplay, StringPool.BLANK) %>"
/>
</div>

Display Article through AUI Script

<a href="#" onclick="Liferay.Journal.display(this, '13310');return false;" >WebContentB</a>
AUI().use('event', 'node', function(A) {
     (function() {
         Liferay.Journal = {
             getPortlet : function(elt) {
                 var nodeObject = A.one(elt);
                 return nodeObject.ancestor('.portlet-boundary');
             },
           display : function(elt, articleId) {
                var portletNode = Liferay.Journal.getPortlet(elt);
                var portletId = portletNode.portletId;
                var renderURL = Liferay.PortletURL.createRenderURL();
               renderURL.setParameter("articleId", articleId);
                renderURL.setPortletId(portletId);
                renderURL.setPortletMode("view");
                renderURL.setWindowState("normal");
                //alert(renderURL.toString());
                window.location = renderURL.toString();
            }
        };
    })();
});

Ref:


AUI Auto Complete list

JSP PAGE

<portlet:resourceURL var="getPlaces">
            <portlet:param name="<%=Constants.CMD%>" value="get_places" />
</portlet:resourceURL>
<aui:input id="myInputNode" name="myInputNode" label="Place"
            helpMessage="Type Some text in Input" />
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
A.io.request('<%=getPlaces%>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'true',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace />myInputNode',
resultTextLocator: 'name',
render: 'true',
resultHighlighter: 'phraseMatch',
resultFilters:['phraseMatch'],
source:this.get('responseData'),
})
}}
});
});
</aui:script>

=========== portlet class======

@Override
             public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {
               String cmd = ParamUtil.getString(resourceRequest, Constants.CMD);
             
              System.out.println("Constants.CMD: " + cmd);

              if (cmd.equals("get_places")) {
                getPlaceJson(resourceRequest, resourceResponse);
              }if (cmd.equals("get_users")) {
                            getUsers(resourceRequest, resourceResponse);
                          }
             
            }

            private void getPlaceJson(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException {

              JSONArray jsonResults = JSONFactoryUtil.createJSONArray();
              try {
                String keyword = ParamUtil.getString(resourceRequest, "keywords");
                String searchPattern = keyword.replace("*", "%");

                System.out.println("Keywords: " + searchPattern);

                JSONObject jsonCells = JSONFactoryUtil.createJSONObject();
                jsonCells.put("key", "1");
                jsonCells.put("name", "New York, USA");
                jsonResults.put(jsonCells);
                jsonCells = JSONFactoryUtil.createJSONObject();
                jsonCells.put("key", "2");
                jsonCells.put("name", "Delhi, India");
                jsonResults.put(jsonCells);
                jsonCells = JSONFactoryUtil.createJSONObject();
                jsonCells.put("key", "3");
                jsonCells.put("name", "Hyderabad, India");
                jsonResults.put(jsonCells);
              } catch (Exception e) {       
              }
              PrintWriter out=resourceResponse.getWriter();
           out.println(jsonResults.toString());
            }


Load other portlet Class and Other portlet Resource in Current Portlet

String portletId="autocompletelistaction_WAR_AUIAutoCompleteListportlet";
<%=PortletClassLoaderUtil.getClassLoader(portletId).getResource
("log4j.properties").toString()%>


Load specific portlet class loader using Portlet Bean Locator

ClassLoader classLoader = (ClassLoader) PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(), "portletClassLoader");
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(CSLStudyVersion.class, classLoader);



Portlet class loader

DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(CSLStudyVersion.class, PortletClassLoaderUtil.getClassLoader());


Portal Class Loader

DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(User.class, PortalClassLoaderUtil.getClassLoader());


Set Content to Ckeditor

<%
String articleId=ParamUtil.getString(renderRequest,"articleId");
String artcileContent="";
JournalArticle article=null;
if(articleId!=null&&!articleId.isEmpty()){
 article = JournalArticleLocalServiceUtil.getArticle(groupId, articleId);      
 JournalArticleDisplay articleDisplay =  JournalContentUtil.getDisplay (article.getGroupId(), article.getArticleId(),"",defaultLanguageId,themeDisplay);
 artcileContent = articleDisplay.getContent();

}%>
<aui:input name="artcileContent" id="artcileContent" type="hidden" value="<%=artcileContent%>" />
<liferay-ui:input-editor ></liferay-ui:input-editor>
<aui:script>
var A = AUI();
  function <portlet:namespace />initEditor() {
  var content=A.one('#<portlet:namespace />artcileContent').get("value");
        return content;
    }
}
</aui:script>

Get request parameters in velocity in liferay


Example URL:

http://localhost:8080/web/guest?isLoginPanelOpen=yes

Write following code in velocity files/templates

#set ($serviceContext = $portal.getClass().forName
("com.liferay.portal.service.ServiceContextThreadLocal").getServiceContext())
#set ($httpServletRequest = $serviceContext.getRequest())
#set($isLoginPanelOpen=$paramUtil.getString($httpServletRequest,
 'isLoginPanelOpen'))


Load Potlet in Div



<div id="loginBoxDiv" ></div>

<aui:script>
AUI().use('aui-base','aui-node','aui-io-request','aui-io','liferay-portlet-url', function(A) {
var url =Liferay.PortletURL.createRenderURL();   
url.setPortletId('signinaction_WAR_WatsonSiginInportlet'); 
url.setWindowState('pop_up');
var myAjaxRequest=A.io.request(url.toString(), {
   dataType: 'html',
   autoLoad: false,
    on: {
    success: function() {
   document.getElementById("login-portlet-content").innerHTML=this.get('responseData');
   //A.one('#loginBoxDiv').set('innerHTML',this.get('responseData'));
     }}
 });
    //myAjaxRequest.set('cache', false);
      myAjaxRequest.start();            
});
</aui:script>


AUI Animation Example

<div class="righ-header-search" id="righ-header-search">
<div class="searchBtn">
<a href="#"><img src="$images_folder/watson/common/btn-search.png"></a>
</div>
<div class="searchinput" id="searchinput" style="width: 1px;"><input type="text" value="" placeholder="enter keywords"></div>
</div>
//anim
AUI().use('aui-base','aui-node','aui-io', 'aui-event','anim', function (A) {
            //search box animataion
                        var a = new A.Anim(
                                                              {
                                                                node: '#searchinput',
                                                                duration: 0.1,
                                                                easing: A.Easing.bounceOut
                                                              });
                        //alert(a);                  
                        A.one('#righ-header-search').on('mouseenter', function(event){
                                    //A.one('.searchinput1').width(1);
                                     var toArrat={width:300,opacity: 0.5};
                                     a.set("to",toArrat);
                                     a.run();
                                    // b.stop();
                        });                                          
            A.one('#righ-header-search').on('mouseleave', function(event){
                                    var toArrat1={width:1,opacity: 0.5};
                                     a.set("to",toArrat1);
                                    a.run();
                                    // b.destroy();
                        });      
           
            A.one('#searchBtn').on('click', function(event){
                        document.themeSearchForm.submit();
                        });                  
  });


Dynamic Query In operator

String[] centerTypesArray = { "Leaderboard", "LearningCentre", "CSRCentre", "SocialCentre", "CommunicationCentre" , "PolicyCentre" , "Idea Centre" ,
"AppreciationCentre" ,"Public Page"};

Dynamic Query activityQuery=DynamicQueryFactoryUtil.forClass(ActivityData.class,(ClassLoader)PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(),
"portletClassLoader"))
.add(RestrictionsFactoryUtil.between("publicationliveDate", actdate,curdate))
.add(PropertyFactoryUtil.forName("centretype").in(centerTypesArray))
.addOrder(OrderFactoryUtil.desc("publicationliveDate"));


Reset Encryption Key for company


You can reset the company key by

removing it from DB and restarting portal

 or executing following Groovy script from

Go to control panel click on server administration and click on script tab there you can find Groovy Console

import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.Encryptor;
company = CompanyLocalServiceUtil.getCompanyById(PortalUtil.getDefaultCompanyId());
company.setKey(Base64.objectToString(Encryptor.generateKey()));
CompanyLocalServiceUtil.updateCompany(company);


Wrap action request with dynamic action request

public void processAction(StrutsPortletAction originalStrutsPortletAction,
             PortletConfig portletConfig, ActionRequest actionRequest,
          ActionResponse actionResponse) throws Exception {
        String login = ParamUtil.getString(actionRequest, "login");
      DynamicActionRequest actionRequestNew = new DynamicActionRequest(actionRequest);
        actionRequestNew.setParameter("login", login + "++");

       originalStrutsPortletAction.processAction(originalStrutsPortletAction,
                portletConfig, actionRequestNew, actionResponse);
    }


Embed portlet in theme using velocity code

Write following code in velocity files


<div class="righ-header-weather">
#set ($locPortletId = "weatheraction_WAR_StockCurrencyWeatherNewsportlet")
#set ($portletPreferencesFactoryUtil = $portal.getClass().forName("com.liferay.portlet.PortletPreferencesFactoryUtil"))
#set ($portletSetup = $portletPreferencesFactoryUtil.getLayoutPortletSetup($layout, $locPortletId))
#if ($portletSetup.getValue("portletSetupShowBorders", "") != "false")
#set ($temp = $portletSetup.setValue("portletSetupShowBorders", "false"))
#set ($temp = $portletSetup.store())
#end
#set ($embeddedPortletURL = $portletURLFactory.create($request, $locPortletId, $layout.plid, "RENDER_PHASE"))
#set ($VOID = $embeddedPortletURL.setWindowState("pop_up"))
#set ($VOID = $embeddedPortletURL.setPortletMode("view"))
<iframe frameborder="0" id="${locPortletId}custom_frame" src="${embeddedPortletURL.toString()}" scrolling="no" width="120px" height="43px"></iframe>
</div>


OR


#set ($locPortletId = "82")
##
## Portlet Setup
##
## This is for look and feel only. In case of instanceable portlets this
## is the same as the PortletPreferences.
##
## If you want the PortletPreferences for a non-instancable portlet,
## you'll have to make a different call.
##
#set ($portletPreferencesFactoryUtil = $portal.getClass().forName("com.liferay.portlet.PortletPreferencesFactoryUtil"))
#set ($portletSetup = $portletPreferencesFactoryUtil.getLayoutPortletSetup($layout, $locPortletId))

#if ($portletSetup.getValue("portletSetupShowBorders", "") != "false")
            #set ($temp = $portletSetup.setValue("portletSetupShowBorders", "false"))
            #set ($temp = $portletSetup.store())
#end

##
## Create the portletURL
##
#set ($embeddedPortletURL = $portletURLFactory.create($request, $locPortletId, $layout.plid, "RENDER_PHASE"))
## Make sure it's in popup mode, otherwise it doesn't embed nicely.
#set ($VOID = $embeddedPortletURL.setWindowState("pop_up"))
#set ($VOID = $embeddedPortletURL.setPortletMode("view"))
## You can set parameters if you like
##set ($VOID = $embeddedPortletURL.setParameter("some_parameter", "some_value"))

## The iframe. You'll have to set the width of the iframe.
<iframe frameborder="0" id="${locPortletId}custom_frame" src="${embeddedPortletURL.toString()}" scrolling="no" width="50%"></iframe>

## This is the nifty plugin that will proportion the iframe automatically with the height of the content.
## This only works if the portlet is in the same domain as the portal of course.
<script type="text/javascript">
            AUI().use('aui-resize-iframe', function(A) {
                        A.one('#${locPortletId}custom_frame').plug(A.Plugin.ResizeIframe);
            });
</script>


Embed portlet in HTML div


var url =Liferay.PortletURL.createRenderURL();   
            url.setPortletId('signinaction_WAR_WatsonSiginInportlet'); 
    url.setWindowState('pop_up');
    var myAjaxRequest=A.io.request(url.toString(), {
              dataType: 'html',
              autoLoad: false,
              on: {
               success: function() {
                // A.one('#testestDiv').set('innerHTML',"meera");
                 document.getElementById("login-portlet-content").innerHTML=this.get('responseData');
                 //A.one('#loginBoxDiv').set('innerHTML',this.get('responseData'));
               } }});

myAjaxRequest.start();


Embed portlet in Journal Article


<div id="embedded-welcome-portlet">
  <runtime-portlet name="47" instance="4433" queryString=""/>
</div>

Ref:




Author

0 comments :

Post a Comment

Recent Posts

Recent Posts Widget

Popular Posts