Issue with wildcard directory search - java

I am running into an issue with trying to validate the existence of a file in a directory utilizing a wildcard.
The method is supposed to determine if a file with name FAACIFP_(year)(cycle).DAT could be found in the current directory.
I've tried running a PathMaker.matches("glob:FAACIFP_18") with IF/ELSE and when I tested it, it would always evaluate TRUE. So, I tried a lambda function, and it won't find the file.
Shouldn't the lambda below print the file name, or am I misunderstanding/misusing it?
static void getCnvrtdCifpName() throws IOException{
String cnvFileName = "FAACIFP_"+Year.now()
.format(DateTimeFormatter.ofPattern("yy"));
Path cnvFilePath = Paths.get(System.getProperty("user.dir"));
Files.find(cnvFilePath,0,(path,attr) ->
path.getFileName().startsWith(cnvFileName)).forEach(System.out::println);
System.out.println("EVALUATING METHOD....\t SEARCH PATH: "+cnvFilePath
+" \n\t\t\t FILE STRING: "+cnvFileName);
}
Output:
run:
Located RAW CIFP file FAACIFP18
EVALUATING METHOD.... SEARCH PATH: C:\Users\u314170\Documents\Personal\Java\NetBeans\A424Parser
FILE STRING: FAACIFP_18
BUILD SUCCESSFUL (total time: 0 seconds)

Two problems:
1) change the maxdepth in your find call to 1 (from zero)
2) path.getFileName() returns a full pathname. You will want to evaluate only the filename portion (look at getName(getNameCount()-1)

After the suggestions, I finally found a resolution:
static void getCnvrtdCifpName() throws IOException{
String cnvFileName = "FAACIFP_"+Year.now()
.format(DateTimeFormatter.ofPattern("yy"));
Path cnvFilePath = Paths.get(System.getProperty("user.dir"));
DirectoryStream<Path> cnvFileStream = Files.newDirectoryStream(cnvFilePath,cnvFileName+"*");
System.out.println("EVALUATING METHOD....\t SEARCH PATH: "+cnvFilePath
+" \n\t\t\t FILE STRING: "+cnvFileName);
List cnvDirList = new ArrayList();
for(Path file: cnvFileStream){
cnvDirList.add(file.getFileName().toString());
}
cnvFileStream.close();
System.out.println(cnvDirList);
}
With output:
run:
EVALUATING METHOD.... SEARCH PATH: C:\Users\u314170\Documents\Personal\Java\NetBeans\A424Parser
FILE STRING: FAACIFP_18
[FAACIFP_1808.dat, FAACIFP_1810.txt, FAACIFP_1811.txt]
BUILD SUCCESSFUL (total time: 0 seconds)
I really enjoy the problem-solving challenges while learning Java. There are so many resources out there, and many different ways to resolve an issue.

Related

Looking for files of certain extension using lambda

As an exercise, I decide to rewrite some code of mine to use lambda expression. The code should check if a given string is a path to a file with .pdf extension and then it should display all the files that meet this requirement. This so what I've already come up with:
Files.newDirectoryStream(Paths.get(args[0]), path -> path.toFile()
.toString()
.endsWith(".pdf"))
.forEach(System.out::println);
This code fails at one point: it also displays directories. Could you tell me why the following code fails to compile?
Files.newDirectoryStream(Paths.get(args[0]), path -> path.toFile()
.isFile()
.toString()
.endsWith(".pdf"))
.forEach(System.out::println);
Your second code fails to compile because isFile returns a boolean. Once you have a boolean, file name is gone; even if you could convert it to String, matching its suffix to ".pdf" would fail anyway.
You are testing two separate conditions, so you should test them in two separate checks:
Files.newDirectoryStream(Paths.get(args[0]), path ->
Files.isRegularFile(path) && path.toString().endsWith(".pdf")
).forEach(System.out::println);
Note that path.toString().endsWith(...) can be checked without converting Path to File.
Because the compiler expects to have a boolean as second argument of
newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
Filter being a functional interface defined as :
boolean accept(T entry) throws IOException;
But here :
.isFile()
.toString()
a String is returned.
Make things in two times by combining two boolean expressions :
Files.newDirectoryStream(Paths.get(args[0]), path ->
Files.isRegularFile(path)
&& path.toString().endsWith(".pdf"))
.forEach(System.out::println);
In addition to Andreas comment about :
path.toFile().toString().endsWith(".pdf"))
that may be abbreviated by : path.toString().endsWith(".pdf"), you could also replace
path.toFile().isFile() by Files.isRegularFile(path).
It allows to rely only on the java.nio.file API rather that mixing it with the java.io.file API.

