Can strange paths cause a wrong structure of the file system? - java

Consider the following example:
//both files are the same
final File path = new File("/home/alice/../bob/file.txt");
final File canonicalPath = new File("/home/bob/file.txt");
File parent = canonicalPath;
while((parent = parent.getParentFile()) != null) {
System.out.println(parent.getName());
}
This would print:
bob
home
If I would use path instead of canonicalPath, would the output be the same or would it be:
bob
home
alice
home
This woule be very strange because it would suggest that alice is the parent of home which is not true.

First of all, I think you want to compare home/alice/../bob/file.txt without a starting / instead of /home/alice/../bob/file.txt, otherwise you'd be comparing apples with oranges.
Actually it's more interesting to compare the difference using this code instead:
File parent;
parent = path;
while((parent = parent.getParentFile()) != null) {
System.out.println(parent);
}
parent = canonicalPath;
while((parent = parent.getParentFile()) != null) {
System.out.println(parent);
}
The parents of "home/alice/../bob/file.txt":
"home/alice/../bob"
"home/alice/.."
"home/alice"
"home"
null
In contrast, the parents of "home/bob/file.txt":
"home/bob"
"home"
null

The result would not be the same since those are two different filesystem paths.
But use Path instead:
final Path path = Paths.get("/home/bob/../alice/somefile");
final Path normalized = path.normalize(); // /home/alice/somefile
path.toAbsolutePath(); // get an absolute path
path.toRealPath(); // same, but follows symlinks
// etc etc

Related

Retrieve last level directory name from path

I have a string that represents a path ... something like this:
/A/B/C/D/E/{id}/{file_name}.ext
The path structure could be different but in general I would like to retrieve last directory name (in the example {id}) before the file-name.
I would like to use Path java class.
Is there a simple and safe way to retrieve last directory name using Path class?
Path#getParent returns a path’s parent. You can then use Path#getFileName:
path.getParent().getFileName();
You could use getName() with File which is available
Reference : https://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29
File f = new File("C:\\Dummy\\Folder\\MyFile.PDF");
System.out.println(f.getName());
Which returns you MyFile.PDF.
(or)
// Path object
Path path
= Paths.get("D:\\eclipse\\configuration"
+ "\\myconfiguration.conf");
// call getName(int i) to get
// the element at index i
Path indexpath = path.getName(path.getNameCount()-2);
// prints the name
System.out.println("Name of the file : " + indexpath);
Which prints myconfiguration.conf. Hope it helps !

smbj: How can I get subdirectories only?

I use https://github.com/hierynomus/smbj for samba access.
I want get only the subfolders of my target directory.
Whith following code I get "..", "." and all the files - is there an elegant way to get subdirectories only?
SmbConfig config = SmbConfig.builder().withMultiProtocolNegotiate(true).build();
smbClient = new SMBClient(config);
Connection connection = smbClient.connect(smbServerName);
AuthenticationContext ac = new AuthenticationContext(smbUser, smbPassword.toCharArray(), smbDomain);
Session session = connection.authenticate(ac);
share = (DiskShare) session.connectShare(smbShareName);
List<FileIdBothDirectoryInformation> subs = share.list("mydirWhichSubDirsIwant");
You need to filter out the results from the returned list. If you only want the subdirectories you can get them as follows:
List<String> subDirectories = new ArrayList<>();
for (FileIdBothDirectoryInformation sub: subs) {
String filename = sub.getFileName();
if (".".equals(filename) || "..".equals(filename)) {
continue;
}
if (EnumWithValue.EnumUtils.isSet(sub.getFileAttributes(), FileAttributes.FILE_ATTRIBUTE_DIRECTORY)) {
subDirectories.add(filename);
}
}

View.getView() returns null

