Wednesday 16 December 2015

Single_Page_Application in liferay 6.2 (Dashboard theme)

Topic: In this we are creating a single page application . The below steps it will show you how we can done . before that have a knowledge in single page application.

Explanation:In this first we will create a Dashboard theme using freemaker and styled . after that once the dashboard theme is created and running successfully in server than we will create a singleportlet(Single page application) after that accordint to flt theme , we will do how the single page application works in theme and reloading of server will stop .

The following steps:

Step1:open the eclipse make a liferay project .
(See the image)
















Step2: select the freemaker and styled .


















Step 3:-Go to docroot under _dff folder paste the code.
(the code is in bottom).

Step4:- Then deploy the theme and see the theme is there and select the dashboard1 theme .


note:- next is how to create a single page application 


Step5:create a portlet "Singleportlet".
(See the image)




Step6: In view .jsp paste the code.

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 <portlet:defineObjects />
 <div id="div-1"> This Is Nav Item Click Content-1 </div> 
 <div id="div-2"> This Is Nav Item Click Content-2 </div> 
<div id="div-3"> This Is Nav Item Click Content-3 </div>


Step7: Then deploy the project.


Note: The connection of dashboard theme and single page application.


Step8:  Go to dashboard theme under _dffs folder open the
portel_normal.ftl and paste the below code .

Jus check this line is there .

<body class="${css_class}" onload="pageOnLoad()">
    <div class="super-global-container">
        <div class="container-table">
            <a href="#main-content" id="skip-to-content">
                <@liferay.language key="skip-to-content" />
            </a>
            <#if !hide_header_for_guests || is_signed_in>
                <header id="banner" role="banner">
                    <@liferay.dockbar />
                    <#if show_logo_in_header || show_site_name>
                        <div id="heading">
                            <h1 class="site-title"> <#if show_logo_in_header> <a class="${logo_css_class}" href="${site_default_url}" title="<@liferay.language_format arguments="${site_name}" key="go-to-x" />"> <img alt="${logo_description}" height="${site_logo_height}" src="${site_logo}" width="${site_logo_width}" class="animated fadeIn" /> </a> </#if> <#if show_site_name> <span class="site-name" title="<@liferay.language_format arguments="${site_name}" key="go-to-x" />"> ${site_name} </span> </#if> </h1> </div>
                    </#if>
                </header>
            </#if>
            <#if has_navigation && !page_group.isControlPanel()>
                <#include "${full_templates_path}/navigation.ftl" /> </#if>
            <div class="container-fluid container-table-cell" id="wrapper">
                <div id="content">
                    <#if show_page_title && !page_group.isControlPanel()>
                        <h2 class="page-title"> <span>${the_title}</span> </h2> </#if>
                    <!-- <#if show_breadcrumb && !page_group.isControlPanel()> <nav id="breadcrumbs"><@liferay.breadcrumbs /></nav> </#if>  -->${theme.include(body_top_include)}
                    <!-- <#if selectable> ${theme.include(content_include)} <#else> ${portletDisplay.recycle()}  ${portletDisplay.setTitle(the_title)}  ${theme.wrapPortlet("portlet.ftl", content_include)} </#if> -->
                    <div id="mycontent" style="border:0px solid gray;width:100%;min-height:600px;background-color:#B0E0E6;color:black;"> </div>
                    <#if !is_signed_in> ${theme.runtime('58')} </#if> ${theme.runtime('SinglePortlet_WAR_SinglePortletportlet')} 
                   
                    
                    </div>
                <#if my_show_footer=="true">
                    <footer id="footer" role="contentinfo">
                        <p class="powered-by"> ${my_footer_text} </p>
                    </footer>
                </#if>
            </div>
        </div>
    </div> ${theme.include(body_bottom_include)} ${theme.include(bottom_include)}
 </body>




Step9: Now open the navigation.ftl and check the below code.


