Monday, August 20, 2012

AUI form Validation using AUI script

Sample example

[sourcecode language="html"]

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>

<aui:form name="fm2" action="" method="post">
<table>
<tr>
<td>
<aui:input name="number" value='${number}' label="Enter number#" inlineLabel="left"/>
</td>
<td>
<aui:button type="submit" name="numberSearch" value="Number Search" />
</td>
</tr>
</table>
</aui:form>

[/sourcecode]
[sourcecode langauge="javascript"]

<aui:script>
AUI().ready('aui-form-validator', 'aui-overlay-context-panel', function(A) {

// Extending Alloy Default values for FormValidator STRINGS and RULES
A.mix(
YUI.AUI.defaults.FormValidator.STRINGS,
{
customRule: 'Please enter number only.'
},
true
);

A.mix(
YUI.AUI.defaults.FormValidator.RULES,
{
customRule: function(val, fieldNode, ruleValue) {
return (!isNaN(val));
}
},
true
);

var validator1 = new A.FormValidator({
boundingBox: '#fm2',
validateOnBlur: true,
selectText: true,
rules: {
<portlet:namespace />number: {
required: true,
rangeLength: ['4','10'],
customRule:true
}
},
fieldStrings: {
<portlet:namespace />number: {
required: ' Number is a required field'
}

on: {
submit: function(event) {
var formEvent = event.validator.formEvent;
}
}
});
});

</aui:script>

[/sourcecode]

form Validation using AUI(Alloy User Interface) script

#####################Rules extracted from CSS classes#####################

Copy paste the below CSS code inside <head> tag.

[sourcecode language="java"]
<style type="text/css">

fieldset {
border: 1px solid #CCCCCC;
margin: 10px;
padding: 10px;
font-size: 13px;
}

legend {
font-size: 20px;
font-weight: bold;
}

input[type=text], textarea, select {
border: 1px solid #777;
padding: 3px;
}

.aui-form-validator-stack-error {
color: red;
display: block;
font-weight: normal;
font-style: italic;
margin: 3px 0;
}

.aui-form-validator-error-container {}
.aui-form-validator-valid-container {}

.aui-form-validator-error {
background: lightPink;
}

.aui-form-validator-valid {
background: lightGreen;
}
</style>
[/sourcecode]

Add the below code in <body> tag.

[sourcecode language="java"]

<h1>Liferay AUI - FormValidator</h1>

<form id="fm1" action="" name="fm1">
<fieldset><legend>Example 1 - Rules extracted from CSS classes</legend>
<p class="aui-field"><label class="aui-field-label" for="name2">Name:</label>
<input id="name2" class="aui-field-required" type="text" name="name" /></p>
<label class="aui-field-label" for="email2">Email:</label>
<input id="email2" class="aui-field-required aui-field-email" type="text" name="email" />

<label class="aui-field-label" for="age2">Age:</label>
<input id="age2" class="aui-field-digits" type="text" name="age" /></fieldset>

<p>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</p>
</form>
[/sourcecode]

Add the below script code after the </form> tag.

[sourcecode language="javascript"]

<aui:script>
AUI().ready('aui-form-validator', 'aui-overlay-context-panel', function(A) {

var validator1 = new A.FormValidator({
boundingBox: '#fm1',
});

on: {
submitError: function(event) {
var formEvent = event.validator.formEvent;
var errors = event.validator.errors;
},

submit: function(event) {
var formEvent = event.validator.formEvent;
}
}
});
});
</aui:script>
[/sourcecode]

checkPoint:

#####################Rules passed on the constructor#####################
[sourcecode language="html"]
<form action="" name="fm2">
<fieldset id="simpleForm">
<legend>Example 2 - Rules passed on the constructor</legend>
<p>
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age" id="age" />
</p>

<p>
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</p>
</fieldset>
</form>
[/sourcecode]
Add the below script code after the </form> tag.
[sourcecode language="javascript"]
<aui:script>

AUI().ready('aui-form-validator', 'aui-overlay-context-panel', function(A) {

    //custom Rules
    A.mix(
        YUI.AUI.defaults.FormValidator.STRINGS,
        {
            customRule: 'Type the number 55.',
        },
        true
    );

    A.mix(
        YUI.AUI.defaults.FormValidator.RULES,
        {
            customRule: function(val, fieldNode, ruleValue) {
                return (val == 55);
            }        
        },
        true
    );

    var validator2 = new A.FormValidator({
        boundingBox: document.fm2,

        fieldContainer: 'p',
        rules: {

            age: {
                customRule: true,
                digits: true,
                range: [18, 50]
                // min: 18,
                // max: 50
            },

            email: {
                required: true,
                email: true
            },

            name: {
                required: true,
                rangeLength: [2,50]
            }
        },

        //custom message
        fieldStrings: {
            email: {
                email: 'Type your email in this field.'
            },
            name: {
                required: 'Required field with a custom message.'
            }
        },

        on: {
            submitError: function(event) {
                var formEvent = event.validator.formEvent;
                var errors = event.validator.errors;
            },

            submit: function(event) {
                var formEvent = event.validator.formEvent;
            }
        }
    });
});

</aui:script>
[/sourcecode]
Checkpoint:

Monday, January 23, 2012

Displaying list of video files in liferay?

upload video file in document library click here

Show/Displaying  a list of video file:
Use Asset Publisher portlet.
To show only video files configure "Asset Publisher portlet" follow the below steps

a. Asset Type >> select Filter then remove all option other than "Document Library Document" in Current field.
b. Displayed assets must match these rules. >> selecting tag(video).
c. save the configuration.

How to upload .mp3/.mp4/.mov... files in Liferay?

To upload .mp3/.mp4/.mov ... files follow the below steps.

Step1:

Add the below key in portal-ext.properties file

or

create a new hook portlet to overhide the portal.properties

[sourcecode language="html"]

#
# A file extension of * will permit all file extensions.
#
# You can map a GIF for the extension by adding the image to the theme's
# image display and document library folder. The wildcard extension of *
# will be ignored. For example, the default image for the DOC extension
# would be found in: /html/themes/_unstyled/images/document_library/doc.gif.
#
dl.file.extensions=\
.bmp,.css,.doc,.docx,.dot,.gif,.gz,.htm,.html,.jpg,.js,.lar,.odb,.odf,\
.odg,.odp,.ods,.odt,.pdf,.png,.ppt,.pptx,.rtf,.swf,.sxc,.sxi,.sxw,.tar,\
.tiff,.tgz,.txt,.vsd,.xls,.xlsx,.xml,.zip,.jrxml,.mp4,.mp3,.mov

[/sourcecode]

Step2:

Upload the video files in document library add a tag video.

Hint: we are adding tag here to display only video file.

Displaying list of video files in liferay? check here

Thursday, January 5, 2012

Liferay In Kannada language coming shortly...

Liferay In Kannada language coming shortly


Language Portlet



Dock



Control Panel

Generate PDF file using java

[sourcecode language="java"]
package com.liferay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {

public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("E:/01_Installing-liferay-bundle.pdf"));

Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello Rajeeva Lochana.B.R"));
document.add(new Paragraph(new Date().toString()));

document.close();
file.close();

} catch (Exception e) {

e.printStackTrace();
}
}
}
[/sourcecode]

Create a URL based on PortletId in Liferay

