In Liferay 7, I have a structure, some FTL code, and I want to create a template from that, in a Java Liferay module (no portlet). Just like a human would do with the UI below, but programmatically:
Note: The code proposed at How to create Structure & Template programmatically in Liferay 6 does not work, it results in Someone may be trying to circumvent the permission checker exceptions.
See also: How to create a Liferay 7 structure programmatically?
This code takes a structure (DDMStructure) and successfully creates a template:
ServiceContext serviceContext = new ServiceContext();
serviceContext.setScopeGroupId(group.getGroupId());
serviceContext.setAddGroupPermissions(true);
serviceContext.setAddGuestPermissions(true);
serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);
String templateKey = "my template"; // Any name you want.
long classNameId = PortalUtil.getPortal().getClassNameId(DDMStructure.class);
long classPK = structure.getPrimaryKey();
long resourceClassNameId = PortalUtil.getPortal().getClassNameId(JournalArticle.class);
nameMap = Utils.createLocalesMap(templateKey);
descriptionMap = nameMap; // Use the same.
String type = "display";
String mode = "create";
String language = "ftl";
String script = null;
try {
script = new String(Files.readAllBytes(Paths.get("/path/to/my/template.ftl")));
} catch (IOException e) {
log.error("Exception when reading template: " + templateDefinitionFilePath, e);
}
try {
DDMTemplate template = DDMTemplateLocalServiceUtil.addTemplate(
user.getUserId(), group.getGroupId(), classNameId, classPK,
resourceClassNameId, nameMap, descriptionMap,
type, mode, language, script, serviceContext);
} catch (PortalException e) {
log.error("Exception when creating template: " + templateDefinitionFilePath, e);
return false;
}
Related
i am getting below error while run this program
i am using SharePoint server 2010 and recently i am install danish language pack in SharePoint server for client environment . but after this when ever i am run below code
i am getting below exceptions
org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException: Bad Request
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:453)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:601)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.NavigationServiceImpl.getChildren(NavigationServiceImpl.java:86)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl$2.fetchPage(FolderImpl.java:285)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getCurrentPage(AbstractIterator.java:132)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getTotalNumItems(AbstractIterator.java:70)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterable.getTotalNumItems(AbstractIterable.java:94)
at ShareTest1.main(ShareTest1.java:188)
public class ShareTest
{
static Session session = null;
static Map<String,Map<String, String>> allPropMap=new HashMap<String,Map<String, String>>();
static void getSubTypes(Tree tree)
{
ObjectType objType = (ObjectType) tree.getItem();
if(objType instanceof DocumentType)
{
System.out.println("\n\nType name "+objType.getDisplayName());
System.out.println("Type Id "+objType.getId());
ObjectType typeDoc=session.getTypeDefinition(objType.getId());
Map<String,PropertyDefinition<?>> mp=typeDoc.getPropertyDefinitions();
for(String key:mp.keySet())
{
PropertyDefinition<?> propdef=mp.get(key);
HashMap<String,String> propMap=new HashMap<String,String>();
propMap.put("id",propdef.getId());
propMap.put("displayName",propdef.getDisplayName());
System.out.println("\nId="+propMap.get("id")+" DisplayName="+propMap.get("displayName"));
System.out.println("Property Type = "+propdef.getPropertyType().toString());
System.out.println("Property Name = "+propdef.getPropertyType().name());
System.out.println("Property Local Namespace = "+propdef.getLocalNamespace());
if(propdef.getChoices()!=null)
{
System.out.println("Choices size "+propdef.getChoices().size());
}
if(propdef.getExtensions()!=null)
{
System.out.println("Extensions "+propdef.getExtensions().size());
}
allPropMap.put(propdef.getId(),propMap);
}
List lstc=tree.getChildren();
System.out.println("\nSize of list "+lstc.size());
for (int i = 0; i < lstc.size(); i++) {
getSubTypes((Tree) lstc.get(i));
}
}
}
public static void main(String[] args)
{
/**
* Get a CMIS session.
*/
String user="parag.patel";
String pwd="Admin123";
/*Repository : Abc*/
String url="http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo";
String repositoryId="6B4D3830-65E5-49C9-9A02-5D67DB1FE87B";
// Default factory implementation of client runtime.
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// user credentials
parameter.put(SessionParameter.USER, "parag.patel");
parameter.put(SessionParameter.PASSWORD, "Admin123");
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, "http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo");
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.REPOSITORY_ID, "6B4D3830-65E5-49C9-9A02-5D67DB1FE87B");
parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "DK");
parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "da");
parameter.put(SessionParameter.LOCALE_VARIANT, "");
parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, CmisBindingFactory.STANDARD_AUTHENTICATION_PROVIDER);
// create session
Session session = factory.createSession(parameter);
if(repositoryId!=null)
{
parameter.put(SessionParameter.REPOSITORY_ID, repositoryId);
session=factory.createSession(parameter);
RepositoryInfo repInfo=session.getRepositoryInfo();
System.out.println("Repository Id "+repInfo.getId());
System.out.println("Repository Name "+repInfo.getName());
System.out.println("Repository cmis version supported "+repInfo.getCmisVersionSupported());
System.out.println("Sharepoint product "+repInfo.getProductName());
System.out.println("Sharepoint version "+repInfo.getProductVersion());
System.out.println("Root folder id "+repInfo.getRootFolderId());
try
{
AclCapabilities cap=session.getRepositoryInfo().getAclCapabilities();
OperationContext operationContext = session.createOperationContext();
int maxItemsPerPage=5;
//operationContext.setMaxItemsPerPage(maxItemsPerPage);
int documentCount=0;
session.setDefaultContext(operationContext);
CmisObject object = session.getObject(new ObjectIdImpl(repInfo.getRootFolderId()));
Folder folder = (Folder) object;
System.out.println("======================= Root folder "+folder.getName());
ItemIterable<CmisObject> children = folder.getChildren();
long to=folder.getChildren().getTotalNumItems();
System.out.println("Total Children "+to);
Iterator<CmisObject> iterator = children.iterator();
while (iterator.hasNext()) {
CmisObject child = iterator.next();
System.out.println("\n\nChild Id "+child.getId());
System.out.println("Child Name "+child.getName());
if (child.getBaseTypeId().value().equals(ObjectType.FOLDER_BASETYPE_ID))
{
System.out.println("Type : Folder");
Folder ftemp=(Folder) child;
long tot=ftemp.getChildren().getTotalNumItems();
System.out.println("Total Children "+tot);
ItemIterable<CmisObject> ftempchildren = ftemp.getChildren();
Iterator<CmisObject> ftempIt = ftempchildren.iterator();
int folderDoc=0;
while (ftempIt.hasNext()) {
CmisObject subchild = ftempIt.next();
if(subchild.getBaseTypeId().value().equals(ObjectType.DOCUMENT_BASETYPE_ID))
{
System.out.println("============ SubDoc "+subchild.getName());
folderDoc++;
documentCount++;
}
}
System.out.println("Folder "+child.getName()+" No of documents="+(folderDoc));
}
else
{
System.out.println("Type : Document "+child.getName());
documentCount++;
}
}
System.out.println("\n\nTotal no of documents "+documentCount);
}
catch(CmisPermissionDeniedException pd)
{
System.out.println("Error ********** Permission Denied ***************** ");
pd.printStackTrace();
}
catch (CmisObjectNotFoundException co) {
System.out.println("Error ******** Root folder not found ***************");
co.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
else
{
System.out.println("Else");
Repository soleRepository=factory.getRepositories(
parameter).get(0);
session = soleRepository.createSession();
}
}
}
here it is my lib which i used in above code .
chemistry-opencmis-client-api-0.9.0
chemistry-opencmis-client-bindings-0.9.0
chemistry-opencmis-client-impl-0.9.0
chemistry-opencmis-commons-api-0.9.0
chemistry-opencmis-commons-impl-0.9.0
log4j-1.2.14
slf4j-api-1.6.1
slf4j-log4j12-1.6.1
it works fine when i am trying to connect repository (url) which is created in english language .
but when try to connect with the danish .repository then getting error.
The best thing you can do is to increase the SharePoint log level for CMIS. Sometimes the logs provide a clue.
The SharePoint 2010 CMIS implementaion isn't a 100% spec compliant. OpenCMIS 0.12.0 contains a few workarounds for SharePoint 2010 and 2013. Most of them a little things like an extra requied URL parameter that isn't in the spec. I wouldn't be supprised if this is something similar.
In Liferay6.1 I want to add images programmatically into Document Library?
This is my main method that I want to add an image into document library by it :
public class ImgGallery {
public static void main(String[] args) throws SystemException, FileNotFoundException {
byte[] bytes = new byte[0];
File srcfile = new File("C:\\Users\\my-pc\\Pictures\\extra\\myPhoto.jpg");
InputStream in = new FileInputStream(srcfile);
long repositoryId = 10180;
long folderId = 10651;
Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
DLFileEntryLocalServiceUtil.addFileEntry(
10196, repositoryId, repositoryId, folderId,
"filename", MimeTypesUtil.getContentType("behnaz.jpg"),
"title", "description", "changeLog", 0, fieldsMap,
srcfile, null, bytes.length, serviceContext
);
}
}
This doesn't work - I don't know what arguments to supply to DLFileEntryLocalServiceUtil.addFileEntry?
For adding a file to Liferay document library
You will need a folder, that you can create it in liferay control panel, my folder is TestFolder. You search for it with DLFolderLocalServiceUtil.getFolder. You need the dlfileentrytypes. I hope we will understand the rest from the. You need to add the fileentry and after that you need to update it to be approved.
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
File file = uploadRequest.getFile("uploadFile");
DLFileEntry fileEntry = null;
Long lessonId = ParamUtil.getLong(request, "lid");
Lesson lll = LessonLocalServiceUtil.getLesson(lessonId);
String lesName = URLEncoder.encode(lll.getName(themeDisplay.getLocale()));
Date da = new Date();
String ext = FileUtil.getExtension(file.getName());
String dat = new SimpleDateFormat("yyyy-MM-dd").format(da);
String title = lesName + "-" + dat + "." + ext;
long portraitId = themeDisplay.getUser().getPortraitId();
byte[] imageBytes = FileUtil.getBytes(file);
InputStream is = new ByteArrayInputStream(imageBytes);
PortletPreferences preferences = request.getPreferences();
String nameRo=uploadRequest.getParameter("nameRO");
String nameEn=uploadRequest.getParameter("name");
DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), 0, "TestFolder");
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), request);
List<DLFileEntryType> tip = DLFileEntryTypeLocalServiceUtil.getFileEntryTypes(DLUtil.getGroupIds(themeDisplay));
fileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
themeDisplay.getScopeGroupId(),
themeDisplay.getScopeGroupId(),
dlFolder.getFolderId(),
file.getName(),
MimeTypesUtil.getContentType(file),
title,
request.getParameter("name"),
"",
tip.get(0).getFileEntryTypeId(),
null,
file,
is,
file.getTotalSpace(),
serviceContext);
DLFileEntryLocalServiceUtil.updateFileEntry(
themeDisplay.getUserId(),
fileEntry.getFileEntryId(),
file.getName(),
MimeTypesUtil.getContentType(file),
title,
"",
"",
true,
tip.get(0).getPrimaryKey(),
null,
file,
is,
file.getTotalSpace(),
serviceContext);
EDIT :
To acces the fileentry download url you can use
DLFileEntry dlf = DLFileEntryLocalServiceUtil.getDLFileEntry(f.get(i).getFileEntryId());
<a href='<%=themeDisplay.getPortalURL()+"/c/document_library/get_file?uuid="+DL.getUuid()+"&groupId="+themeDisplay.getScopeGroupId() %>' download>
Download </a>
Are you trying to call this API function from a commandline? (as the method main implies): You can't just startup a JVM and call Liferay API functions as no initialization is done yet.
You'll need to call API functions (esp. on Local services) from a webapplication - e.g. a portlet or a hook - this typically does not happen from a main method.
Edit: Take a look at the javadoc, granted, this does not give you many clues other than the argument names, but if you go through these and see the implementation as well, there are some things that might be worth trying/checking:
Make sure, userId is a valid id for a user.
Make sure that your value for groupId and repositoryId is valid as well - e.g. it needs to be the id for a site.
Same for folderId: Make sure that it's a valid id for a folder. For this example we don't know how you came up with the value.
You're giving 0 for the size (bytes.length)
I'm guessing that the file you hardcoded actually exists? Make extra extra sure that you don't have a typo in file- or foldername
If this doesn't solve your problem, let us know what exact problem you have with your arguments: "I have a problem" is not really enough information for any meaningful help
I have activated a WSP file which includes a website template. This works and I can see the solution int he solution gallery. When I try to create a website, based on that template, its not showing up. But it says "Status: Activated".
Then I tried to deactivate it and activate it again manually. Out of a sudden, there is a new template showing up, which takes the name of my template appended by a "2".
So whats happening here exactly? The code to activate my solution is:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
}
catch { ... }
Ok, I found the answer myself and want to share it here. The solution is, not to provide the solution in the catalog, but also to enable the features! It works like this:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
Guid solutionId = newUserSolution.SolutionId;
SPFeatureDefinitionCollection siteFeatures = web.Site.FeatureDefinitions;
var features = from SPFeatureDefinition f
in siteFeatures
where f.SolutionId.Equals(solutionId) && f.Scope == SPFeatureScope.Site
select f;
foreach (SPFeatureDefinition feature in features)
{
try
{
web.Site.Features.Add(feature.Id, false, SPFeatureDefinitionScope.Site);
}
catch { }
}
SPWebTemplateCollection webTemplates = web.Site.RootWeb.GetAvailableWebTemplates(1033);
SPWebTemplate webTemplate = (from SPWebTemplate t
in webTemplates
where t.Title == "Projekt"
select t).FirstOrDefault();
if (webTemplate != null)
{
try
{
web.Site.RootWeb.ApplyWebTemplate(webTemplate.Name);
}
catch { }
}
}
catch { ... }
I am creating a NEW sharepoint site from a silverlight webpart. I am using the ClientContext Model and it is working great for a team site template (STS#0). I need to create a NEW site from a CUSTOM site template that I have created, but I do not know how to reference this template being to specify a web template it is by name and only able to reference one of the standard templates.
Here is my code:
string siteUrl = App.RootSite;
string siteDescription = project.projectName; // "A new project site.";
int projectLanguage = 1033;
string projectTitle = project.projectName; // "Project Web Site";
string projectUrl = project.projectURL; //"projectwebsite";
bool projectPermissions = false;
string webTemplate = "STS#0"; //TODO: reference custom site template
try
{
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebCreationInformation webCreateInfo = new WebCreationInformation();
webCreateInfo.Description = siteDescription;
webCreateInfo.Language = projectLanguage;
webCreateInfo.Title = projectTitle;
webCreateInfo.Url = projectUrl;
webCreateInfo.UseSamePermissionsAsParentSite = projectPermissions;
webCreateInfo.WebTemplate = webTemplate;
oNewWebsite = oWebsite.Webs.Add(webCreateInfo);
clientContext.Load(
oNewWebsite,
website => website.ServerRelativeUrl,
website => website.Created,
website => website.Id);
clientContext.ExecuteQueryAsync(onQuerySucceeded, onQueryFail);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
Loop through all of your available templates, you will find that the custom template name has the guid in front of it: {A13D0D34-EEC2-4BB5-A563-A926F7F9681A}#ProjectSiteTemplate.
ClientContext clientContext = new ClientContext(siteUrl);
Web oWebsite = clientContext.Web;
WebTemplateCollection templates = oWebsite.GetAvailableWebTemplates(1033, true);
clientContext.Load(templates);
clientContext.ExecuteQueryAsync(onTemplateSucceeded, null);
private void onTemplateSucceeded(object sender, ClientRequestSucceededEventArgs args)
{
UpdateUIMethod updateUI = ShowTemplates;
this.Dispatcher.BeginInvoke(updateUI);
}
private void ShowTemplates()
{
foreach (WebTemplate template in templates)
{
MessageBox.Show(template.Id + " : "
+ template.Name + " : "
+ template.Title);
}
}
example
http://www.learningsharepoint.com/2010/07/25/programatically-create-site-from-site-template-sharepoint-2010/
I'm getting a stuck. Suppose that I create 5 sites. For each one, I create a few sharepoint groups. So, I create a dropdownlist control to bind 5 sites and when I click on any site there, I will get sharepoint groups created on it. But I always see the dropdownlist used to bind these groups still never change. I mean it only binds a few default groups in sahrepoint everytime. The new created groups is not.
And I have confusion like this
web.AssociatedGroups
web.Groups
web.SiteGroups
which one we will use this case ? Please guide me
Here my snippet code
private void BindSPGroupsToDropDownList(DropDownList ddl, string siteUrl)
{
ddl.Items.Clear();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
//web.SiteGroups
foreach (SPGroup spGroup in web.Groups)
{
ddl.Items.Add(new ListItem(spGroup.Name.Trim(), spGroup.ID.ToString()));
}
}
}
});
}
}
thanks in advance
You don't show how you add groups, so it is hard to see why you can't list them.
Some considerations:
groups are scoped at the site collection level, i.e. there is no notion of groups at the web (SPWeb) level; only at the SPSite level
I wrote code a couple of years ago for managing groups, so I don't remember the difference between the different properties. Looking at my code, I used SPWeb.SiteGroups to test if a group exists and to add a new group.
Here is my - slightly anonymized - code:
public static void CreateSiteGroup(SPSite site, string strGroupName, string strGroupDesc, string strGroupOwner) {
if (site == null) {
string message = GetMessagePrefix() + " Site is null";
XxxLog.Error(XxLogEventId.Common, message, XxxLogCategory.CommonBusiness);
} else if (String.IsNullOrEmpty(strGroupName)) {
string message = GetMessagePrefix() + " The group name is empty";
XxxLog.Error(XxxLogEventId.Common, message, XxxLogCategory.CommonBusiness);
} else {
try {
using (SPWeb rootWeb = site.RootWeb) {
SPMember owner;
if (String.IsNullOrEmpty(strGroupOwner)) {
owner = rootWeb.CurrentUser;
} else {
if (!ContainsGroup(site, strGroupOwner)) {
string message = GetMessagePrefix() + " Can not find owner group name: " + strGroupOwner;
XxxLog.Error(XxxLogEventId.Common, message, XxxLogCategory.CommonBusiness);
return;
} else {
owner = rootWeb.SiteGroups[strGroupOwner];
}
}
if (!ContainsGroup(site, strGroupName)) {
rootWeb.SiteGroups.Add(strGroupName,
owner,
null, // no default user
strGroupDesc);
} else {
string message = GetMessagePrefix() + " The group " + strGroupName + " was already present";
XxxLog.Info(message, XxxLogCategory.CommonBusiness);
}
}
} catch (Exception e) {
string message = GetMessagePrefix() + " Cannot create " + strGroupName + " group";
XxxLog.Error(XxxLogEventId.Common, message,e, XxxLogCategory.CommonBusiness);
}
}
}
public static Boolean ContainsGroup(SPSite site, string name) {
SPGroup group = null;
using (SPWeb rootWeb = site.RootWeb) {
foreach (SPGroup g in rootWeb.SiteGroups) {
if (g.Name.ToUpper().Equals(name.ToUpper())) {
group = g;
break;
}
}
}
return (group != null);
}