I'm trying to find my folder or view in my database. Which named Team Documents this folder has some filter option like By Date, By Category. But this returns me a null even the folder already exists.
String dbServer = "d23dbm95/23/A/IBM", dbFileName = "dbom\\farizan\\stsklb1.nsf";
public void runNotes()
{
Session session = null;
Database db = null;
View view = null;
Document doc = null;
try
{
NotesThread.sinitThread();
session = NotesFactory.createSession();
System.out.println("User = " + session.getUserName());
db = session.getDatabase(dbServer, dbFileName);
if(db.isOpen())
{
System.out.println("Title "+db.getTitle());
view = db.getView("Team Documents \\ By Date");
if(view == null)
{
System.out.println("still null");
}
}
}
catch(NotesException e)
{
e.printStackTrace();
}
}
I tried also to fill my getView() method like Team Documents. But still returns a null. Any approach to this problem?
While it would have been more helpful if you had included a link to a screenshot of your Domino Designer client's folder list, my best guess is that you have two folders, not one folder with "filter options". Also, my guess is that "Team Documents" is not actually a folder; it's just a prefix on the folder names that makes them appear to be nested in a parent folder.
If that's the case, you would need
iew = db.getView("Team Documents\\By Category");
Or
iew = db.getView("Team Documents\\By Date");
Note: No spaces before & after the backslashes.
If my assumptions above are not correct, then my suggestion would be to assign alias names to the folders in Domino Designer and use the aliases instead of the display names in your code. Frankly, that's always a good practice, because it allows your code to continue working even if you decide to change the display names.

Orient DB - Export subclasses of a specified class using JAVA

Im working with exporting and importing Orient DB using java. I could export a whole database. But when i specify to export a specified class it export that class only. Sub classes are not exported. Here is the code:
ODatabaseDocumentTx db = new ODatabaseDocumentTx("remote:localhost/sampleDataBase").open("admin", "admin");
ODatabaseExport export = new ODatabaseExport(db, "DataCont/FinalTry.gz", listener);
Set<String> a= new HashSet<String>();
a.add("Employee".toUpperCase());
export.setIncludeClasses(a);
export.exportDatabase();
export.close();
So is this suppose to be or am i doing anything wrong?
Checking the source code for ODatabaseExport it does seem that it only takes clusters/records which are exactly of the type specified with setIncludeClasses(). For instance in exportRecords():
ODocument doc = (ODocument) rec;
final String className = doc.getClassName() != null ? doc.getClassName().toUpperCase() : null;
if (includeClasses != null) {
if (!includeClasses.contains(className))
continue;
} else if (excludeClasses != null) {
if (excludeClasses.contains(className))
continue;
}
They have similar checks in several other places in that class. This would mean that you need to put into the a set all the classes you want to export yourself.
You can add this piece of code if want to export all subclasses too:
Set<String> classesToExport = new HashSet<>();
classesToExport.add("Employee".toUpperCase());
OSchema oSchema = db.getMetadata().getSchema();
for (String className : classesToExport) {
OClass clazz = oSchema.getClass(className);
for(OClass subClass : clazz.getAllBaseClasses()){
//String subClassName = subClass.getName();
String subClassName = subClass.getName().toUpperCase();
if(!classesToExport.contains(subClassName)){
classesToExport.add(subClassName);
}
}
}

How to get all the parents of the treeitem?

I am programming in GWT
i have tree which is like
1.A Folder
1.Marketing Folder
2.Sales Folder
1.In Folder
1.Invoice.txt
2. Out Folder
2.B folder
1. xyz
1.fgh
2. abc
3.C foder
If i click on Invoice.txt the output should be like
"A folder/Sales FOlder/In FOlder/Invoice.txt"
i am using getParent method to display th output but it is show me only the
"In folder".
Plese some one help me to understand this,
How wil i get the complete path.
I am using tree Widget
private String getPath(TreeItem selectedItem) {
StringBuilder builder = new StringBuilder();
buildPath(selectedItem, builder);
return builder.toString();
}
private void buildPath(TreeItem item, StringBuilder builder) {
if (item.getParentItem() != null) {
buildPath(item.getParentItem(), builder); //build path
builder.append('/');
}
builder.append(item.getText());
}

Categories