Necessary package need to Import in JSP page
[sourcecode language="html" wraplines="false"]
    <%@ page import="com.liferay.portlet.PortletURLFactoryUtil"%>
    <%@ page import="com.liferay.portal.kernel.portlet.LiferayPortletURL"%>
    <%@ page import="javax.portlet.PortletRequest"%>
    <%@ page import="javax.portlet.PortletURL"%>
    <%@ page import="javax.servlet.http.HttpServletRequest"%>
[/sourcecode]

Syntax:
[sourcecode language="java" wraplines="false"]
portletURL URL = PortletURLFactoryUtil.create(request, portletId, plid, lifecycle);
[/sourcecode]
OR

[sourcecode language="java" wraplines="false"]
LiferayPortletURL URL = PortletURLFactoryUtil.create(request, portletId, plid, lifecycle);
[/sourcecode]

For creating PortletRequest URL
[sourcecode language="html" wraplines="false"]

ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
LiferayPortletURL renderURL = PortletURLFactoryUtil.create(request, portletId, plid, PortletRequest.RENDER_PHASE);
renderURL.setWindowState(WindowState.NORMAL); //to set windowsState
renderURL.setPortletMode(PortletMode.VIEW);  //to set portletmode
renderURL.setParameter(arg0,arg1);  /to set the parameter ex:ipcActionURL.setParameter("struts_action",/etc/reports/add);

LiferayPortletURL actionURL = PortletURLFactoryUtil.create(request, "portletId", plid, PortletRequest.ACTION_PHASE);
actionURL.setWindowState(WindowState.NORMAL); //to set windowsState
actionURL.setPortletMode(PortletMode.VIEW);  //to set portletmode
actionURL.setParameter(arg0,arg1);  /to set the parameter ex:ipcActionURL.setParameter("struts_action",/etc/reports/add);
[/sourcecode]

PortletId:
          To fetch the current portletId or portletName.
[sourcecode language="java" wraplines="false"]
            portletDisplay.getId();
            portletDisplay.getPortletName();
[/sourcecode]

plid (Portlet Layout id):
         We need to mention plid, based on this plid it will redirect that particular
         page.//for InterPortlet communication(IPC)

[sourcecode language="java" wraplines="false"]
<%= LayoutLocalServiceUtil.getFriendlyURLLayout(themeDisplay.getScopeGroupId(), false, "/layoutName").getPlid() %>
[/sourcecode]
OR
[sourcecode language="java" wraplines="false"]
<%=themeDisplay.getPlid()%>
[/sourcecode]

Lifecycle/PortletRequest:
         Two types of portlet request we can use here.



  1.   PortletRequest.RENDER_PHASE

  2.   PortletRequest.ACTION_PHASE

  3.   PortletRequest.EVENT_PHASE

  4.   PortletRequest.RESOURCE_PHASE

  5.   PortletRequest.LIFECYCLE_PHASE

Insert text into PDF file using java

Required jars:

  • itext-1.1.4.jar

  • itext-rups-2.1.3.jar

  • jdtaus-editor-client-application-1.0-beta-10.jar

  • PDFRenderer.jar


[sourcecode language="java"]

package com.liferay;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class TextToPDF{
public static void main(String arg[]){
try{
InputStreamReader in= new InputStreamReader(System.in);
BufferedReader bin= new BufferedReader(in);
System.out.println("Enter text:");
String text=bin.readLine();
Document document = new Document(PageSize.A4, 36, 72, 108, 180);
PdfWriter.getInstance(document,new FileOutputStream("E:/workspace/rnd/javarnd/pdfFile.pdf"));
document.open();
document.add(new Paragraph(text));
System.out.println("Text is inserted into pdf file");
document.close();
}catch(Exception e){}
}
}
[/sourcecode]

PDF file to image(.png) conversion using java

Required jars:

  •   itext-1.1.4.jar

  •  itext-rups-2.1.3.jar

  •  jdtaus-editor-client-application-1.0-beta-10.jar

  •  PDFRenderer.jar


[sourcecode language="java"]
package com.liferay;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Transparency;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;

public class ImageMain {

public static void setup() throws IOException {

//load a pdf from a byte buffer
File file = new File("E:/01_Installing-liferay-bundle.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);

int numPgs = pdffile.getNumPages();

for (int i=0; i<numPgs; i++)
{
// draw the first page to an image
PDFPage page = pdffile.getPage(i);

//get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0,0,
(int)page.getBBox().getWidth(),
(int)page.getBBox().getHeight());

//generate the image
Image img = page.getImage(
rect.width, rect.height, //width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);

//save it as a file
BufferedImage bImg = toBufferedImage( img );
File yourImageFile = new File("E:/workspace/rnd/javarnd/page_" + i + ".png");
ImageIO.write( bImg,"png",yourImageFile);
}
}

// This method returns a buffered image with the contents of an image
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}

// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();

// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;

// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
System.out.println("The system does not have a screen");
}

if (bimage == null) {
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}

// Copy image to buffered image
Graphics g = bimage.createGraphics();

// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();

return bimage;
}

public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
ImageMain.setup();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}

[/sourcecode]

Tuesday, January 3, 2012

MVC Generic Jsp Portlet

[sourcecode language="html"]
liferay-display.xml
<?xml version="1.0"?>
<!DOCTYPE display PUBLIC "-//Liferay//DTD Display 5.2.0//EN" "http://www.liferay.com/dtd/liferay-display_5_2_0.dtd">
<display>
<category name="category.training">
<portlet id="liferay-publisher" />
<portlet id="liferay-book" />
</category>
</display>

[/sourcecode]
[sourcecode language="html"]
liferay-portlet.xml
<?xml version="1.0"?>
<!DOCTYPE liferay-portlet-app PUBLIC "-//Liferay//DTD Portlet Application 5.2.0//EN" "http://www.liferay.com/dtd/liferay-portlet-app_5_2_0.dtd">

<liferay-portlet-app>
<portlet>
<portlet-name>liferay-publisher</portlet-name>
<icon>/images/icon.png</icon>
<instanceable>false</instanceable>
<header-portlet-css>/css/test.css</header-portlet-css>
<header-portlet-javascript>/js/test.js</header-portlet-javascript>
</portlet>

<portlet>
<portlet-name>liferay-book</portlet-name>
<icon>/images/icon.png</icon>
<instanceable>false</instanceable>
<header-portlet-css>/css/test.css</header-portlet-css>
<header-portlet-javascript>/js/test.js</header-portlet-javascript>
</portlet>

<role-mapper>
<role-name>administrator</role-name>
<role-link>Administrator</role-link>
</role-mapper>
<role-mapper>
<role-name>guest</role-name>
<role-link>Guest</role-link>
</role-mapper>
<role-mapper>
<role-name>power-user</role-name>
<role-link>Power User</role-link>
</role-mapper>
<role-mapper>
<role-name>user</role-name>
<role-link>User</role-link>
</role-mapper>
</liferay-portlet-app>

[/sourcecode]
[sourcecode language="html"]
portlet.xml
<?xml version="1.0"?>

