Error in starting openday light netconf testtool simulator - java

While starting open daylight netconf test tool simulator I am getting the following error:
"java -jar netconf-testtool-1.5.0-SNAPSHOT-executable.jar --device-count 2 --schemas-dir yangs/"
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1283)
at java.util.regex.Matcher.reset(Matcher.java:309)
at java.util.regex.Matcher.<init>(Matcher.java:229)
at java.util.regex.Pattern.matcher(Pattern.java:1093)
at org.opendaylight.netconf.test.tool.TesttoolParameters.validate(TesttoolParameters.java:316)
at org.opendaylight.netconf.test.tool.Main.main(Main.java:58)
I can able to start it with some other yang files, but not with this specific yang files. What may be the issue causing this?

Take a look at the source code:
final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName());
if (!matcher.matches()) {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line = reader.readLine();
while (!DATE_PATTERN.matcher(line).find()) { <--- Line 316
line = reader.readLine();
}
...
}
}
It's trying to ensure the yang file has a revision date. If it's not in the yang file name, then it opens the file and searches for a revision date. It blows up b/c it reaches the EOF without finding it. That's my take from reading the source - assuming I'm correct then either rename the offending file with a valid revision or add a revision statement to the yang.

Related

How can I get all errors when executing a command?

I'm developing a java program, at a certain point in the program I need to execute some commands and show all the errors returned by that command. But I can only show the first one.
This is my code:
String[] comando = {mql,"-c",cmd};
File errorsFile = new File("C:\\Users\\Administrator2\\Desktop\\errors.txt");
ProcessBuilder pb = new ProcessBuilder(comando);
pb.redirectError(errorsFile);
Process p = pb.start();
p.waitFor();
String r = errorsFile.getAbsolutePath();
Path ruta = Paths.get(r);
Charset charset = Charset.forName("ISO-8859-1");
List<String> fileContents = Files.readAllLines(ruta,charset);
if (fileContents.size()>0){
int cont = 1;
for(String str : fileContents){
System.out.println("Error"+cont);
System.out.println("\t"+str);
cont++;
}
}
else{
//other code
}
In this case I know that there are more than one errors, so I expect more than one output but as you can see in the photo I get only one.
I think the key here might be that ProcessBuilder's redirectError(File file) is actually redirectError (Redirect.to(file)) .
From Oracle's documentation of ProcessBuilder class:
This is a convenience method. An invocation of the form redirectError(file) behaves in exactly the same way as the invocation redirectError (Redirect.to(file)).
Most example's I have seen use Redirect.appendTo(File file) rather than Redirect.to(file). The documentation may explain why.
From Oracle's documentation of ProcessBuilder.Redirect :
public static ProcessBuilder.Redirect to(File file)
Returns a redirect to write to the specified file. If the specified file exists when the subprocess is started, its previous contents will be discarded.
public static ProcessBuilder.Redirect appendTo(File file)
Returns a redirect to append to the specified file. Each write operation first advances the position to the end of the file and then writes the requested data.
I would try replacing
pb.redirectError(errorsFile)
with
pb.redirectError(Redirect.appendTo(errorsFile))
and see if you get more lines that way.
Have you debugged and checked the contents of fileContents?
EDIT: Sorry, it should be a comment, but can't do it yet :(

Java ProcessBuilder and VBS script issue

Am going round in circles here trying to execute a bit of VBScript from java using processbuilder. I'm running my java code as part of a tomcat servlet. If I run the same command from a command line - its running fine. Have tried opening permissions right up (everyone=full perms)
Java Code (excerpt):
ProcessBuilder pb = new ProcessBuilder("cscript", "C:\\Users\\Public\\Documents\\office2pdf.vbs", "C:\\Users\\Public\\Documents\\temp\\22.doc");
Process pr = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
String line = null;
StringBuilder sb = new StringBuilder("");
while ( (line = reader.readLine()) != null) {
sb.append(line);
}
int i = pr.waitFor() ;
getServletContext().log("pb response="+i+", er="+sb.toString());
VBScript (excerpt):
Sub SaveWordAsPDF(p_strFilePath)
'Save Word file as a PDF
'Initialise
Dim objWord, objDocument
Set objWord = CreateObject("Word.Application")
Wscript.Echo p_strFilePath
'Open the file
Set objDocument = objWord.Documents.Open(p_strFilePath)
'Save the PDF
objDocument.SaveAs PathOfPDF(p_strFilePath), WORD_PDF
'Close the file and exit the application
objDocument.Close FALSE
objWord.Quit
End Sub
I've traced it as far to see that the vbscript is infact loading; the line 'Wscript.Echo p_strFilePath' does in fact actually print the correct path to the word doc. According to the error stream returned from java the offending line from vbscript is: 'Set objDocument = objWord.Documents.Open(p_strFilePath)' for which its saying:
Microsoft VBScript runtime error: Object required: 'objWord.Documents.Open(...)'
not sure if this is only triggered from incomplete path; looked at lots of posts - haven't been able to find any that exactly match my situation. Any advice is greatly appreciated!