How to split the string using comma delimiter in Jenkins Groovy script?

I have tried to get all the solution files(*.sln) in a given path and print it individually by split the string(each solution file path) using comma delimiter. Programming script language am using is Jenkins Groovy. Am getting the below specified error when build the Jenkins job. Any one please look into this and guide me to proceed in a right way.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
def resultList = files.tokenize(",")
for(i=0; i<resultList.size();i++)
{
println resultList[i]
}
Error Details:
hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.tokenize() is applicable for argument types: (java.lang.String) values: [,]
Possible solutions: toUnique(), toUnique(), toUnique(java.util.Comparator), takeWhile(groovy.lang.Closure), toUnique(groovy.lang.Closure), toUnique(java.util.Comparator)
Thanks in advance!!
Myself itself found an answer for my above problem. Please find below the modified working code.
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\jobs', '**/*.sln'
assert files instanceof List
println files.size()+" solution files found in the given path. Below are the found solution files details. \n"
for(i=0;i<files.size();i++)
{
println files[i];
}
Thanks

synonyms() error in wordnet

I want to use synonyms () described in 'Intro to the tm package' for R. It uses the wordnet package. The wordnet package downloaded from CRAN does not have Dict (dictionary) in its directory. I downloaded it from the Princeton site and copied it over to the directory. After using sys.setenv() and setDict() for setting paths, I still get this error:
Error in sort(unique(unlist(lapply(synsets, getWord))))
error in evaluating the argument 'x' in selecting a method for function 'sort': Error in unique(unlist(lapply(synsets, getWord))) :
error in evaluating the argument 'x' in selecting a method for function 'unique': Error in .jcall(synset, "Ljava/util/List;", "getWord") :
java.lang.NumberFormatException: For input string: "t"
when I try synonyms("company", pos = "NOUN") or another English word in place of 'company'. The problem is in getSynonyms() called from synonyms(). Any idea on how to fix this problem?
Different combinations lead to different input string NumberFormatException. My Java is version 1.8. I tried all the online resources. I added two paths to PATH for R's bin and RJava's jri. Discussion on the exception indicates it is a string to numeric conversion issue. I have made sure that Java to R linkage (via rJava) works (URL: https://www.rforge.net/rJava/ ).

Get history of a Deleted File from SVN using SVNKit

I am trying to access Revision History of a file that has been deleted using SVNKit.
Following is what I am doing to achieve that.
SVNClientManager manager = SVNClientManager.newInstance();
SVNLogClient logClient = manager.getLogClient();
logClient.doLog(svnURL, new String[] { fileName }, SVNRevision.create(deletedRevision),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, false, true, -1, null,
new ISVNLogEntryHandler() {
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
log.debug(" ==== " + logEntry.getChangedPaths() + " === "
+ logEntry.getRevision());
}
});
Here, deletedRevision => The SVN revision in which File was deleted.
When this code is executed I keep on getting following exceptions:
org.tmatesoft.svn.core.SVNException: svn: '<FilePath>' path not found: 404 Not Found (https://<RepositoryURL>
at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:64)
at org.tmatesoft.svn.core.internal.wc.SVNErrorManager.error(SVNErrorManager.java:51)
at org.tmatesoft.svn.core.internal.io.dav.DAVRepository.logImpl(DAVRepository.java:976)
at org.tmatesoft.svn.core.io.SVNRepository.log(SVNRepository.java:1034)
at org.tmatesoft.svn.core.wc.SVNLogClient.doLog(SVNLogClient.java:1024)
at org.tmatesoft.svn.core.wc.SVNLogClient.doLog(SVNLogClient.java:891)
at com.blueoptima.connectors.scr.SVN.getWorkingFileList(SVN.java:711)
... 4 more
Is it something that I am doing wrong here? Is there any other way to get the History of a deleted file using SVNKit
Though this question has been asked more than a year back but still thought of answering it if it could be other's help.
I didnt try for retrieving history of a deleted file but i could retrieve the history of a deleted branch using -
SVNLogClient.doLog(SVNURL.parseURIEncoded(path), new String[] { "" }, pegRevision, SVNRevision.create(0),pegRevision, stopOnCopy, discoverChangedPaths, logsLimit, logHandler);
This is similar to the call you are making but you need to supply proper values for pegRevision, startRevision and endRevision. Use of UNDEFINED may not give correct result, instead use the revision at which file was deleted as pegRevision and startRevision as 0 and it should work.
You should specify a revision where the file existed as a peg revision. Obviously it is deletedRevision-1. And maybe (I'm not sure here, just try) the file should exist in both start and end revisions.

Java + regex how to check such a string "LOAD_filesourceB-01012008_000058.dat" for type and number(last 6 digits)

how to implement such a requirement via regexp?
I have a list of filenames as String's.
LOAD_filesourceA-01012008-00001.dat
LOAD_filesourceB-01012008-00001.dat
LOAD_filesourceB-01012008-00003.dat
LOAD_filesourceA-01012008-00004.dat
LOAD_filesourceA-01012008-000055.dat
LOAD_filesourceB-01012008_000055.dat
...
LOAD_filesourceB-01012008_000058.dat
etc
after loading each file, that file gets moved into an archive directory... and I log the file type and load number(last 6 chars in filename)
I have 2 pieces of info:
1- whether the file I wish to load is of type A or B
2- the last loaded file number as integer
based on these, I would like to get the file name of the next file, i.e. that is of the same file type and the load number(= the last 6 digits before . ".dat" section) should be the next available number. say loaded was 12, then I will search for 13, if not available 14, 15 etc.. till I process all files in that directory.
just given a string like "LOAD_filesourceB-01012008_000058.dat" can I check that this is file type B and assuming last loaded file number was 57, it satisfies being number 58 requirement. (> 57 I mean)
LOAD_filesource(A|B)-[0-9]+-([0-9])+.dat
A or B will end up in group 1, the number of the file in group 2. Then parse group 2 as a decimal integer.
See this:
public class Match {
Pattern pattern = Pattern.compile("LOAD_filesource(A|B)-[0-9]{8}[_-]([0-9]{5,6})\\.dat");
String files[] = {
"LOAD_filesourceA-01012008-00001.dat",
"LOAD_filesourceB-01012008-00001.dat",
"LOAD_filesourceB-01012008-00003.dat",
"LOAD_filesourceA-01012008-00004.dat",
"LOAD_filesourceA-01012008-000055.dat",
"LOAD_filesourceB-01012008_000055.dat",
"LOAD_filesourceB-01012008_000058.dat"
};
public static void main(String[] args) {
new Match().run();
}
private void run() {
for (String file : files) {
Matcher matcher = pattern.matcher(file);
System.out.print(String.format("%s %b %s %s\n", file, matcher.matches(), matcher.group(1), matcher.group(2)));
}
}
}
with this output:
LOAD_filesourceA-01012008-00001.dat true A 00001
LOAD_filesourceB-01012008-00001.dat true B 00001
LOAD_filesourceB-01012008-00003.dat true B 00003
LOAD_filesourceA-01012008-00004.dat true A 00004
LOAD_filesourceA-01012008-000055.dat true A 000055
LOAD_filesourceB-01012008_000055.dat true B 000055
LOAD_filesourceB-01012008_000058.dat true B 000058
I don't know if its intentional or not, but you have listed two different formats, one that uses a hyphen as the final separator and one that uses an underscore. If both are really supported, you would want:
LOAD_filesource(A|B)-[0-9]+[_-]([0-9])+.dat
Also, your six digit number is sometimes five digits (e.g. the 00001 in LOAD_filesourceA-...-00001.dat), but the above regular expression only requires at least one digit be present.
Depending on how many files you're going to attempt to examine, you might be better off loading up a directory listing rather than randomly checking to see if a file exists. With an appropriate compare method, sorting your list could give you your files in an easy-to-work-with order.

Categories

Resources