<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"
version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd">
<portlet>
<portlet-name>liferay-publisher</portlet-name>
<display-name>Liferay Publisher</display-name>
<portlet-class>com.liferay.training.library.portlet.PublisherPortlet</portlet-class>
<init-param>
<name>view-jsp</name>
<value>/html/publisher/view.jsp</value>
</init-param>
<init-param>
<name>edit-jsp</name>
<value>/html/publisher/edit.jsp</value>
</init-param>
<init-param>
<name>edit-publisher-jsp</name>
<value>/html/publisher/editPublisher.jsp</value>
</init-param>
<init-param>
<name>help-jsp</name>
<value>/html/publisher/help.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
<portlet-mode>edit</portlet-mode>
<portlet-mode>help</portlet-mode>
</supports>
<resource-bundle>content.Language</resource-bundle>
<portlet-info>
<title>Liferay Publisher</title>
<short-title>Liferay Publisher</short-title>
<keywords>Liferay Publisher</keywords>
</portlet-info>
<!-- Portlet preferences (configurable by user in portlet EDIT mode) -->
<portlet-preferences>
<preference>
<name>rowsPerPage</name>
<value>20</value>
</preference>
<preference>
<name>unitedStatesPhoneFormat</name>
<value>###-###-####</value>
</preference>
</portlet-preferences>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
<portlet>
<portlet-name>liferay-book</portlet-name>
<display-name>Liferay Book</display-name>
<portlet-class>com.liferay.training.library.portlet.BookPortlet</portlet-class>
<init-param>
<name>view-jsp</name>
<value>/html/book/view.jsp</value>
</init-param>
<init-param>
<name>edit-jsp</name>
<value>/html/book/edit.jsp</value>
</init-param>
<init-param>
<name>edit-book-jsp</name>
<value>/html/book/editBook.jsp</value>
</init-param>
<init-param>
<name>help-jsp</name>
<value>/html/book/help.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
<portlet-mode>help</portlet-mode>
</supports>
<!-- Resource Bundle -->
<resource-bundle>content.Language</resource-bundle>
<portlet-info>
<title>Liferay Books</title>
<short-title>Liferay Books</short-title>
<keywords>Liferay Books</keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
</portlet-app>
[/sourcecode]
[sourcecode language="html"]
service.xml
<?xml version="1.0"?>
<!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 5.2.0//EN" "http://www.liferay.com/dtd/liferay-service-builder_5_2_0.dtd">
<service-builder package-path="com.liferay.training.library">
<!--
Author will be inserted into Java Doc comments in generated classes
-->
<author>Joe Bloggs</author>
<!--
Tables in the database will have their names prepended with "Library_"
-->
<namespace>Library</namespace>
<!-- Define the entity for the Library_Publisher table -->
<entity name="Publisher" local-service="true" remote-service="false">

<!-- Primary key column -->
<column name="publisherId" type="long" primary="true" />

<!-- Foreign key columns -->
<column name="companyId" type="long" />
<column name="groupId" type="long" />

<!-- Other columns -->
<column name="name" type="String" />
<column name="emailAddress" type="String" />
<column name="website" type="String" />
<column name="phoneNumber" type="String" />

<!-- Sort order -->
<order by="asc">
<order-column name="name" />
</order>

<!-- Finder Methods -->
<finder name="GroupId" return-type="Collection">
<finder-column name="groupId" />
</finder>
</entity>

<!-- Define the entity for the Library_Book table -->
<entity name="Book" local-service="true" remote-service="false">

<!-- Primary key column -->
<column name="bookId" type="long" primary="true" />

<!-- Foreign key columns -->
<column name="companyId" type="long" />
<column name="groupId" type="long" />
<column name="publisherId" type="long" />

<!-- Other columns -->
<column name="title" type="String" />
<column name="authorName" type="String" />
<column name="publicationDate" type="Date" />

<!-- Sort order -->
<order by="asc">
<order-column name="title" />
</order>

<!-- Finder Methods -->
<finder name="GroupId" return-type="Collection">
<finder-column name="groupId" />
</finder>
</entity>
</service-builder>

[/sourcecode]
[sourcecode language="html"]

portal.properties

resource.actions.configs=resource-actions/default.xml

portlet.prorerties

resource.actions.configs=resource-actions/default.xml

[/sourcecode]


[sourcecode language="java"]

package com.liferay.training.library.portlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.training.library.model.Book;
import com.liferay.training.library.model.Publisher;
import com.liferay.training.library.model.impl.BookImpl;
import com.liferay.training.library.service.BookLocalServiceUtil;
import com.liferay.training.library.service.PublisherLocalServiceUtil;

