smbj: How can I get subdirectories only? - java

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);
}
}

Related

How to search file inside a specific folder in google API v3

As i am using v3 of google api,So instead of using parent and chidren list i have to use fileList, So now i want to search list of file inside a specific folder.
So someone can suggest me what to do?
Here is the code i am using to search the file :
private String searchFile(String mimeType,String fileName) throws IOException{
Drive driveService = getDriveService();
String fileId = null;
String pageToken = null;
do {
FileList result = driveService.files().list()
.setQ(mimeType)
.setSpaces("drive")
.setFields("nextPageToken, files(id, name)")
.setPageToken(pageToken)
.execute();
for(File f: result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
f.getName(), f.getId());
if(f.getName().equals(fileName)){
//fileFlag++;
fileId = f.getId();
}
}
pageToken = result.getNextPageToken();
} while (pageToken != null);
return fileId;
}
But in this method it giving me all the files that are generated which i don't want.I want to create a FileList which will give file inside a specific folder.
It is now possible to do it with the term parents in q parameter in drives:list. For example, if you want to find all spreadsheets in a folder with id folder_id you can do so using the following q parameter (I am using python in my example):
q="mimeType='application/vnd.google-apps.spreadsheet' and parents in '{}'".format(folder_id)
Remember that you should find out the id of the folder files inside of which you are looking for. You can do this using the same drives:list.
More information on drives:list method can be seen here, and you can read more about other terms you can put to q parameter here.
To search in a specific directory you have to specify the following:
q : name = '2021' and mimeType = 'application/vnd.google-apps.folder' and '1fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG' in parents
This examples search a folder called "2021" into folder with 1fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG
In my case, I'm writing a code in c++ and the request url would be:
string url = "https://www.googleapis.com/drive/v3/files?q=name+%3d+%272021%27+and+mimeType+%3d+%27application/vnd.google-apps.folder%27+and+trashed+%3d+false+and+%271fJ9TFZOe8G9PUMfC2Ts06sRnEPJQo7zG%27+in+parents";
Searching files by folder name is not yet supported. It's been requested in this google forum but so far, nothing yet. However, try to look for other alternative search filters available in Search for Files.
Be creative. For example make sure the files within a certain folder contains a unique keyword which you can then query using
fullText contains 'my_unique_keyword'
You can use this method to search the files from google drive:
Files.List request = this.driveService.files().list();
noOfRecords = 100;
request.setPageSize(noOfRecords);
request.setPageToken(nextPageToken);
String searchQuery = "(name contains 'Hello')";
if (StringUtils.isNotBlank(searchQuery)) {
request.setQ(searchQuery);
}
request.execute();

Create new directory in share-point using SOAP in java

I have just started working on share-point using java my firm uses share-point 2010 version so I have to work using SOAP and I have done following functionality.
Download Document from share-point.
Upload Document to share-point.
But I am stuck at creating new directory, I have tried some code by googling but no luck.
Here is my code:
public void createFolder(ListsSoap ls, String filePathToCreate,
String fileName, LoginDO loginDO, HttpServletResponse response)
throws Exception {
try {
String query = "";
String folderName = "NewFolder";
// 1. Prepare Query, Query Options and field Options
if (CommonUtilities.isValidStr(folderName)) {
// Prepare Query & Query Options for child folders
query = "<Batch OnError=\"Continue\" PreCalc=\"TRUE\" ListVersion=\"0\" " +
"RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"
+ "<Method ID=\"1\" Cmd=\"New\">"
+ "<Field Name=\"FSObjType\">1</Field>"
+"<Field Name=\"ID\">New</Field>"
+ "<Field Name=\"BaseName\">" + folderName + "</Field>"
+ "</Method></Batch>";
} else {
// Prepare Query & Query Options for Parent folders
query = "<Query><Where><Eq><FieldRef Name=\"FSObjType\" />"
+ "<Value Type=\"Lookup\">1</Value></Eq></Where></Query>";
}
UpdateListItems.Updates updates = null;
// 2. Prepare Query, QueryOptions & ViewFields object as per options
if (CommonUtilities.isValidStr(query)) {
updates = new UpdateListItems.Updates();
updates.getContent().add(
sharepointUtil.createSharePointCAMLNode(query));
}
// 3. Call Web service to get result for selected options
UpdateListItemsResult result = ls
.updateListItems(SHAREPOINT_FOLDER_NAME,updates);
/*
* CommonUtilities
* .getApplicationProperty(ApplicationConstants.SHAREPOINT_FOLDER_NAME
* ), "", msQuery, viewFields, "", msQueryOptions, "");
*/
// 4. Get elements from share point result
Element element = (Element) result.getContent().get(0);
NodeList nl = element.getElementsByTagName("z:row");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
System.out.println("Some.!");
}
} catch (Exception e) {
e.printStackTrace();
}
// logger.logMethodEnd();
}`
Anyhow updateListItems() method is executed without error but there is nothing in result.
Any help is appreciated.
Thank you :)
seems there was problem in
"RootFolder=\"https://xxx/Shared%20Documents/FPL%20SOs%20-%20JD%20Documents\">"
while passing root directory to create folder within.
found other way around by passing folderName with full directories hierarchy.
Thank you all for your inputs :)

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);
}
}
}

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

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

How to parse property value in properties file

Hi
I am loading a property file to establish DB connection,
ex:
DB1="JDBc................", username , password
above line is as in property file, but when i call getConnection method I need to send url, username and pw.
How can I parse it.
You can put your key/value pairs in a properties file like this:
dbUrl = yourURL
username = yourusername
password = yourpassword
Then you can load them into your app from the properties file:
private void loadProps() {
try {
InputStream is = getClass().getResourceAsStream("database_props.properties");
props = new Properties();
props.load(is);
is.close();
dbConnStr = props.getProperty("dbUrl");
username = props.getProperty("username");
password = props.getProperty("password");
}
catch(IOException ioe) {
log.error("IOException in loadProps");
for(StackTraceElement ste : ioe.getStackTrace())
log.error(ste.toString());
}
}
And then you can use those values to create your connection.
You can split the entry:
String dbProperty = prop.getProperty("DB1");
String[] dbDetails = dbProperty.split(",", 3);
dbDetails[0] will hold your JDBC..., [1] your username and [2] your password
Better still, you might want to hold them in different properties (As lweller said)
db.username = scott
db.password = tiger
db.url = ....
This way you get better clarity and control.
It is better to define separately
dburl =....
username =....
password = ...
Still if you want to parse it, you can use the split method of string to split by comma

Categories