I am trying to list all the files and folders under the root folder of liferay site.
QueryDefinition queryDefinition = new QueryDefinition(WorkflowConstants.STATUS_ANY, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
List<Object> list = DLFolderLocalServiceUtil.getFoldersAndFileEntriesAndFileShortcuts(groupId, folderId, null, true, queryDefinition);
Is it the right way? How to differentiate the files and folders?
You can get and differentiate all files, folders and shortcuts as following:
List <Object> foldersAndFileEntriesAndFileShortcuts =
DLAppServiceUtil.getFoldersAndFileEntriesAndFileShortcuts(
folder.getGroupId(), folderId, WorkflowConstants.STATUS_ANY,
true, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
for (Object folderAndFileEntryAndFileShortcut: foldersAndFileEntriesAndFileShortcuts) {
if (folderAndFileEntryAndFileShortcut instanceof FileEntry) {
FileEntry fileEntry = (FileEntry) folderAndFileEntryAndFileShortcut;
} else if (folderAndFileEntryAndFileShortcut instanceof Folder) {
Folder subFolder = (Folder) folderAndFileEntryAndFileShortcut;
} else if (folderAndFileEntryAndFileShortcut instanceof DLFileShortcut) {
DLFileShortcut dlFileShorcut = (DLFileShortcut) folderAndFileEntryAndFileShortcut;
}
}
There is a util called: DLAppServiceUtil with method: getFoldersAndFileEntriesAndFileShortcuts. Check out this this link (liferay code).
Related
Basically, I'm trying to return a collection of strings in Java.
But...
each string must be unique because they're all the names of ".db" files in current folder, so I thought this collection should be LinkedHashSet.
The elements (filenames) must maintain the exact same order, so I can choose one of them by it's order number in the collection.
My main routine will show this collection in a GUI component (maybe a JList) for the user to choose one of them (without the .db extension).
I'm totally newbie (as you can see), so if you think there are better options than LinkedHashSet please tell me.
Also, how can I grab this collection in the main class?
What I've got so far:
public Set GetDBFilesList() {
//returns ORDERED collection of UNIQUE strings with db filenames
LinkedHashSet a = new LinkedHashSet();
FilenameFilter dbFilter = (File file, String name) -> {
return name.toLowerCase().endsWith(".db");
};
String dirPath = "";
File dir = new File(dirPath);
File[] files = dir.listFiles(dbFilter);
if (files.length > 0) {
for (File aFile : files) {
a.add(aFile.getName());
}
}
return a;
}
You want an ordered and unique collection - LinkedHashSet is a good choice.
Some comments on your methode:
Your should use Generics f.e.: LinkedHashSet<File> or LinkedHashSet<String>
The check for files.length is unnecessary, but you could check for null if the path is not a directory or an I/O error occured
You should name your variables properly: a is not a good name
Your methode can be static - maybe in a static helper class?
The Set.add methode returns true or false if the item was added or not, you should check that just in case
Putting all together:
//Your Main class
public class Main
{
public static void main(String[] args)
{
File dir = new File("");
Collection<File> dbFiles = DbFileManager.getDatabaseFiles(dir);
}
}
//Your DB File Reader Logic
public class DbFileManager
{
public static Collection<File> getDatabaseFiles(File directory)
{
Collection<File> dbFiles = new LinkedHashSet<>();
//filter code etc.
boolean success = dbFiles.addAll(directory.listFiles(filter));
//Check if everthing was added
return dbFiles;
}
}
I'm trying to rename the entries of an archive using the libarchive library.
In particular I'm using the function archive_entry_set_pathname.
Files and empty directories are correctly renamed, but unfortunately this is not working if a directory is not empty: instead of being renamed, a new empty directory with the new name is created as sibling of the target directory, which has the old name.
Relevant code snippet:
...
while (archive_read_next_header(inputArchive, &entry) == ARCHIVE_OK) {
if (file == QFile::decodeName(archive_entry_pathname(entry))) {
// FIXME: not working with non-empty directories
archive_entry_set_pathname(entry, QFile::encodeName(newPath));
}
int header_response;
if ((header_response = archive_write_header(outputArchive, entry)) == ARCHIVE_OK) {
... // write the (new) outputArchive on disk
}
}
What's wrong with non-empty directories?
In an archive, the files are stored with their full path names relative to the root of the archive. Your code only matches the directory entry, you also need to match all entries below that directory and rename them. I'm no Qt expert and I haven't tried this code, but you will get the idea.
QStringLiteral oldPath("foo/");
QStringLiteral newPath("bar/");
while (archive_read_next_header(inputArchive, &entry) == ARCHIVE_OK) {
QString arEntryPath = QFile::decodeName(archive_entry_pathname(entry));
if(arEntryPath.startsWith(oldPath) {
arEntryPath.replace(0, oldPath.length(), newPath);
archive_entry_set_pathname(entry, QFile::encodeName(arEntryPath));
}
int header_response;
if ((header_response = archive_write_header(outputArchive, entry)) == ARCHIVE_OK) {
... // write the (new) outputArchive on disk
}
}
I am trying to use the ZipFiles() utility method and its producing an empty zip file. I am using Sitecore 6.5. There are no error, permissions or otherwise.
Any thoughts? Here is the code.
public void CreateZipFile(string zipfileName, List<string> files)
{
var zipfile = string.Format("{0}/{1}/{2}", TempFolder.Folder, "myfolder", zipfileName) ;
var fileArray = files.ToArray();
var x = FileUtil.ZipFiles(zipfile, fileArray);
}
EDIT:
I am passing the files like this
var files = new List<string> { FileUtil.MapPath("/temp/sample.xlf") };
The proper usage of FileUtil.ZipFiles method is:
FileUtil.ZipFiles("/test.zip", new []{"/web.config", "/otherfile.txt"})
Sitecore automatically maps paths. The zip file will be created in your web app root.
EDIT AFTER COMMENT
If you want to create a zip file outside the web root and with a flat structure inside, you can use Sitecore ZipWriter class like this:
public static string ZipFiles(string absolutePathToZipfile, string[] files)
{
using (ZipWriter zipWriter = new ZipWriter(absolutePathToZipfile))
{
foreach (string path in files)
{
using (FileStream fileStream = System.IO.File.OpenRead(path.StartsWith("/") ? FileUtil.MapPath(path) : path))
zipWriter.AddEntry(FileUtil.GetFileName(path), fileStream);
}
}
return absolutePathToZipfile;
}
i am working on CDT eclipse plug in development, i am trying to get the list of sources files which exist in eclipse project explorer using CDT code using following code ,which results null.
Case1:
IFile[] files2 = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(new URI("file:/"+workingDirectory));
for (IFile file : files2) {
System.out.println("fullpath " +file.getFullPath());
}
Case2:
IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocationURI(getProject().getRawLocationURI());
for (IFile file : files) {
System.out.println("fullpath " +file.getFullPath());
}
Case3:
IFile[] files3 = ResourceLookup.findFilesByName(getProject().getFullPath(),ResourcesPlugin.getWorkspace().getRoot().getProjects(),false);
for (IFile file : files3) {
System.out.println("fullpath " +file.getFullPath());
}
Case4:
IFolder srcFolder = project.getFolder("src");
Case 1 ,2,3 giving me output null, where i am expecting list of files;
in Case 4: i am getting the list of "helloworld/src" files, but i am expecting to get the files from the existing project mean main root ,ex:"helloworld"
please suggest me on this.
You can either walk through the worspace resources tree using IResourceVisitor - or you can walk through CDT model:
private void findSourceFiles(final IProject project) {
final ICProject cproject = CoreModel.getDefault().create(project);
if (cproject != null) {
try {
cproject.accept(new ICElementVisitor() {
#Override
public boolean visit(final ICElement element) throws CoreException {
if (element.getElementType() == ICElement.C_UNIT) {
ITranslationUnit unit = (ITranslationUnit) element;
if (unit.isSourceUnit()) {
System.out.printf("%s, %s, %s\n", element.getElementName(), element.getClass(), element
.getUnderlyingResource().getFullPath());
}
return false;
} else {
return true;
}
}
});
} catch (final CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Note there may be more source files then you actually want (e.g. you may not care system about headers) - you can filter them by checking what the underlying resource is.
I'm using the following code, using the SharpZipLib library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file);
}
zipFile.CommitUpdate();
}
I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.
My solution was to set the NameTransform object property of the ZipFile to a ZipNameTransform with its TrimPrefix set to the directory of the file. This causes the directory part of the entry names, which are full file paths, to be removed.
public static void ZipFolderContents(string folderPath, string zipFilePath)
{
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.NameTransform = new ZipNameTransform(folderPath);
foreach (string file in files)
{
zipFile.BeginUpdate();
zipFile.Add(file);
zipFile.CommitUpdate();
}
}
}
What's cool is the the NameTransform property is of type INameTransform, allowing customisation of the name transforms.
How about using System.IO.Path.GetFileName() combined with the entryName parameter of ZipFile.Add()?
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file, System.IO.Path.GetFileName(file));
}
zipFile.CommitUpdate();
}
The MSDN entry for Directory.GetFiles() states that The returned file names are appended to the supplied path parameter. (http://msdn.microsoft.com/en-us/library/07wt70x2.aspx), so the strings you are passing to zipFile.Add() contain the path.
According to the SharpZipLib documentation, there is an overload of the Add method,
public void Add(string fileName, string entryName)
Parameters:
fileName(String) The name of the file to add.
entryName (String) The name to use for the ZipEntry on the Zip file created.
Try this approach:
string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file, Path.GetFileName(file));
}
zipFile.CommitUpdate();
}