liferay 6 How to get the Folder id of a folder - liferay

Having a folder name e.g. "images", how can i get the folderId attribute of this folder? I need the folderId so i can then use the DLFolderLocalServiceUtil interface and methods to query for the files in the dir

This should work
Long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; // if the id of the parent is set to default
DLFolder dir = DLFolderLocalServiceUtil.getFolder(groupId, parentFolderId, dirName);
see: DLFolderLocalServiceUtil
Where groupId is the id of the site the request is coming from, you can get it using themeDisplay:
ThemeDisplay themeDisplay =
(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
long groupId = themeDisplay.getLayout().getGroupId();
and parentFolderId is the id of the folder containg the folder you're searching for and it is set when you add a new folder using:
DLFolder newFolder=addFolder(long userId, long groupId, long repositoryId, boolean mountPoint, long parentFolderId, String name,
String description, boolean hidden, ServiceContext serviceContext)

Related

Invalid property on line changeLog in liferay programatic uploading into document and library

06, i want to upload the files into document and library, i have searched and written the code like this, i have got error invalid property change log. can any one correct my code? and i have another doubt repository id and comapny id are same? and in portlet it showing You have entered invalid data. Please try again.
public void uploadBook(ActionRequest actionRequest,
ActionResponse actionRresponse) throws PortletException,
IOException, com.liferay.portal.kernel.exception.PortalException, com.liferay.portal.kernel.exception.SystemException {
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
String submissionFileName = uploadRequest.getFileName("file");//uploaded filename
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);
File file = uploadRequest.getFile("file");
String contentType = MimeTypesUtil.getContentType(file);
InputStream inputStream = new FileInputStream(file);
String folderName="library";
long folderId = 11502;
long repositoryId =10132;
//java.io.File file = ( java.io.File)uploadRequest.getFile("file");
// InputStream is = new FileInputStream(file);
DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
repositoryId,
folderId,
file.getName(),
contentType,
submissionFileName,
"no description",
"changeLog",
inputStream,
file.length(),
serviceContext);
//addFileEntry(long userId, long groupId, long folderId, String name, String title, String description, String changeLog, String extraSettings, byte[] bytes, ServiceContext serviceContext)
String successMessage ="File Uploaded Successfully";
SessionMessages.add(actionRequest, "request_rocessed",successMessage);
}
You can refer EditFileEntryAction.java method updateFileEntry(..) for what parameter are getting passed.
repositoryId by default is groupId where you are adding your document (i.e. site or organization).
FolderId has to be existing folder Id of that group (site or org)
changeLog pass it as blank ""
Paste the complete stacktrace / logs from Tomcat

Liferay: How to get relative paths to web contents's documents and media

Under Web content I set my structure to have an application field: "Documents an media".
Through this field user can add various files which are then displayed in my .xhtml.
User can make this "Documents and media" field repeatable to add more files.
How could I iterate through all added files and get their relative paths.
If my Documents and media field is not repeatable I can get relative path like this:
public String getWebContentTitle(String title, String nodeName) throws PortalException, SystemException {
FacesContext context = FacesContext.getCurrentInstance();
ThemeDisplay themeDisplay = (ThemeDisplay) context.getExternalContext().getRequestMap().get(WebKeys.THEME_DISPLAY);
long groupId = themeDisplay.getScopeGroupId();
JournalArticle article = JournalArticleLocalServiceUtil.getArticleByUrlTitle(groupId, formatUrlTitle(title));
String languageKey = context.getExternalContext().getRequestLocale().toString();
JournalArticleDisplay articleDisplay = JournalContentUtil.getDisplay(groupId, article.getArticleId(), article.getTemplateId(), languageKey, themeDisplay);
JournalArticle journalArticle = JournalArticleLocalServiceUtil.getArticle(groupId, article.getArticleId());
String myContent = journalArticle.getContentByLocale(languageKey);
if (nodeName != null) {
String nodeText=getParseValue(nodeName, journalArticle, myContent);
return nodeText;
} else
{
String ret=articleDisplay.getContent();
return ret;
}
}
private String getParseValue(String fieldname, JournalArticle article, String locale) {
String nodeText = "";
try {
Document document = SAXReaderUtil.read(article.getContentByLocale(locale));
Node node = document.selectSingleNode("/root/dynamic-element[#name='" + fieldname +"']/dynamic-content");
nodeText = node.getText();
} catch(Exception e){
}
return nodeText;
}
This method return relative path to my added document (say horses.pdf).
How could I get relative paths to more documents added through "Documents and media field", which is repeatable and has defined specific Variable name (say HorsesPdfs?)
Any help would be greatly appreciated!
You could try
DLAppLocalServiceUtil.getFileEntries(REPOSITORY_ID, FOLDER_ID), probably better than DLFileEntry as its the new approach that takes workflows in consideration.
Where
REPOSITORY_ID = parent group, which is by default LR´s one GroupLocalServiceUtil.getGroup(COMPANY_ID, GroupConstants.GUEST).getGroupId()
COMPANY_ID = PortalUtil.getDefaultCompanyId(); //If just one instance, if not, better to play with CompanyLocalServiceUtil to match your Id
For FOLDER ID, you can use root older of LR´s Doc & Media which is
FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; //or find it e.g DLAppLocalServiceUtil.getFolder( repositoryId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, FOLDER_NAME).getFolderId(); if you programtically used addFolder(long userId, long repositoryId, long parentFolderId, String name, String description, ServiceContext serviceContext)

