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
Related
I have been looking for ways to upload BASE64 binary files days and I am stuck.
First of all a do not know how to convert BASE64 binary file to array buffer, blob, ... Everything is about BASE64 string but I have BASE64 binary file.
Do you have any solution?
You need to convert this Base64 string to byte array. C# Programming provide several approaches to do this without trouble. Following Upload large files sample SharePoint Add-in and Convert.FromBase64String(String) Method, both at Microsoft Docs, the final code that meet your requirements will be like this:
//This approach is useful for short files, less than 2Mb:
public void UploadFileContentFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that target library exists. Create if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
FileCreationInformation newFile = new FileCreationInformation();
// The next line of code causes an exception to be thrown for files larger than 2 MB.
newFile.Content = Convert.FromBase64String(base64Str);
newFile.Url = fileName;
// Get instances to the given library.
List docs = web.Lists.GetByTitle(libraryName);
// Add file to the library.
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
//This other approach provides you to Upload large files, more than 2Mb:
public void UploadDocumentContentStreamFromBase64(ClientContext ctx, string libraryName, string fileName, string base64Str)
{
Web web = ctx.Web;
// Ensure that the target library exists. Create it if it is missing.
if (!LibraryExists(ctx, web, libraryName))
{
CreateLibrary(ctx, web, libraryName);
}
byte[] fileContent = Convert.FromBase64String(base64Str);
using (MemoryStream memStream = new MemoryStream(fileContent))
{
FileCreationInformation flciNewFile = new FileCreationInformation();
// This is the key difference for the first case - using ContentStream property
flciNewFile.ContentStream = memStream;
flciNewFile.Url = fileName;
flciNewFile.Overwrite = true;
List docs = web.Lists.GetByTitle(libraryName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
ctx.Load(uploadFile);
ctx.ExecuteQuery();
}
}
Whenever I am trying to get the image file using the document Id, getting following error
Could not load file or assembly 'Kofax.CEBPM.ThinClient.DocumentServices, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cf95ca7471e897ff' or one of its dependencies. The system cannot find the file specified.
FYI : Document ID is valid and I am able to search the image in KTA's Repository Browser.
I have tried different ways to get the image but all are failing. Any help ?
private static void GetDocument(string sessionId, string docId)
{
try
{
CaptureDocumentService captureDocumentService = new CaptureDocumentService();
ReportingData reportingData = new ReportingData();
// Using simple GetDocument method
Document document = captureDocumentService.GetDocument(sessionId, null, docId);
// Using GetDocumentAsFile with valid path
captureDocumentService.GetDocumentAsFile(sessionId, docId, #"C:\ValidPath\", "dummy.abc");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine(ex.Message);
}
}
Judging from the error message, their either is an issue with permissions (check your path and ACLs in KTA) or the kind of file in your repository (are you sure it's a TIFF?)
Personally, I'd go with the GetDocumentFile method - this returns a stream, which may give you more flexibility. Here's an example:
public string ExportDocumentImages(string sessionId, string documentId, string outputFolder, string extension)
{
var cds = new CaptureDocumentService();
var doc = cds.GetDocument(sessionId, null, documentId);
Directory.CreateDirectory(outputFolder);
var fileName = Path.Combine(
outputFolder,
doc.Id + extension);
using (var fs = File.Create(fileName))
{
var s = cds.GetDocumentFile(sessionId, null, doc.Id, "");
s.CopyTo(fs);
}
return fileName;
}
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;
}
As many of your answers would suggest, I am able to get the details of a particular username using a PrincipalContext and a PrincipalSearcher but I was curious to learn the exact syntax and uses of filter in DirectorySearcher.
Could anyone help me in the right path to learn more about it, because I have a DirectorySearcher filter like this but I am not getting the expected results.
This is my code
Dictionary<string, string> Ids = new Dictionary<string, string>();
DirectoryEntry entry = new DirectoryEntry(ConfigurationManager.AppSettings["LDAPPath"].ToString());
DirectorySearcher dSearcher = new DirectorySearcher(entry);
string guid1 = string.Empty;
dSearcher.Filter = "(&(objectClass=user)(cn=SomeUserName"))";
dSearcher.PropertiesToLoad.Add("isDeleted");
dSearcher.PropertiesToLoad.Add("objectGUID");
dSearcher.PropertiesToLoad.Add("objectSid");
SearchResult sResultSet = dSearcher.FindOne();
if (sResultSet.Properties["objectGUID"][0].GetType() == typeof(Byte[]))
{
Byte[] objByteArray = (Byte[])sResultSet.Properties["objectGUID"][0];
Guid objGUID = new Guid(objByteArray);
Ids.Add("GUID", objGUID.ToString());
}
if (sResultSet.Properties["objectSid"][0].GetType() == typeof(Byte[]))
{
Byte[] sidInBytes = (Byte[])sResultSet.Properties["objectSid"][0]; ;
var objSid = new SecurityIdentifier(sidInBytes, 0);
Ids.Add("SID", objSid.ToString());
}
return Ids;
What I am trying to do is get the guid of the user by passing the username, but I am not getting the result and I don't know what I've done wrong in this code.
I am getting the correct result when I use PrincipalContext and PrincipalSearcher class. Please help me. Thank you
I have text file with List Name and item name. I need to get item guid by it's name. how? (not using foreach splistitem item in splist cause the text file is large and the loop is going to take a toll)
You may have enough information to use the SPWeb function GetListItem, otherwise you will need to try SPWeb.SearchListItems. Neither of which is going to be all the fast either.
The web services have a decent search function that I have used such as:
public static string GetPageId(string listName, string webPath, string pageTitle)
{
string pageId = "";
IntranetLists.Lists lists = new IntranetLists.Lists();
lists.UseDefaultCredentials = true;
lists.Url = webPath + "/_vti_bin/lists.asmx";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + pageTitle + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
Guid g = GetWebID(webPath);
XmlNode items = lists.GetListItems(listName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, g.ToString());
foreach (XmlNode listItem in SPCollection.XpathQuery(items, "//sp:listitems/rs:data/z:row"))
{
XmlAttribute id = listItem.Attributes["ows_Id"];
if (id != null)
{
pageId = id.Value;
}
}
return pageId;
}
public static XmlNodeList XpathQuery(XmlNode xmlToQuery, string xPathQuery)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlToQuery.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
return doc.SelectNodes(xPathQuery, mg);
}
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsitedataquery.aspx or CamlQuery
SPListItemCollection items = web.Lists.GetItems(new SPQuery() { Query = "YOUR QUERY" });
Go to the list settings page. Right click on "Title, description and navigation" and copy the URL. Paste that into notepad and copy everything after "List=" in the string. That's your URL Encoded GUID for the list. All you need to do is decode it here http://www.albionresearch.com/misc/urlencode.php
source: http://weblogs.asp.net/jimjackson/archive/2008/02/11/get-a-sharepoint-list-guid-from-the-browser.aspx
this is for manually getting each GUID of a certain list.