Saturday, August 1, 2015

Save a Document with Metadata Programatically in Liferay


In my previous blog we see how to upload a file with metadata associated with it by using Liferay GUI.Today we will discuss how to upload a file or document with metadata in Document and Media Portlet Programmatically. Before reading this blog you must know how to create metadata sets and document type for this you can read my previous blog Save Document with Metadata in Liferay.

So lets start this step by step:-

Step 1:-Create Liferay Project and Portlet
Create a Liferay Project in eclipse and then create a Generic portlet in the Project.For theses you may refer Step 1 and Step 2 of my previous blog Here .





Step 2:-Create Your Form
Open view.jsp and paste this code:-

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="uplaodData" name="uploadDocument"></portlet:actionURL>
<b>Please Upload a Document</b>
<form action="<%=uplaodData%>" method="post" enctype="multipart/form-data">
Candidate Name:-<input type="text" name="name" id="name"><br>
Experience:-<input type="text" name="experience" id="experience"><br>
File Title:-<input type="text" name="title" id="title"><br>
<input type="file" name="uploadedFile"><br>
File Description:-<input type="text" name="description" >
<br>
<input type="Submit" name="Submit">
</form>
view raw view.jsp hosted with ❤ by GitHub

Explanation:-
Here we create a simple form that contain 4 fields .Two for metadata and other two for document title and description.Form enctype is multipart/form-data because we also upload a file.

Step 3:-Create portlet.properties
Create a property file in src with name portlet.properties and paste this content:-

fileupload.folder.name=Naukri
metadata.sets.name=Resume


Step 4:-Create Controller Class
Open your java class and paste this content:-

package com.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
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.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
import com.liferay.portlet.dynamicdatamapping.storage.Field;
import com.liferay.portlet.dynamicdatamapping.storage.Fields;
import com.liferay.util.portlet.PortletProps;
public class Demo extends GenericPortlet {
private static long PARENT_FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
private static String ROOT_FOLDER_NAME = PortletProps.get("fileupload.folder.name");
private static String METADATA_SETS_NAME = PortletProps.get("metadata.sets.name");
public void init() {
viewTemplate = getInitParameter("view-template");
}
public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException {
include(viewTemplate, renderRequest, renderResponse);
}
@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(request);
String candidateName =ParamUtil.getString(uploadPortletRequest, "name");
String fileDescription = ParamUtil.getString(uploadPortletRequest, "description");
String fileTitle = ParamUtil.getString(uploadPortletRequest, "title");
String experience = ParamUtil.getString(uploadPortletRequest, "experience");
File file = uploadPortletRequest.getFile("uploadedFile");
String mimeType = uploadPortletRequest.getContentType("uploadedFile");
InputStream is = new FileInputStream( file );
String fileName=uploadPortletRequest.getFileName("uploadedFile");
DLFolder folder = null;
ServiceContext serviceContext=null;
try {
folder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), PARENT_FOLDER_ID, ROOT_FOLDER_NAME);
serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), uploadPortletRequest);
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
DDMStructure structure = getDDMStructureByName(themeDisplay);
Fields fields = new Fields();
fields.put(new Field("candidate_name",candidateName ));
fields.put(new Field("experience", experience));
fieldsMap.put(structure.getStructureKey(), fields);
DLFileEntry dlFileEntry=null;
try {
dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(), themeDisplay.getScopeGroupId(),
themeDisplay.getScopeGroupId(), folder.getFolderId(),fileName, mimeType, fileName, StringPool.BLANK, StringPool.BLANK,
folder.getDefaultFileEntryTypeId(),fieldsMap, file, null, file.length(), serviceContext);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
DLFileEntryLocalServiceUtil.updateFileEntry(folder.getUserId(), dlFileEntry.getFileEntryId(), file.getName(), mimeType,
fileTitle, fileDescription, "Draft to save",true, dlFileEntry.getFileEntryTypeId(), fieldsMap, file, is,
file.getTotalSpace(), serviceContext);
}
catch (Exception e) {
e.printStackTrace();
}
}
public DDMStructure getDDMStructureByName(ThemeDisplay themeDisplay)
{
DDMStructure structure = null;
try {
List<DDMStructure> structures = DDMStructureLocalServiceUtil.getStructures(themeDisplay.getScopeGroupId());
for (DDMStructure struct : structures) {
if (struct.getName((Locale.ROOT)).equalsIgnoreCase(METADATA_SETS_NAME)) {
structure = struct;
break;
}
}
} catch (SystemException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return structure;
}
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);
}
}
protected String viewTemplate;
private static Log _log = LogFactoryUtil.getLog(Demo.class);
}
view raw Demo.java hosted with ❤ by GitHub

Explanation:-

  • Here we create a method getDDMStructureByName which give us structue  in which we have to save our document.You just pass the name of metadata set to it and will return structure.
  • From line 75 to 80 we create a we create a Map of Metadata fields and pass to addFileEntry method.The "candidate_name" and "experience" is exactly same name that we are using when we create metadata sets.All other detail of this method i already explained in Folder and File Upload Programmatically .



Step 5:-Check Output
Now deploy your portlet and check output as:-
Now go to Resume folder and check uploaded file 




Project Structure:-






Hope this will Help....

You can Download Source code from  Save a Document with Metadata Programmatically in Liferay.


Related Post:-

No comments:

Post a Comment

Total Pageviews

1041354

Number Of Unique Visitor

Free counters!