/**
* The Liferay Book Portlet allows the end user to create their own library of
* books. It is linked with the Publishers portlet which tracks the publishers
* of books.
*
* @author Steven Cao
* @author Rich Sezov
*/
public class BookPortlet extends GenericPortlet {

/**
* Portlet API's init method. We will use this to define all of the pages to
* which the user can navigate.
*
* @throws javax.portlet.PortletException
*/
public void init()
throws PortletException {

// Edit Mode Pages
editJSP = getInitParameter("edit-jsp");

// Help Mode Pages
helpJSP = getInitParameter("help-jsp");

// View Mode Pages
viewJSP = getInitParameter("view-jsp");

// View Mode Edit Book
editBookJSP = getInitParameter("edit-book-jsp");
}

/**
* Convenience method for including JSPs.
*
* @param path
* @param renderRequest
* @param renderResponse
* @throws IOException
* @throws PortletException
*/
protected void include(
String path, RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

PortletRequestDispatcher portletRequestDispatcher =
getPortletContext().getRequestDispatcher(path);

if (portletRequestDispatcher == null) {
// do nothing
// _log.error(path + " is not a valid include");
}
else {
portletRequestDispatcher.include(renderRequest, renderResponse);
}
}

/**
* Portlet API's doView method.
*
* @param renderRequest
* @param renderResponse
* @throws java.io.IOException
* @throws javax.portlet.PortletException
*/
public void doView(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

String jsp = (String) renderRequest.getParameter("view");
if (jsp == null || jsp.equals("")) {
showViewDefault(renderRequest, renderResponse);
}
else if (jsp.equalsIgnoreCase("editBook")) {
try {
showViewEditBook(renderRequest, renderResponse);
} catch (Exception ex) {
_log.debug(ex);
try {
showViewDefault(renderRequest, renderResponse);
} catch (Exception ex1) {
_log.debug(ex1);
}
}
}
}

/**
* Portlet API's doEdit method.
*
* @param renderRequest
* @param renderResponse
* @throws java.io.IOException
* @throws javax.portlet.PortletException
*/

public void doEdit(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

showEditDefault(renderRequest, renderResponse);
}

/**
* Portlet API's doHelp method. Currently there is a simple string.
*
* @param renderRequest
* @param renderResponse
* @throws java.io.IOException
* @throws javax.portlet.PortletException
*/

public void doHelp(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

include(helpJSP, renderRequest, renderResponse);
}

/**
* View Mode's default view. This view displays the list of books and a
* button which allows users to navigate to the Edit Books screen.
*
* @param renderRequest
* @param renderResponse
* @throws IOException
* @throws PortletException
*/
public void showViewDefault(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

long groupId = themeDisplay.getScopeGroupId();

PermissionChecker permissionChecker =
themeDisplay.getPermissionChecker();

boolean hasAddPermission =
permissionChecker.hasPermission(
groupId, "com.liferay.training.library.model", groupId, "ADD_BOOK");

List<Book> tempResults = Collections.EMPTY_LIST;
try {
tempResults = BookLocalServiceUtil.findAllInGroup(groupId);
} catch (SystemException e) {
_log.debug(e);
}


renderRequest.setAttribute("tempResults", tempResults);
renderRequest.setAttribute("hasAddPermission", hasAddPermission);

PortletURL addBookURL = renderResponse.createActionURL();
addBookURL.setParameter("javax.portlet.action", "newBook");
renderRequest.setAttribute("addBookURL", addBookURL.toString());

include(viewJSP, renderRequest, renderResponse);
}

/**
* This method shows the Edit Book screen in View mode. This screen allows
* users to add or edit a book.
*
* @param renderRequest
* @param renderResponse
* @throws IOException
* @throws PortletException
*/
public void showViewEditBook(
RenderRequest renderRequest, RenderResponse renderResponse)
throws Exception {
PortletURL editURL = renderResponse.createActionURL();
String editType = (String)renderRequest.getParameter("editType");
if (editType.equalsIgnoreCase("edit")) {
editURL.setParameter("javax.portlet.action", "updateBook");
long bookID = Long.parseLong(renderRequest.getParameter("bookID"));
Book book = BookLocalServiceUtil.getBook(bookID);
String date = dateToJsp (renderRequest, book.getPublicationDate());
renderRequest.setAttribute("date", date);
renderRequest.setAttribute("book", book);
} else {
editURL.setParameter("javax.portlet.action", "addBook");
Book errorBook = (Book)renderRequest.getAttribute("errorBook");
if (errorBook!=null) {
renderRequest.setAttribute("book", errorBook);
String date = dateToJsp (renderRequest, errorBook.getPublicationDate());
renderRequest.setAttribute("date", date);
} else {
BookImpl blankBook = new BookImpl();
blankBook.setPublicationDate(new Date());
renderRequest.setAttribute("book", blankBook);
String date = dateToJsp (renderRequest, blankBook.getPublicationDate());
renderRequest.setAttribute("date", date);
}

}
ThemeDisplay themeDisplay =
(ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
List<Publisher> publisherList = PublisherLocalServiceUtil.findAllInGroup(themeDisplay.getScopeGroupId());
renderRequest.setAttribute("publisherList", publisherList);
renderRequest.setAttribute("editURL", editURL.toString());
include(editBookJSP, renderRequest, renderResponse);
}

private String dateToJsp (RenderRequest request, Date date) {
PortletPreferences prefs = request.getPreferences();
SimpleDateFormat format = new SimpleDateFormat(prefs.getValue("dateFormat", "yyyy/MM/dd"));
String stringDate = format.format(date);
return stringDate;
}

/**
* This method shows the default page for Edit mode. This page allows the
* user to choose the number of books displayed per "page" and also sets the
* date format.
*
* @param renderRequest
* @param renderResponse
* @throws javax.portlet.PortletException
* @throws java.io.IOException
*/
public void showEditDefault(
RenderRequest renderRequest, RenderResponse renderResponse)
throws PortletException, IOException {

include(editJSP, renderRequest, renderResponse);
}

/* Portlet Actions */

@ProcessAction(name = "newBook")
public void newBook (ActionRequest request, ActionResponse response) {
response.setRenderParameter("view", "editBook");
response.setRenderParameter("editType", "add");
}

/**
* This Action adds a new book to the database.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "addBook")
public void addBook(ActionRequest request, ActionResponse response)
throws Exception {
ArrayList<String> errors = new ArrayList();
PortletPreferences prefs = request.getPreferences();
SimpleDateFormat format = new SimpleDateFormat(prefs.getValue("dateFormat", "yyyy/MM/dd"));
String stringDate = ParamUtil.getString(request, "bookPublicationDate");
if (BookValidator.isDate(format, stringDate)) {
Book book = bookFromRequest(request);
if (BookValidator.validateBook(book, errors)) {
BookLocalServiceUtil.addBook(book);
response.setRenderParameter("view", "");
SessionMessages.add(request, "book-added");
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
response.setRenderParameter("view", "editBook");
response.setRenderParameter("editType", "add");
request.setAttribute("errorBook", book);
}
}

}

/**
* This Action shows the Edit screen.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "editBook")
public void editBook(ActionRequest request, ActionResponse response)
throws Exception {
long bookKey = ParamUtil.getLong(request, "resourcePrimKey");
if (Validator.isNotNull(bookKey)) {
response.setRenderParameter("bookID", Long.toString(bookKey));
response.setRenderParameter("view", "editBook");
response.setRenderParameter("editType", "edit");
}
}

/**
* This Action deletes a book from the database.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "deleteBook")
public void deleteBook(ActionRequest request, ActionResponse response)
throws Exception {
long bookId = ParamUtil.getLong(request, "resourcePrimKey");

if (Validator.isNotNull(bookId)) {

BookLocalServiceUtil.getBook(bookId);
BookLocalServiceUtil.deleteBook(bookId);
SessionMessages.add(request, "book-deleted");
}
else {
SessionErrors.add(request, "error-deleting");
}
}

/**
* This Action updates the database record of an existing book.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "updateBook")
public void updateBook(ActionRequest request, ActionResponse response)
throws Exception {
ArrayList<String> errors = new ArrayList();
PortletPreferences prefs = request.getPreferences();
SimpleDateFormat format = new SimpleDateFormat(prefs.getValue("dateFormat", "yyyy/MM/dd"));
String stringDate = ParamUtil.getString(request, "bookPublicationDate");
if (BookValidator.isDate(format, stringDate)) {
Book book = bookFromRequest(request);
if (BookValidator.validateBook(book, errors)) {
BookLocalServiceUtil.updateBook(book);
response.setRenderParameter("view", "");
SessionMessages.add(request, "book-updated");
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
response.setRenderParameter("bookID", Long.toString(book.getPrimaryKey()));
response.setRenderParameter("view", "editBook");
response.setRenderParameter("editType", "add");
request.setAttribute("errorBook", book);
}
}
}

/**
* This Action sets the preferences for how many books can be viewed per
* page and the format for the date.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "setBookPref")
public void setBookPref(ActionRequest request, ActionResponse response)
throws Exception {
String rowsPerPage = ParamUtil.getString(request, "rowsPerPage");
String dateFormat = ParamUtil.getString(request, "dateFormat");

ArrayList<String> errors = new ArrayList();
if (BookValidator.validateEditBook(rowsPerPage, dateFormat, errors)) {
response.setRenderParameter("rowsPerPage", "");
response.setRenderParameter("dateFormat", "");

PortletPreferences prefs = request.getPreferences();
prefs.setValue("rowsPerPage", rowsPerPage);
prefs.setValue("dateFormat", dateFormat);
prefs.store();

SessionMessages.add(request, "operate-successfully");
}
}

private Book bookFromRequest (ActionRequest request) {
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
BookImpl book = new BookImpl();
book.setTitle(ParamUtil.getString(request, "bookTitle"));
book.setAuthorName(ParamUtil.getString(request, "bookAuthorName"));
PortletPreferences prefs = request.getPreferences();
SimpleDateFormat format = new SimpleDateFormat(prefs.getValue("dateFormat", "yyyy/MM/dd"));
try {
book.setPublicationDate(format.parse(ParamUtil.getString(request, "bookPublicationDate")));
} catch (ParseException ex) {
book.setPublicationDate(new Date());
}
book.setPublisherId(ParamUtil.getLong(request, "publisherId"));
book.setPrimaryKey(ParamUtil.getLong(request, "resourcePrimKey"));
book.setCompanyId(themeDisplay.getCompanyId());
book.setGroupId(themeDisplay.getScopeGroupId());
return book;
}

protected String editBookJSP;
protected String editJSP;
protected String helpJSP;
protected String viewJSP;

private static Log _log = LogFactoryUtil.getLog(BookPortlet.class);

}
[/sourcecode]

[sourcecode language="java" wraplines="true"]

package com.liferay.training.library.portlet;

import java.text.SimpleDateFormat;

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

import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.training.library.model.Book;
import java.util.List;

public class BookValidator {

/**
* Validate book
*
* @param request
* @param response
* @param format
*/

public static boolean validateBook(
Book book, List errors) {
boolean valid = true;
if (Validator.isNull(book.getTitle())) {
errors.add("booktitle-required");
valid = false;
}
if (Validator.isNull(book.getAuthorName())) {
errors.add("bookauthorname-required");
valid = false;
}
if (Validator.isNull(book.getPublicationDate())) {
errors.add("bookpublicationdate-required");
valid = false;
}
if (Validator.isNull(book.getPublisherId())) {
errors.add("publisher-required");
valid = false;
}
return valid;
}

public static boolean validateEditBook(
String rowsPerPage, String dateFormat, List errors) {
boolean valid = true;
if (Validator.isNull(rowsPerPage)) {
errors.add("rowsperpage-required");
valid = false;
}
else if (!Validator.isNumber(rowsPerPage)) {
errors.add("rowsperpage-invalid");
valid = false;
}
else if (Validator.isNull(dateFormat)) {
errors.add("dateformat-required");
valid = false;
}
return valid;
}

/**
* Check if the date is with the corresponding format
*
* @param format
* @param date
*/
public static boolean isDate(SimpleDateFormat format, String date) {

try {
format.format(format.parse(date));
return true;
}
catch (Exception e) {
return false;
}
}
}

[/sourcecode]

[sourcecode language="java" wraplines="true"]
/**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.liferay.training.library.portlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletURL;
import javax.portlet.ProcessAction;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.SystemException;
import com.liferay.portal.model.Group;
import com.liferay.portal.kernel.dao.search.ResultRow;
import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.ActionKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.training.library.model.Publisher;
import com.liferay.training.library.model.impl.PublisherImpl;
import com.liferay.training.library.service.PublisherLocalServiceUtil;

/**
* Liferay Publisher Portlet, used as an example for Liferay Developer
* Training.
*
* @author Steven Cao
* @author Rich Sezov
*
*/
public class PublisherPortlet extends GenericPortlet {

public void init() throws PortletException {
editJSP = getInitParameter("edit-jsp");
helpJSP = getInitParameter("help-jsp");
viewJSP = getInitParameter("view-jsp");
editPublisherJSP = getInitParameter("edit-publisher-jsp");
}

public void doDispatch(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

String jspPage = renderRequest.getParameter("jspPage");

if (jspPage != null) {
include(jspPage, renderRequest, renderResponse);
}
else {
super.doDispatch(renderRequest, renderResponse);
}
}

public void doEdit(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

if (renderRequest.getPreferences() == null) {
super.doEdit(renderRequest, renderResponse);
}
else {
include(editJSP, renderRequest, renderResponse);
}
}

public void doHelp(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

include(helpJSP, renderRequest, renderResponse);
}

/**
* Portlet API's doView method. This method forwards processing to the proper
* JSP based on a parameter.
*
* @param renderRequest
* @param renderResponse
* @throws java.io.IOException
* @throws javax.portlet.PortletException
*/
public void doView(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {

String jsp = (String) renderRequest.getParameter("view");
if (jsp == null || jsp.equals("")) {
try {
showViewDefault(renderRequest, renderResponse);
}
catch (SystemException e) {
SessionErrors.add(renderRequest, "error-retrieving-publisher");
}
}
else if (jsp.equalsIgnoreCase("editPublisher")) {
try {
showViewEditPublisher(renderRequest, renderResponse);
} catch (Exception ex) {
_log.debug(ex);
try {
showViewDefault(renderRequest, renderResponse);
} catch (SystemException ex1) {
_log.debug(ex1);
}
}
}
}

/**
* View Mode's default view. This view displays the list of publishers and a
* button which allows users to navigate to the Edit Publishers screen.
*
* @param renderRequest
* @param renderResponse
* @throws IOException
* @throws PortletException
*/
public void showViewDefault(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException, SystemException {

ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);

long groupId = themeDisplay.getScopeGroupId();

PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();
boolean hasAddPermission = permissionChecker.hasPermission(groupId, "com.liferay.training.library.model", groupId, "ADD_PUBLISHER" );
boolean hasConfigurePermission = permissionChecker.hasPermission(groupId, Group.class.getName(), groupId, ActionKeys.PERMISSIONS );

List<Publisher> tempResults = PublisherLocalServiceUtil.findAllInGroup(groupId);

renderRequest.setAttribute("tempResults", tempResults);
renderRequest.setAttribute("hasAddPermission", hasAddPermission);
renderRequest.setAttribute("hasConfigurePermission", hasConfigurePermission);

PortletURL addPublisherURL = renderResponse.createActionURL();
addPublisherURL.setParameter("javax.portlet.action", "newPublisher");
renderRequest.setAttribute("addPublisherURL", addPublisherURL.toString());

include(viewJSP, renderRequest, renderResponse);
}

protected void include(
String path, RenderRequest renderRequest,
RenderResponse renderResponse)
throws IOException, PortletException {

PortletRequestDispatcher portletRequestDispatcher =
getPortletContext().getRequestDispatcher(path);

if (portletRequestDispatcher == null) {
_log.error(path + " is not a valid include");
}
else {
portletRequestDispatcher.include(renderRequest, renderResponse);
}
}

/**
* This Action causes the Edit Publisher form to be displayed in its
* add mode.
*
* @param request
* @param response
*/
@ProcessAction(name = "newPublisher")
public void newPublisher (ActionRequest request, ActionResponse response) {
response.setRenderParameter("view", "editPublisher");
response.setRenderParameter("editType", "add");
}

/**
* This Action adds a new publisher to the database
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "addPublisher")
public void addPublisher(ActionRequest request, ActionResponse response)
throws Exception {
Publisher publisher = publisherFromRequest (request);
ArrayList <String> errors = new ArrayList();
if (PublisherValidator.validatePublisher(publisher, errors)) {
PublisherLocalServiceUtil.addPublisher(publisher);
response.setRenderParameter("view", "");
SessionMessages.add(request, "publisher-added");
// remove errorPublisher?
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
response.setRenderParameter("view", "editPublisher");
response.setRenderParameter("editType", "add");
request.setAttribute("errorPublisher", publisher);
}
}

/**
* This method shows the Edit Publisher screen in View mode. This screen
* allows users to add or edit a book.
*
* @param renderRequest
* @param renderResponse
* @throws IOException
* @throws PortletException
*/
public void showViewEditPublisher(
RenderRequest renderRequest, RenderResponse renderResponse)
throws Exception {
PortletURL editURL = renderResponse.createActionURL();
String editType = (String)renderRequest.getParameter("editType");
if (editType.equalsIgnoreCase("edit")) {
editURL.setParameter("javax.portlet.action", "updatePublisher");
long publisherID = Long.parseLong(renderRequest.getParameter("publisherID"));
Publisher publisher = PublisherLocalServiceUtil.getPublisher(publisherID);
renderRequest.setAttribute("publisher", publisher);
} else {
editURL.setParameter("javax.portlet.action", "addPublisher");
Publisher errorPublisher = (Publisher)renderRequest.getAttribute("errorPublisher");
if (errorPublisher!=null) {
renderRequest.setAttribute("publisher", errorPublisher);
} else {
renderRequest.setAttribute("publisher", new PublisherImpl());
}

}
renderRequest.setAttribute("editURL", editURL.toString());
include(editPublisherJSP, renderRequest, renderResponse);
}

/**
* Convenience method to create a Publisher object out of the request. Used
* by the Add / Edit methods.
* @param request
* @return
*/
private Publisher publisherFromRequest (ActionRequest request) {
ThemeDisplay themeDisplay =(ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
PublisherImpl publisher = new PublisherImpl();
publisher.setName(ParamUtil.getString(request, "publisherName"));
publisher.setEmailAddress(ParamUtil.getString(request, "publisherEmail"));
publisher.setWebsite(ParamUtil.getString(request, "publisherWebsite"));
publisher.setPhoneNumber(ParamUtil.getString(request, "publisherPhonenumber"));
publisher.setPrimaryKey(ParamUtil.getLong(request, "resourcePrimKey"));
publisher.setCompanyId(themeDisplay.getCompanyId());
publisher.setGroupId(themeDisplay.getScopeGroupId());
return publisher;
}

/**
* This Action shows the Edit screen
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "editPublisher")
public void editPublisher(ActionRequest request, ActionResponse response)
throws Exception {
long publisherKey = ParamUtil.getLong(request, "resourcePrimKey");
response.setRenderParameter("publisherID", Long.toString(publisherKey));
response.setRenderParameter("view", "editPublisher");
response.setRenderParameter("editType", "edit");

}

/**
* This Action updates the database record of an existing publisher.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "updatePublisher")
public void updatePublisher(ActionRequest request, ActionResponse response)
throws Exception {
Publisher publisher = publisherFromRequest(request);
ArrayList<String> errors = new ArrayList();
if (PublisherValidator.validatePublisher(publisher, errors)) {
PublisherLocalServiceUtil.updatePublisher(publisher);
response.setRenderParameter("view", "");
SessionMessages.add(request, "publisher-updated");
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
response.setRenderParameter("publisherID", Long.toString(publisher.getPrimaryKey()));
response.setRenderParameter("view", "editPublisher");
response.setRenderParameter("editType", "edit");
request.setAttribute("errorPublisher", publisher);
}
}

/**
* This Action deletes a publisher from the database.
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "deletePublisher")
public void deletePublisher(ActionRequest request, ActionResponse response)
throws Exception {

long publisherId = ParamUtil.getLong(request, "resourcePrimKey");
if (Validator.isNotNull(publisherId)) {
PublisherLocalServiceUtil.deletePublisher(publisherId);
SessionMessages.add(request, "publisher-deleted");
} else {
SessionErrors.add(request, "error-deleting");
}
}
/**
* This Action sets the preferences for how many publishers can be viewed per
* page and the format for the phone number
*
* @param request
* @param response
* @throws java.lang.Exception
*/
@ProcessAction(name = "setPublisherPref")
public void setPublisherPref(ActionRequest request, ActionResponse response)
throws Exception {
String rowsPerPage = ParamUtil.getString(request, "rowsPerPage");
String phoneFormat = ParamUtil.getString(request, "phoneFormat");

response.setRenderParameter("rowsPerPage", rowsPerPage);
response.setRenderParameter("phoneFormat", phoneFormat);

PortletPreferences prefs = request.getPreferences();
prefs.setValue("rowsPerPage", rowsPerPage);
prefs.setValue("unitedStatesPhoneFormat", phoneFormat);
prefs.store();

}


protected String editJSP;
protected String helpJSP;
protected String viewJSP;
protected String editPublisherJSP;

private static Log _log = LogFactoryUtil.getLog(PublisherPortlet.class);

}
[/sourcecode]

[sourcecode language="java" wraplines="true"]
package com.liferay.training.library.portlet;

import java.util.List;

import com.liferay.portal.kernel.util.Validator;
import com.liferay.training.library.model.Publisher;

public class PublisherValidator {
/**
* Verify publisher
*
* @param Publisher to be validated
* @param List to populate with any errors
*/
public static boolean validatePublisher(Publisher publisher, List errors) {
boolean valid = true;
if (Validator.isNull(publisher.getName())) {
errors.add("publishername-required");
valid=false;
}
if (Validator.isNull(publisher.getEmailAddress())) {
errors.add("publisheremail-required");
valid=false;
}
if (!Validator.isEmailAddress(publisher.getEmailAddress())) {
errors.add("publisheremail-format-error");
valid=false;
}
if (Validator.isNull(publisher.getPhoneNumber())) {
errors.add("publisherphonenumber-required");
valid=false;
}
if (!Validator.isPhoneNumber(publisher.getPhoneNumber())) {
errors.add("publisherphonenumber-format-error");
valid=false;
}
return valid;
}



}

[/sourcecode]

[sourcecode language="java" wraplines="true"]
/**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.liferay.training.library.service.impl;

import java.util.List;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.SystemException;
import com.liferay.training.library.model.Book;
import com.liferay.training.library.service.base.BookLocalServiceBaseImpl;
import com.liferay.training.library.service.persistence.BookUtil;

/**
* <a href="BookLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
*
* @author Joe Bloggs
*
*/
public class BookLocalServiceImpl extends BookLocalServiceBaseImpl {
@SuppressWarnings("unchecked")
public List findAllInGroup(long groupId)
throws SystemException {

List<Book> list =
(List<Book>) BookUtil.findByGroupId(groupId);
return list;
}

/**
* Adds a new Book to the database.
* @param validBook
* @return Book that was added to the database
* @throws com.liferay.portal.SystemException
*/
public Book addBook (Book validBook) throws SystemException {
Book book = BookUtil.create(CounterLocalServiceUtil.increment(Book.class.getName()));
book.setAuthorName(validBook.getAuthorName());
book.setCompanyId(validBook.getCompanyId());
book.setGroupId(validBook.getGroupId());
book.setPublicationDate(validBook.getPublicationDate());
book.setPublisherId(validBook.getPublisherId());
book.setTitle(validBook.getTitle());
return BookUtil.update(book, false);
}
public void remove(Book book) throws SystemException {
BookUtil.remove(book);
}
}
[/sourcecode]


[sourcecode language="java" wraplines="true"]
/**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

package com.liferay.training.library.service.impl;

import java.util.List;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.SystemException;
import com.liferay.training.library.model.Publisher;
import com.liferay.training.library.service.base.PublisherLocalServiceBaseImpl;
import com.liferay.training.library.service.persistence.PublisherUtil;

/**
* <a href="PublisherLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
*
* @author Joe Bloggs
*
*/
public class PublisherLocalServiceImpl extends PublisherLocalServiceBaseImpl {

@SuppressWarnings("unchecked")
public List findAllInGroup(long groupId)throws SystemException {
List<Publisher> list = (List<Publisher>) PublisherUtil.findByGroupId(groupId);
return list;
}
/**
* Adds a new publisher to the database.
* @param validPublisher
* @return
* @throws com.liferay.portal.SystemException
*/
public Publisher addPublisher (Publisher validPublisher) throws SystemException {
Publisher publisher =
PublisherUtil.create(CounterLocalServiceUtil.increment(Publisher.class.getName()));
publisher.setName(validPublisher.getName());
publisher.setEmailAddress(validPublisher.getEmailAddress());
publisher.setWebsite(validPublisher.getWebsite());
publisher.setPhoneNumber(validPublisher.getPhoneNumber());
publisher.setCompanyId(validPublisher.getCompanyId());
publisher.setGroupId(validPublisher.getGroupId());
return PublisherUtil.update(publisher, false);
}
public void remove(Publisher publisher) throws SystemException {
PublisherUtil.remove(publisher);
}

}
[/sourcecode]

[sourcecode language="html" wraplines="true"]
##
## Messages
##

category.training=Training


action.ADD_BOOK=Add Book
action.ADD_PUBLISHER=Add Publisher


model.resource.com.liferay.training.library.model=Library
publisherName=Name


publisherEmail=Email Address
publisherWebsite=Web Site


publisher-added-successfully=Publisher was Added Successfully
publisherPhonenumber=Phone Number


publisher-deleted-successfully=Publisher was Deleted Successfully
publisher-updated-successfully=Publisher was Updated Successfully
publisherEmptyResultsMessage=There are no publishers to display.


publisheremail-required=Publisher Email is Required
publishername-required=Publisher Name is Required


publisheremail-format-error=Publisher Email Format Error
publisherwebsite-required=Publisher WebSite is Required


publisher-required=Publisher Required
publisherphonenumber-format-error=Publisher Phone Number Format Error
publisherphonenumber-required=Publisher Phone Number is Required


publisherHelp=This portlet allows users to add view, add, edit, and publishers from the system.


phoneFormat=Phone Format
rowsPerPage=Rows Per Page
rowsperpage-required=Rows Per Page is Required


phoneformat-required=Phone Format is Required
prefs-success=Preferences Stored Successfully


bookTitle= Book Title
rowsperpage-invalid=Rows Per Page Invalid


bookAuthorName=Book Author Name
bookPublication=Book Publication


bookEmptyResultsMessage=There are no books to display.
bookPublicationDate=Book Publication
bookPublisher=Book Publisher


book-added-successfully=Book was Added Successfully
book-deleted-successfully=Book was Deleted Successfully


book-updated-successfully=Book was Updated Successfully
bookHelp=This portlet allows users to add view, add, edit, and books from the system.


dateFormat=Date Format
dateformat-error=Date Format Error


[/sourcecode]


[sourcecode language="java" wraplines="true"]
resource-actions/default.xml

<?xml version="1.0" encoding="UTF-8"?>

<resource-action-mapping>
<portlet-resource>
<portlet-name>liferay-book</portlet-name>
<supports>
<action-key>CONFIGURATION</action-key>
<action-key>VIEW</action-key>
</supports>
<community-defaults>
<action-key>VIEW</action-key>
</community-defaults>
<guest-defaults>
<action-key>VIEW</action-key>
</guest-defaults>
<guest-unsupported />
</portlet-resource>
<portlet-resource>
<portlet-name>liferay-publisher</portlet-name>
<supports>
<action-key>CONFIGURATION</action-key>
<action-key>VIEW</action-key>
</supports>
<community-defaults>
<action-key>VIEW</action-key>
</community-defaults>
<guest-defaults>
<action-key>VIEW</action-key>
</guest-defaults>
<guest-unsupported />
</portlet-resource>
<model-resource>
<model-name>com.liferay.training.library.model</model-name>
<portlet-ref>
<portlet-name>liferay-book</portlet-name>
</portlet-ref>
<supports>
<action-key>ADD_BOOK</action-key>
<action-key>ADD_PUBLISHER</action-key>
</supports>
<community-defaults/>
<guest-defaults/>
<guest-unsupported>
<action-key>ADD_BOOK</action-key>
<action-key>ADD_PUBLISHER</action-key>
</guest-unsupported>
</model-resource>
<model-resource>
<model-name>com.liferay.training.library.model.Book</model-name>
<portlet-ref>
<portlet-name>liferay-book</portlet-name>
</portlet-ref>
<supports>
<action-key>DELETE</action-key>
<action-key>PERMISSIONS</action-key>
<action-key>UPDATE</action-key>
<action-key>VIEW</action-key>
</supports>
<community-defaults>
<action-key>VIEW</action-key>
</community-defaults>
<guest-defaults>
<action-key>VIEW</action-key>
</guest-defaults>
<guest-unsupported>
<action-key>UPDATE</action-key>
</guest-unsupported>
</model-resource>
<model-resource>
<model-name>com.liferay.training.library.model.Publisher</model-name>
<portlet-ref>
<portlet-name>liferay-publisher</portlet-name>
</portlet-ref>
<supports>
<action-key>DELETE</action-key>
<action-key>PERMISSIONS</action-key>
<action-key>UPDATE</action-key>
<action-key>VIEW</action-key>
</supports>
<community-defaults>
<action-key>VIEW</action-key>
</community-defaults>
<guest-defaults>
<action-key>VIEW</action-key>
</guest-defaults>
<guest-unsupported>
<action-key>UPDATE</action-key>
</guest-unsupported>
</model-resource>
</resource-action-mapping>


[/sourcecode]



[sourcecode language="html" wraplines="true"]
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
<%@ taglib uri="http://liferay.com/tld/security" prefix="liferay-security" %>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util" %>

<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.Random" %>

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.liferay.portal.kernel.dao.search.ResultRow" %>
<%@ page import="com.liferay.portal.kernel.dao.search.SearchEntry" %>
<%@ page import="com.liferay.portal.kernel.util.DateUtil" %>
<%@ page import="com.liferay.portal.kernel.util.ListUtil" %>
<%@ page import="com.liferay.portal.kernel.util.ParamUtil" %>
<%@ page import="com.liferay.portal.kernel.util.WebKeys" %>
<%@ page import="javax.portlet.PortletURL" %>
<%@ page import="javax.portlet.ActionRequest" %>
<%@ page import="javax.portlet.PortletRequest" %>
<%@ page import="javax.portlet.PortletPreferences" %>
<%@ page import="javax.portlet.PortletSession" %>
<%@ page import="com.liferay.portlet.PortletPreferencesFactoryUtil" %>
<%@ page import="com.liferay.portal.kernel.util.ListUtil" %>
<%@ page import="com.liferay.portal.kernel.language.LanguageUtil" %>
<%@ page import="com.liferay.portal.kernel.dao.search.*" %>
<%@ page import="com.liferay.training.library.model.Publisher"%>
<%@ page import="com.liferay.training.library.service.PublisherLocalServiceUtil"%>
<%@ page import="com.liferay.training.library.model.Book"%>
<%@ page import="com.liferay.training.library.service.BookLocalServiceUtil"%>
<%@ page import="com.liferay.portal.security.permission.ActionKeys"%>


<liferay-theme:defineObjects />
<portlet:defineObjects />

<%
PortletPreferences prefs = renderRequest.getPreferences();
%>
[/sourcecode]

/*************************************************Book******************************************/
View

[sourcecode language="html"]
<%@include file="../init.jsp" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.liferay.training.library.service.PublisherLocalServiceUtil" %>

<jsp:useBean id="addBookURL" class="java.lang.String" scope="request" />

<liferay-ui:success key="book-added" message="book-added-successfully" />
<liferay-ui:success key="book-deleted" message="book-deleted-successfully" />
<liferay-ui:success key="book-updated" message="book-updated-successfully" />

<c:choose>
<c:when test='<%= (Boolean)request.getAttribute("hasAddPermission") %>'>
<input type="button" name="addBookButton" value="Add Book" onClick="self.location = '<%=addBookURL %>';">
</c:when>
</c:choose>

<%
SimpleDateFormat dateFormat =
new SimpleDateFormat(prefs.getValue("dateFormat", "yyyy/MM/dd"));
%>
<liferay-ui:search-container delta='<%= new Integer(prefs.getValue("rowsPerPage", "5")) %>' emptyResultsMessage="bookEmptyResultsMessage">
<liferay-ui:search-container-results>

<%
List<Book> tempResults = (List<Book>)request.getAttribute("tempResults");
results = ListUtil.subList(tempResults, searchContainer.getStart(), searchContainer.getEnd());;
total = tempResults.size();

pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%>

</liferay-ui:search-container-results>

<liferay-ui:search-container-row
className="com.liferay.training.library.model.Book"
keyProperty="bookId"
modelVar="book"
>

<liferay-ui:search-container-column-text
name="title"
property="title"
/>

<liferay-ui:search-container-column-text
name="author-name"
property="authorName"
/>

<liferay-ui:search-container-column-text
name="name"
value="<%= dateFormat.format(book.getPublicationDate()) %>"
/>

<%
String publisherName;
try {
publisherName =
PublisherLocalServiceUtil.getPublisher(
book.getPublisherId()).getName();
}
catch (Exception ex) {
publisherName = "";
}
%>

<liferay-ui:search-container-column-text
name="publisher"
value="<%= publisherName %>"
/>

<liferay-ui:search-container-column-jsp
align="right"
path="/html/book/edit_actions.jsp"
/>

</liferay-ui:search-container-row>

<liferay-ui:search-iterator />

</liferay-ui:search-container>
[/sourcecode]

/************************************editBook*****************************************/
[sourcecode language="html"]

<%@include file="../init.jsp" %>

<jsp:useBean class="java.lang.String" id="editURL" scope="request" />
<jsp:useBean id="book" type="com.liferay.training.library.model.Book" scope="request"/>
<jsp:useBean id="date" class="java.lang.String" scope="request" />
<jsp:useBean id="publisherList" type="java.util.List" scope="request" />

<portlet:defineObjects />

<liferay-ui:success key="book-added" message="book-added" />

<form name="addBook" action="<%=editURL %>" method="POST">
<strong>Publisher Details</strong>

<input type="hidden" name="resourcePrimKey" value="<%=book.getPrimaryKey() %>">

<table border="0">
<tr>
<td>
<liferay-ui:message key="bookTitle" />*<br>
<input type="text" name="bookTitle" value="<%=book.getTitle() %>" size="45" />
<liferay-ui:error key="booktitle-required" message="booktitle-required" />
</td>
</tr>
<tr>
<td>
<liferay-ui:message key="bookAuthorName" />*<br>
<input type="text" name="bookAuthorName" value="<%=book.getAuthorName() %>" size="45" />
<liferay-ui:error key="bookauthorname-required" message="bookauthorname-required" />
</td>
</tr>
<tr>
<td>
<liferay-ui:message key="bookPublicationDate" /><br>
<input type="text" name="bookPublicationDate" value="<%=date%>" size="45" />
<liferay-ui:error key="bookpublicationdate-required" message="bookpublicationdate-required" />
</td>
</tr>
<tr>
<td>
<liferay-ui:message key="publisher" />*<br>
<select name="<portlet:namespace />publisherId">
<option value="">Please Select</option>
<%
for (int i=0;i<publisherList.size();i++) {
Publisher publisher = (Publisher)publisherList.get(i);
if (publisher.getPrimaryKey() == book.getPublisherId()) {
%>
<option value="<%= publisher.getPrimaryKey() %>" selected="selected"><%= publisher.getName() %></option>

<% } else {
%>
<option value="<%= publisher.getPrimaryKey() %>"><%= publisher.getName() %></option>
<%
}
}
%>
</select>
<liferay-ui:error key="publisher-required" message="publisher-required" />
</td>
</tr>
</table>

<input type="submit" value="Submit" >
<input type="button" value="Cancel" onClick="self.location = '<portlet:renderURL></portlet:renderURL>';" />
</form>
[/sourcecode]

/**********************************************edit************************************************/

[sourcecode language="html"]

<%@include file="../init.jsp" %>

<liferay-ui:success key="operate-successfully" message="operate-successfully" />

<form name="setBookPref" action="<portlet:actionURL name="setBookPref" />" method="POST">
<table border="0">
<tbody>
<tr>
<td>
<liferay-ui:message key="rowsPerPage" />*<br>
<input type="text" name="rowsPerPage" value="<%=prefs.getValue("rowsPerPage","") %>" size="45" />
<liferay-ui:error key="rowsperpage-required" message="rowsperpage-required" />
<liferay-ui:error key="rowsperpage-invalid" message="rowsperpage-invalid" />
</td>
</tr>
<tr>
<td>
<liferay-ui:message key="dateFormat" />*<br>
<input type="text" name="dateFormat" value="<%=prefs.getValue("dateFormat","")%>" size="45" />
<liferay-ui:error key="dateformat-required" message="dateformat-required" />
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" />
</form>
[/sourcecode]

/**********************************************editAction***********************************************************/
[sourcecode languahe="html"]
<%@include file="/html/init.jsp" %>


<%
ResultRow row = (ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
Book book = (Book)row.getObject();

long groupId = themeDisplay.getScopeGroupId();
String name = portletDisplay.getRootPortletId();
String primKey = String.valueOf(book.getPrimaryKey());
%>
<liferay-ui:icon-menu cssClass="">

<c:if test="<%= permissionChecker.hasPermission(groupId, name, primKey, ActionKeys.UPDATE) %>">
<portlet:actionURL name="editBook" var="editURL">
<portlet:param name="resourcePrimKey" value="<%=primKey %>" />
</portlet:actionURL>

<liferay-ui:icon image="edit" url="<%=editURL.toString() %>" />
</c:if>

<c:if test="<%= permissionChecker.hasPermission(groupId, name, primKey, ActionKeys.DELETE) %>">
<portlet:actionURL name="deleteBook" var="deleteURL">
<portlet:param name="resourcePrimKey" value="<%= primKey %>" />
</portlet:actionURL>

<liferay-ui:icon image="delete" url="<%=deleteURL.toString() %>" />
</c:if>

<c:if test="<%= permissionChecker.hasPermission(groupId, name, primKey, ActionKeys.PERMISSIONS) %>">
<liferay-security:permissionsURL
modelResource="<%= Book.class.getName() %>"
modelResourceDescription="<%= book.getTitle() %>"
resourcePrimKey="<%= primKey %>"
var="permissionsURL"
/>

<liferay-ui:icon image="permissions" url="<%= permissionsURL %>" />
</c:if>

</liferay-ui:icon-menu>

/******************************************************help********************************************************/
[sourcecode language="html"]
<%
/**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
%>

<%@include file="/html/init.jsp" %>

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<liferay-ui:message key="bookHelp" />
[/sourcecode]

[/sourcecode]