No Role exists with the key {companyId=1, name=Owner} error in liferay portlet

I'm using Service Builder in my portlet. Here is my addProduct method in PRProductLocalServiceBaseImpl:
public class PRProductLocalServiceImpl extends PRProductLocalServiceBaseImpl {
public PRProduct addProduct(long companyID, long groupID, String productName, String serialNumber, long userID) throws SystemException, PortalException{
PRProduct product = prProductPersistence.create(counterLocalService.increment(PRProduct.class.getName()));
resourceLocalService.addResources(companyID, groupID, userID, PRProduct.class.getName(), product.getPrimaryKey(), false, true, true);
product.setProductName(productName);
product.setSerialNumber(serialNumber);
product.setCompanyId(companyID);
product.setGroupId(groupID);
return prProductPersistence.update(product, false);
}
}
When I call this method from my portlet class and pass 1 as companyID it gives "No Role exists with the key {companyId=1, name=Owner}". and here is my portlet class:
public void addProduct(ActionRequest actionReaquest, ActionResponse actionResponse)
{
PortletSession session = actionReaquest.getPortletSession();
try
{
String productName = actionReaquest.getParameter("productName");
String userID = actionReaquest.getParameter("userID");
String companyID = actionReaquest.getParameter("companyID");
String groupID = actionReaquest.getParameter("groupID");
String serialNumber = actionReaquest.getParameter("serialNumber");
PRProduct product = PRProductLocalServiceUtil.addProduct(Long.parseLong(companyID), Long.parseLong(groupID), productName,
serialNumber, Long.parseLong(userID));
session.setAttribute("errorMessage", "Product added successfully");
actionResponse.setRenderParameter("jspPage", "/ProductAdded.jsp");
}
catch(Exception e)
{
session.setAttribute("errorMessage", e.getMessage());
actionResponse.setRenderParameter("jspPage", "/ProductAdded.jsp");
}
}
Can any body help? Any help is appreciated in advance.
Have checked to see if the Company ID is in fact 1?
The best way to get the current Liferay User ID, Group ID, and Company ID is by the ThemeDisplayobject. So instead of using your code:
String userID = actionReaquest.getParameter("userID");
String companyID = actionReaquest.getParameter("companyID");
String groupID = actionReaquest.getParameter("groupID");
You should use:
ThemeDisplay themeDisplay = (ThemeDisplay) actionReaquest.getAttribute(WebKeys.THEME_DISPLAY);
long realUserId = themeDisplay.getRealUserId();
long companyId = themeDisplay.getCompanyId();
long groupId = themeDisplay.getScopeGroupId();
This way you'll get the values from Liferay, rather than having to pass them in yourself. It also means you don't have to a Long.parseLong() to get the Long value of a String.
See if this helps! It's also better practice to do it this way for any future portlets. The ThemeDisplay objects holds a lot of useful information!
Also minor thing, it's spelt "request" not "reaquest" :)
Probably you need to add the content as an admin user or Owner user, below is the example to ass the content as the admin user set the adminUser permission before adding the content, try same for Owner:
User adminUser = UserLocalServiceUtil.getUserByEmailAddress(companyId,"test#liferay.com");
permissionChecker = PermissionCheckerFactoryUtil.create(adminUser);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
or just fetch the owner the using code below:
Role role=com.liferay.portal.service.RoleLocalServiceUtil.getRole(long companyId,"Owner");
and update the add method add one more argument in add method i.e. serviceContext and all role(owner) in it,as we do while adding User in liferay.