<nav class="${nav_css_class} container-table-cell controls-hidden ${menuMinimizeClass}" id="navigation" role="navigation">
    <#if show_menu_minimize>
        <div class="sidebar-toggle-wrapper"> <span onclick="return clickToggleSidebar();" class="icon icon-align-justify"></span> </div>
    </#if>
    <ul aria-label="<@liferay.language key=" site-pages " />" role="menubar" id="menu-list">
        <#list nav_items as nav_item>
            <#assign nav_item_attr_has_popup="" />
            <#assign nav_item_attr_selected="" />
            <#assign nav_item_css_class="" />
            <#if nav_item.isSelected()>
                <#assign nav_item_attr_has_popup="aria-haspopup='true'" />
                <#assign nav_item_attr_selected="aria-selected='true'" />
                <#assign nav_item_css_class="selected" />
                <#if nav_item.isChildSelected()>
                    <#assign nav_item_css_class="" /> </#if>
            </#if>
            <li ${nav_item_attr_selected} class="${nav_item_css_class}" id="layout_${nav_item.getLayoutId()}" role="presentation"> <a aria-labelledby="layout_${nav_item.getLayoutId()}" ${nav_item_attr_has_popup} href="#" id="${nav_item.getName()}" ${nav_item.getTarget()} role="menuitem"><span class="menuitemicon">${nav_item.icon()}</span><span class="menuitemtitle">${nav_item.getName()}</span></a>
                <!-- <a aria-labelledby="layout_${nav_item.getLayoutId()}" ${nav_item_attr_has_popup} href="${nav_item.getURL()}" ${nav_item.getTarget()} role="menuitem"><span class="menuitemicon">${nav_item.icon()}</span><span class="menuitemtitle">${nav_item.getName()}</span></a> -->
                <!-- <#if nav_item.hasChildren() && (nav_item.isSelected() || nav_item.isChildSelected())> <ul class="child-menu" role="menu"> <#list nav_item.getChildren() as nav_child> <#assign nav_child_attr_selected = "" /> <#assign nav_child_css_class = "" /> <#if nav_child.isSelected()> <#assign nav_child_attr_selected = "aria-selected='true'" /> <#assign nav_child_css_class = "selected" /> </#if> </li> <li ${nav_child_attr_selected} class="${nav_child_css_class}" id="layout_${nav_child.getLayoutId()}" role="presentation"> <a aria-labelledby="layout_${nav_child.getLayoutId()}" href="${nav_child.getURL()}" ${nav_child.getTarget()} role="menuitem"><span class="menuitemicon">${nav_child.icon()}</span><span class="menuitemtitle">${nav_child.getName()}</span></a> <#if nav_child.hasChildren() && (nav_child.isSelected() || nav_child.isChildSelected())> <ul class="child-menu" role="menu"> <#list nav_child.getChildren() as child_child> <#assign child_child_attr_selected = "" /> <#assign child_child_css_class = "" /> <#if child_child.isSelected()> <#assign child_child_attr_selected = "aria-selected='true'" /> <#assign child_child_css_class = "selected" /> </#if> <li ${child_child_attr_selected} class="${child_child_css_class}" id="layout_${child_child.getLayoutId()}" role="presentation"> <a aria-labelledby="layout_${child_child.getLayoutId()}" href="${child_child.getURL()}" ${child_child.getTarget()} role="menuitem"><span class="menuitemicon">${child_child.icon()}</span><span class="menuitemtitle">${child_child.getName()}</span></a> </li> </#list> </ul> </#if> </li> </#list> </ul> </#if>-->
            </li>
        </#list>
    </ul>
