Save file to Document directory in liferay 6.1 using API - file

I need to save a uploaded file in sub directory of Document & Media folder in liferay from web-form portlet.
I have extended the web Form portlet to do so, but file is getting uploaded successfully in database & not in Document & Media folder.
I tried following code to upload the file in document directory but no success please help .
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
String title = file.getName();
DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(themeDisplay.getScopeGroupId(), 0, "Test");
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(),actionRequest);
Map<String, Fields> fieldsMap = new HashMap<String, Fields>();
long fileEntryTypeId = DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT;
FileInputStream inputStream = new FileInputStream(file);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.addFileEntry(themeDisplay.getUserId(), 10153, dlFolder.getRepositoryId(),
dlFolder.getRepositoryId(), title, file.getContentType(), title, "fileDesc", "sss",
fileEntryTypeId, fieldsMap, file, inputStream, file.length(), serviceContext);
inputStream.close();
DLFileEntryLocalServiceUtil.updateFileEntry(themeDisplay.getUserId(), dlFileEntry.getFileEntryId(), title, file.getContentType(),
title, "fileDesc", "comment", true, dlFileEntry.getFileEntryTypeId(), fieldsMap, file, null, file.length(), serviceContext);

Try this code snippet
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);
Folder folderName = DLAppLocalServiceUtil.getFolder(parentRepositoryId,
parentFolderId,
"Folder Name");
long folderId = folderName.getFolderId();
long repositoryId = folderName.getRepositoryId();
FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
repositoryId,
folderId,
file.getName(),
contentType,
"File Name",
"description",
"changeLog",
inputStream,
file.length(),
serviceContext);

I know it's an old question, but I had similar issue today. I used DLFileEntryLocalServiceUtil, and I had to call both addFileEntry() and updateFileEntry() in order to correctly create the asset.
See Liferay DLFileEntryLocalServiceUtil.addFileEntry does not create AssetEntry record

Related

WPF Printdocument