Null Pointer Error: Can't Find Declaration Cause

In Console:
Exception in thread "main" java.lang.NullPointerException
at SimulatedReality.main(SimulatedReality.java:25)
Line 25 is "BecomesArray = ReadsLine.toCharArray();".
In my code, I am attempting to read off of a file and check all of its characters (or at least for first ten) to see if any are of the value one. I am trying to do this to reset the text of the document after being used once. The problem with the code is that there is a null-pointer error, caused by declaration problems (or, at least, that is what I heard). I couldn't find where this error was. Please and thank you for whoever helps me. I am a beginner, so explanation will be best if overly simplified.
File SRFile = new File("C:/Users/ThinkingBeing/Documents/SRFile.txt");
SRFileWriter = new
FileWriter("C:/Users/ThinkingBeing/Documents/SRFile.txt");
if(!SRFile.exists()){
SRFile.createNewFile();
SRFileWriter.write("000000");
System.out.println("File now exists.");
} else {
for(int i=0;i<=5;i++){
SRFileReader = new BufferedReader(new FileReader(SRFile));
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
BasicChar = BecomesArray[i];
if(BasicChar!='0'){
SRFileWriter.write("000000");
System.out.println("File Off Of Counter. Counter Fixed.");
}
}
SRFileWriter.close();
SRFileReader.close();
}
I think I found your issue (and please follow Java naming conventions).
SRFileReader = new BufferedReader(new FileReader(SRFile)); // <-- file reader once
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
FileWriter SRFileWriter = new FileWriter
("C:/Users/ThinkingBeing/Documents/SRFile.OUT.txt"); // <-- Don't write to
// your input file while you're reading it.
for(int i=0;i<(BecomesArray != null) ? BecomesArray.length : 0;i++){
// SRFileReader = new BufferedReader(new FileReader(SRFile));
BasicChar = BecomesArray[i];
if(!SRFile.exists()||BasicChar=='1'){
// SRFile.createNewFile(); // <-- Would clear your input file.
SRFileWriter.write("00BOOYTA"); // <-- which was also your output file.
}
}
SRFileWriter.close();
SRFileReader.close();
Several possible problems...
It's possible your file has less than 10 lines.
Then readLine will return null and the next line will fail. Documentation here
ReadsLine = SRFileReader.readLine();
BecomesArray = ReadsLine.toCharArray();
Also you should probably make sure your file exists before you start reading from it.
if(!SRFile.exists()||BasicChar=='1'){
And lastly, I can't quite make out what you're trying to achieve just by reading your code. But there's definitely something off with the logic. I find it odd that BasicChar is the i-th character of the i-th line for each line.

How to append existing line in text file

How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite

read a small file contail a Long number in one goal and get ride of the carriage return \n

I have a small file test.txt contains a Long number inside while another piece of java code to read the Long constantly from the file.
Here is the steps:
Run
echo "123" > test.txt
then if you go to the test.txt file, vim test.txt -> :set list, you will see the file looks like:
123$
I have a piece of java code does the following:
byte[] testBytes = File.readAllBytes(test.txt);
String testString = new String(testBytes); // in debug mode, testString looks like "123\n"
long bytesEverRead = Long.parseLong(testString); // this line throws exception because parseLong("123\n") won't work
As you can see above, "123\n" is being read from the file which cause my parseLong failed. How can I read 123 out from test.txt without having \n with it. What's the best way to handle this?
You could use java.util.Scanner (introduced in Java 5).
There are several examples on the Javadoc page, but in your case it would be as easy as:
Scanner sc = new Scanner(new File("test.txt"));
long bytesEverRead = sc.nextLong();
You could use
String testString = new String(testBytes).trim();
long bytesEverRead = Long.parseLong(testString);

Categories