</nav>
<#if menuMinimizeByDefault>
    <script type="text/javascript">
        console.debug('attempting');
        AUI().ready('aui-base', 'liferay-hudcrumbs', 'liferay-navigation-interaction', 'liferay-sign-in-modal', function(A) { // Auto-open-close navigation bar on hover console.debug('binding'); AUI().one('#navigation').on('hover', function() { AUI().one('#navigation').removeClass("minimizedNav"); }, function() { AUI().one('#navigation').addClass("minimizedNav"); }); });
    </script>
</#if>



Step10:open the main.js and paste the below code



$('#menu-list').on('click', 'a', function(e) {
    console.log('nav click');
    e.preventDefault();
    e.stopPropagation();
    var navItemName = $(this).attr("id");
    console.log("pageName ::" + navItemName.toLowerCase());
    var content = '';
    if (navItemName.toLowerCase() == "welcome") {
        content = $("#div-1").html();
    } else if (navItemName.toLowerCase() == "page1") {
        content = $("#div-2").html();
    } else if (navItemName.toLowerCase() == "page2") {
        content = $("#div-3").html();
    } else {
        content = "Error:Page Not Found."
    }
    console.log("dynemic content is:" + content);
    $("#mycontent").html(content);
    $(this).closest('ul').find('.selected').removeClass('selected');
    $(this).closest('li').addClass('selected');
});

function pageOnLoad() {
    console.log('on page load event call');
    $("#mycontent").html($("#div-1").html());
}



Step11:Now open the portal_normal.ftl then paste the portletid of the single portlet that  
had created first.
For portlet id;
follow te steps
Go to mysql,
use lportal;
select * from portlet ;
paste the portletid and put in the portal_normal.ftl.



Step 12:Now deploy the theme  , now theme will be connected with single page application in liferay 6.2 and last the server will not reload if we click any tabs in navigation panel.




                                        Code_Theme_Spa_Link




                                                       hope this helps you...


.






External_database_each_click_submit

liferay already have a default database "lportal". In this we 

creating a external database on each click on submission .


Explanation:- create account page for registration purpose and in this one form will be there "company name" and some other form also be there ,  now by the click on submit button a external_database would be generated by the company name .

The following steps:-

Step1:create portlet "ShareDatabaseCreate".

Step2:   In View.jsp


<%@page import="javax.portlet.ActionRequest"%>
<%@page import="javax.portlet.PortletURL"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="/WEB-INF/tld/aui.tld" prefix="aui" %>

<portlet:defineObjects />
<%
  PortletURL actionURL=renderResponse.createActionURL();
  actionURL.setParameter(ActionRequest.ACTION_NAME, "addUser");
%>
<aui:form action="<%=actionURL.toString() %>" method="post">
 
<aui:input name="firstName" label="First Name">
<aui:validator name="required" errorMessage="Sorry, firstname required."/>
</aui:input>
<aui:input name="lastName" label="Last Name">
<aui:validator name="required" errorMessage="Sorry, lastname required."/>
</aui:input>
<aui:input name="emailAddress" label="Email Address">
<aui:validator name="required" errorMessage="Sorry, email address required."/>
</aui:input>
<aui:input name="companyName" label="CompanyName">
<aui:validator name="required" errorMessage="Sorry, company name required."/>
</aui:input>
 
</aui:form>


Step3:create service builder and build service's as below


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 6.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_6_2_0.dtd">
<service-builder package-path="com.database">
<author>Abhishek-kumar</author>
<namespace>shareddb</namespace>

<entity name="DatabaseInformation" local-service="true" remote-service="false">
<column name="id" type="long" id-type="increment" />
<column name="userId" type="long" />
<column name="registerCompanyName" type="String" primary="true"/>
<column name="isDatabaseExist" type="Boolean" />
<column name="createDate" type="Date" />
<column name="modifiedDate" type="Date" />
</entity>
</service-builder>

Step4:create action class like below package com.shareddb;


package com.shareddb;

import java.util.Date;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;




import com.database.model.DatabaseInformation;
import com.database.model.impl.DatabaseInformationImpl;
import com.database.service.DatabaseInformationLocalServiceUtil;
import com.database.service.NewTableLocalService;
import com.database.service.NewTableLocalServiceUtil;
import com.jdbctemplate.DatabaseTemplate;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class ActionClass extends MVCPortlet {

DatabaseTemplate databaseTemplate;
public ActionClass() {
databaseTemplate=new DatabaseTemplate();
}

public void addUser(ActionRequest actionRequest,
ActionResponse actionResponse) {

String firstName=ParamUtil.getString(actionRequest, "firstName");
String lastName=ParamUtil.getString(actionRequest, "lastName");
String emailAddress=ParamUtil.getString(actionRequest, "emailAddress");
String companyName=ParamUtil.getString(actionRequest, "companyName");
ThemeDisplay themeDisplay=(ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

long groupIds[]=null;
long organizationIds[]=null;
long roleIds[]=null;
long userGroupIds[]=null;
boolean wantToSendEmail=Boolean.FALSE;

ServiceContext serviceContext=new ServiceContext();
User user=null;
try {

user=UserServiceUtil.addUser(themeDisplay.getCompanyId(), true, StringPool.BLANK, StringPool.BLANK, true, StringPool.BLANK, emailAddress, 0, StringPool.BLANK, LocaleUtil.getDefault(), firstName, StringPool.BLANK, lastName, 0, 0, true, 1, 1, 1970, "", groupIds, organizationIds, roleIds, userGroupIds,wantToSendEmail, serviceContext);
//UserLocalServiceUtil.addUser(0L, themeDisplay.getCompanyId(), true, StringPool.BLANK, StringPool.BLANK, true, StringPool.BLANK, emailAddress, 0L, StringPool.BLANK, LocaleUtil.getDefault(), firstName, StringPool.BLANK, lastName, 0, 0, Boolean.TRUE, 1, 1, 1986, StringPool.BLANK, groupIds, organizationIds, roleIds, userGroupIds, wantToSendEmail, serviceContext);
} catch (PortalException e) {
//e.printStackTrace();
} catch (SystemException e) {
//e.printStackTrace();
}

System.out.println(user.getUserId());

if(Validator.isNotNull(user)){
System.out.println("--come1--");
DatabaseInformation databaseInformation=null;
try {
databaseInformation=DatabaseInformationLocalServiceUtil.fetchDatabaseInformation(companyName);
} catch (SystemException e) {
e.printStackTrace();
}
System.out.println("--come2--");
if(Validator.isNull(databaseInformation)){


System.out.println("databaseInformation is null");
//if data is not available in the db
boolean isDatabaseCreated = databaseTemplate.isDatabaseGenerated(Long.toString(user.getUserId()),MYSQL_USERNAME,MYSQL_PASSWORD);
_log.info("database object created : " + isDatabaseCreated);
if(Validator.isNotNull(isDatabaseCreated)){

databaseInformation=new DatabaseInformationImpl();
databaseInformation.setUserId(user.getUserId());
databaseInformation.setRegisterCompanyName(companyName);
databaseInformation.setIsDatabaseExist(Boolean.TRUE);
databaseInformation.setCreateDate(new Date());
databaseInformation.setModifiedDate(new Date());
try {
databaseInformation=DatabaseInformationLocalServiceUtil.addDatabaseInformation(databaseInformation);
} catch (SystemException e) {
//e.printStackTrace();
}
if(Validator.isNotNull(databaseInformation)){
//do something here/coding for table creation.
//call table creation template.
}
}
}else{
//if database is available

}
}
}

private static final String MYSQL_USERNAME = "root";
private static final String MYSQL_PASSWORD = "root";
private Log _log = LogFactoryUtil.getLog(ActionClass.class);

}



Step5:Create JDBC Template as below

 com.jdbc.template



Note:-paste database template.java
      paste table template.java















Step8: Deploy your project.

Step9:Run your project and check user_ tables .



                            Code_for_External_Database_Code

                                                    
                                                            
                                               hope this helps you...

Next blog : Single-page-application in  liferay 6.2 !!