Got this code below, how can I send an excel file to the printer?
Edit: I want to send an existing file (excel) to my "Microsoft Print to PDF" printer and then have it save it as a new file (pdf).
PrintDocument doc = new PrintDocument()
{
PrinterSettings = new PrinterSettings()
{
PrinterName = "Microsoft Print to PDF",
PrintToFile = true,
PrintFileName = System.IO.Path.Combine(#AppDomain.CurrentDomain.BaseDirectory + "\\pdf\\", "filename.pdf"),
}
};
doc.Print();

Code/Script to recursively search S3 bucket to unzip (GZIP) and move specific file from ZIP to new location

Hi I have an S3 bucket containing gzip files. Within each zip there is a single TSV file I want to move to a new folder or bucket (dont really mind which). The S3 bucket will be added to with new zip file each hour so this script needs to be something I can schedule or trigger. Happy to use CLI, Lambda or any other method! Pointers, links, help very much appreciated.
Ok so the fudge way to do this is with local processing:
Connect to S3
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "https://s3-eu-west-1.amazonaws.com";
AmazonS3Client s3Client = new AmazonS3Client(
S3AccessKey,
S3SecretKey,
config
);
Copy Down the Files you want to process
S3DirectoryInfo dir = new S3DirectoryInfo(s3Client, bucketname, "jpbodenukproduction");
dir.CopyToLocal(#"C:\S3Local");
Decompress the Gzip (containing the tar, containing the multiple files):
string directorypath = #"C:\S3Local";
DirectoryInfo directoryselected = new DirectoryInfo(directorypath);
foreach (FileInfo FileToDecompress in directoryselected.GetFiles("*.gz"))
{
Decompress(FileToDecompress);
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
Now deal with the tar file (using ICSharpCode.SharpZipLib):
foreach (FileInfo TarFile in directoryselected.GetFiles("*.tar"))
{
var stream = File.OpenRead(TarFile.FullName);
var tarArchive = ICSharpCode.SharpZipLib.Tar.TarArchive.CreateInputTarArchive(stream);
tb1.Text = "Processing:" + TarFile.Name;
try
{
tarArchive.ExtractContents(#"C:\S3Local\Trash\");
}
catch (Exception ziperror)
{
tb1.Text = "Delay Error in TarUnzip:" + ziperror;
Thread.Sleep(10000);
}
finally
{
tarArchive.Close();
stream.Close();
}
Finally do what you want with the unzipped files, I simply extracted the single file I need, recompressed and moved back up to S3.
My plan is to next convert into Lambda and get this running on a schedule.

renaming a file by adding current date

I'm working on a Project and a Part of it is renaming a File to "Filename + currentDate". I have been searching for an answer and found some helpful Topics on that Problem, but i still didn't get my code to work properly(or do anything at all).
Here is my code:
File oldTxt = new File("Filename.txt");
GregorianCalendar now = new GregorianCalendar();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String archivedName = "Filename"+
String.valueOf(dateFormat.format(now.getTime())).replace(".", "_")+".txt";
File archivedTxt = new File(archivedName);
oldTxt.renameTo(archivedTxt);
Any help would be highly appreciated.
You missed the line to create new file.
oldTxt.createNewFile();
File oldTxt = new File("Filename.txt");
--> oldTxt.createNewFile();
GregorianCalendar now = new GregorianCalendar();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
String archivedName = "Filename"+
String.valueOf(dateFormat.format(now.getTime())).replace(".", "_")+".txt";
File archivedTxt = new File(archivedName);
oldTxt.renameTo(archivedTxt);

Display XPS Document in WPF

I need to display data from a database into a WPF app and save it as an XPS document. I want to display it as part of a main window (with Toolbar, Menu and StatusBar) and not as a new window.
What control(s) should I use? Currently, I am looking at FixedDocument and FlowDocument. Am I on the right track? Any good material on how to start?
Improving on Stehpen's answer above...
Assume you've added a documents folder to your project:
Create a method GetDocument where the GetFilePath method refers to the Folder/Filename in the folder above.
private void GetDocument()
{
string fileName = Environment.CurrentDirectory.GetFilePath("Documents\\Title.xps");
Debugger.Break();
XpsDocument doc = new XpsDocument(fileName, FileAccess.Read);
XDocViewer.Document = doc.GetFixedDocumentSequence();
}
Where GetFilePath is an extension method that looks like this:
public static class StringExtensions
{
public static string GetFilePath(
this string EnvironmentCurrentDirectory, string FolderAndFileName)
{
//Split on path characters
var CurrentDirectory =
EnvironmentCurrentDirectory
.Split("\\".ToArray())
.ToList();
//Get rid of bin/debug (last two folders)
var CurrentDirectoryNoBinDebugFolder =
CurrentDirectory
.Take(CurrentDirectory.Count() - 2)
.ToList();
//Convert list above to array for Join
var JoinableStringArray =
CurrentDirectoryNoBinDebugFolder.ToArray();
//Join and add folder filename passed in
var RejoinedString =
string.Join("\\", JoinableStringArray) + "\\";
var final = RejoinedString + FolderAndFileName;
return final;
}
}
Add a Document viewer in your XAML
And add this code in the cs file:
string fileName = null;
string appPath= System.IO.Path.GetDirectoryName(Assembly.GetAssembly(typeof(DocumentWindow)).CodeBase);
fileName = appPath + #"\Documents\Help.xps";
fileName = fileName.Remove(0, 6);
XpsDocument doc = new XpsDocument(fileName, FileAccess.Read);
docView.Document = doc.GetFixedDocumentSequence();

How import a group of existing txt files in isolatedStorageDevice in windows phone 7

I have 17 files in .txt, I want import all this files to isolatedStorageDevice.
How can i do this???
remember: i dont wanna write a file i want put a existing file there.
the files are in the folder in Project ,example: (/Files/user.txt)
Manually
Use any existing Windows Phone Isolated Storage explorer tool
Programmatically
You'll have to write a files copy. Assume there is a CordovaSourceDictionary.xml as part of your project which specifies what files must be moved to IsolatedStorage
<CordovaSourceDictionary>
<FilePath Value="www\img\logo.png"/>
<FilePath Value="www\js\index.js"/>
<FilePath Value="www\cordova-2.1.0.js"/>
<FilePath Value="www\css\index.css"/>
<FilePath Value="www\index.html"/>
</CordovaSourceDictionary>
Then you can copy your files using code below
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative));
if (streamInfo != null)
{
StreamReader sr = new StreamReader(streamInfo.Stream);
//This will Read Keys Collection for the xml file
XDocument document = XDocument.Parse(sr.ReadToEnd());
var files = from results in document.Descendants("FilePath")
select new
{
path = (string)results.Attribute("Value")
};
StreamResourceInfo fileResourceStreamInfo;
using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
foreach (var file in files)
{
fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative));
if (fileResourceStreamInfo != null)
{
using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
{
byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);
string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
if (!appStorage.DirectoryExists(strBaseDir))
{
Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir);
appStorage.CreateDirectory(strBaseDir);
}
// This will truncate/overwrite an existing file, or
using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create))
{
Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length);
using (var writer = new BinaryWriter(outFile))
{
writer.Write(data);
}
}
}
}
else
{
Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?");
}
}
}
}

Resources