Adding Site to Organization in Liferay using hook

I am trying to create a Site for the Organization when the Organization is created using hook and adding listener to Organization entity.
I created site using GroupLocalServiceUtil and set up siteName = String.valueOf(org.getOrganizationId()) + "LFR_ORGANIZATION" + org.getName() like in DB.
Also I have set className and classPK like it is done when you create site to organization in liferay, but nothing happens. Site creates successfully, but it isn't connected with the Organization.
UPD.
Liferay 6.1 GA1
public Group addSite(Organization org) throws PortalException, SystemException
{
ServiceContext serviceContext = new ServiceContext();
String siteName = String.valueOf(org.getOrganizationId()) + "LFR_ORGANIZATION" + org.getName();
Group newSite = GroupLocalServiceUtil.addGroup(
getDefaultUserId(),
"com.liferay.portal.model.Organization", // Class Name
org.getOrganizationId(), // Class PK
siteName , // Name
"", // Description
GroupConstants.TYPE_SITE_PRIVATE, // Type
org.getTreePath(), // Friendly URL
true, // Site
true, // Active
serviceContext);
OrganizationUtil.addGroup(org.getPrimaryKey(), newSite);
return newSite;
}
How can I create such an Organizational Site programmatically?
In Liferay 6.1, it appears that when you create an Organization there is already a backing group. That group may not be visible depending on the boolean site parameter you pass:
OrganiztionLocalServiceUtil.addOrganization(
long userId, long parentOrganizationId, String name, String type,
boolean recursable, long regionId, long countryId, int statusId,
String comments, boolean site, ServiceContext serviceContext)
To make that Site visible for pages, simply call:
OrganiztionLocalServiceUtil.updateOrganization(
long companyId, long organizationId, long parentOrganizationId,
String name, String type, boolean recursable, long regionId,
long countryId, int statusId, String comments, boolean site,
ServiceContext serviceContext)
with site parameter set to true.

How to get GUID of a subfolder in a document library programmatically

Okay, here is the scenario...
I have created a subfolder in a document library, and when an item is added to the document library, i want to do some processing on the document and then move the item to the subfolder, say MySubFolder. For that purpose, i will be using this statement
SPListItem folder = this.workflowProperties.List.Folders[];
but the Folders[] collection will take either an int index or a guid. SInce i am doing it in a workflow, I dont know how to get the guid of the folder here. Please note that I cannot use the url to get the GUID here because the same workflow is applied to a number of document libraries and I have the MySubFolder subfolder in all of them, so giving the url seems a bit tacky here i think.
I don't have Sharepoint here right now, but you should be able to do:
Guid folderId = Guid.Empty;
foreach (SPFolderCollection folder in YourList.Folders)
{
if (folder.Name == "MySubFolder")
{
folderId = folder.UniqueId;
break;
}
}
Or, into your event handler, build your folder URL:
public override void ItemDeleting(SPItemEventProperties properties)
{
Uri folderAddress = new Uri(properties.BeforeUrl, "MySubFolder");
SPFolder folder = yourWeb.GetFolder(folderAddress.ToString());
}
I solved it by doing the following:
Guid folderId = Guid.Empty;
SPFolder spFolder = web.Folders[this.workflowProperties.List.Title].SubFolders["MySubFolder"];
folderId=spFolder.UniqueId;

Resources