How to get specific line from a txt file in java - java

I'm dumping info about all the processes running on my pc into a .txt file. To do this I execute handle.exe from my java application. The file contains all the running processes in this format:
RuntimeBroker.exe pid: 4756
4: Key HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image
8: Event
10: WaitCompletionPacket
1C: IRTimer
20: WaitCompletionPacket
24: IRTimer
28: File \Device\CNG
--
SearchIndexer.exe pid: 5616
4: Event
8: WaitCompletionPacket
C: IoCompletion
1C: IRTimer
20: File \Device\0000007s
22: Directory
I need to get the name of the process that is using a given device i.e. if I'm looping through the file searching for the string "\Device\0000007s", I need to get the name of the process and the process id which is a few lines above. Does anybody know how could I do this? The processes are delimited by a line of dashes -- in the file. Bear in mind that the file is massive, this is just an example.

I would read each line of a process (using a Scanner) into a List<String>. Then search through the List<String> for your desired String and if it is there, do your processing. Here is some psuedo-code:
Scanner scanner = new Scanner("path/to/file.txt");
List<String> stringList;
while(scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
if(nextLine.equals("--") {
for(String line : stringList) {
if(line.contains("\Device\0000007s") {
// Do your processsing here
}
}
stringList.clear();
}
else {
stringList.add(nextLine);
}
}
This is just psuedo-code, doesn't handle the edge case of the last process and probably won't compile. I will leave the nitty-gritty syntax up to you.
There is probably a more optimal way of doing this, with less looping. But for simple things like this I much prefer a clear approach to an optimized one.

Related

Header modifications do not take effect in fresh build

I am trying to use BRIEF descriptor in OpenCV 3.1 for andoid. In order to achieve that OpenCV has to be built from source with _contrib. So I compiled it without errors and could also see BRIEF.cpp.o beeing built in the command window.
So when I try to use it, my android app crashes throwing
OpenCV Error: Bad argument (Specified descriptor extractor type is not supported.) in static cv::javaDescriptorExtractor* cv::javaDescriptorExtractor::create(int), file /home/maksim/workspace/android-pack/opencv/modules/features2d/misc/java/src/cpp/features2d_manual.hpp, line 374
So I checked features2d_manual.hpp. Line 374 is the default expression of a switch case block:
CV_WRAP static javaDescriptorExtractor* create( int extractorType )
{
//String name;
if (extractorType > OPPONENTEXTRACTOR)
{
//name = "Opponent";
extractorType -= OPPONENTEXTRACTOR;
}
Ptr<DescriptorExtractor> de;
switch(extractorType)
{
//case SIFT:
// name = name + "SIFT";
// break;
//case SURF:
// name = name + "SURF";
// break;
case ORB:
de = ORB::create();
break;
//case BRIEF:
// name = name + "BRIEF";
// break;
case BRISK:
de = BRISK::create();
break;
//case FREAK:
// name = name + "FREAK";
// break;
case AKAZE:
de = AKAZE::create();
break;
default: //**this is line 374**
CV_Error( Error::StsBadArg, "Specified descriptor extractor type is not supported." );
break;
}
return new javaDescriptorExtractor(de);
So the error clearly comes up, because case BRIEF is commented. So I modified it like that:
#include "opencv2/xfeatures2d.hpp"
.
.
.
case BRIEF:
de = xfeatures2d::BriefDescriptorExtractor::create();
break;
.
.
.
default:
CV_Error( Error::StsBadArg, "---TEST--- Specified descriptor extractor type is not supported." );
break;
}
After rebuiling in a fresh directory and using the new build, the exact same error is persistent. Not even "---TEST---" is included with the message.
So I am wondering why my changes do not have any effect.
I am also wondering why the file path is:
/home/maksim/workspace/android-pack/opencv/modules/features2d/misc/java/src/cpp/features2d_manual.hpp
This dirctory doesn't even exist on my system and googling it showed, that /home/maksim/ is part of a lot of different error messages on android.
The actual path before building is:
C:\Users\JJG-CD\Desktop\Build_Workspace\opencv-3.1.0\modules\features2d\misc\java\src\cpp\features2d_manual.hpp
I hope somebody can explain to me what the problem is and eventually give me a hint how to solve it.
The error you're seeing almost certainly comes from a library that you link to that uses the same header file. When you recompile your code having changed the header, that header change only takes effect for the code you're actually compiling, and not the code that is already compiled in the libraries that you're also linking.
Look at your compile line and consider all the -l options as possible suspects.
This also explains the non-existent directory reference: this directory existed and was used at the time the library(ies) themselves were compiled on whatever machine they were compiled on.
If you want your header change to take effect in library code, the library itself needs to be recompiled. Have a look at your project configuration files: you may very well already have make or cmake options to do this.
I gave up already but found the solution by chance. The reason my own built libraries have not been used was the fact that those libraries are usually provided by the opencv manager app. To get rid of OpenCV manager and use my own libraries I just needed to initialize OpenCV statically.
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error}
}
Further details can be found here

Determine where a catch block ends ASM

In ASM, I'm trying to determine the labels for a try-catch block.
Currently I have:
public void printTryCatchLabels(MethodNode method) {
if (method.tryCatchBlocks != null) {
for (int i = 0; i < method.tryCatchBlocks.size(); ++i) {
Label start = method.tryCatchBlocks.get(i).start.getLabel();
Label end = method.tryCatchBlocks.get(i).end.getLabel();
Label catch_start = method.tryCatchBlocks.get(i).handler.getLabel();
System.out.println("try{ " + start.toString());
System.out.println("} " + end.toString());
System.out.println("catch { " + catch_start.toString());
System.out.println("} " /*where does the catch block end?*/);
}
}
}
I'm trying to determine where the label is for the end of the catch block but I don't know how. Why do I need it? Because I want to "remove" try-catch blocks from the byte-code.
For example, I am trying to change:
public void test() {
try {
System.out.println("1");
} catch(Exception e) {
//optionally rethrow e.
}
System.out.println("2");
}
to:
public void test() {
System.out.println("1");
System.out.println("2");
}
So to remove it, I thought that I could just get the labels and remove all instructions between the catch-start and the catch-end and then remove all the labels.
Any ideas?
I recommend reading the JVM Spec §3.12. Throwing and Handling Exceptions. It contains an example that is very simple but still exhibiting the problems with your idea:
Compilation of try-catch constructs is straightforward. For example:
void catchOne() {
try {
tryItOut();
} catch (TestExc e) {
handleExc(e);
}
}
is compiled as:
Method void catchOne()
0 aload_0 // Beginning of try block
1 invokevirtual #6 // Method Example.tryItOut()V
4 return // End of try block; normal return
5 astore_1 // Store thrown value in local var 1
6 aload_0 // Push this
7 aload_1 // Push thrown value
8 invokevirtual #5 // Invoke handler method:
// Example.handleExc(LTestExc;)V
11 return // Return after handling TestExc
Exception table:
From To Target Type
0 4 5 Class TestExc
Here, the catch block ends with a return instruction, thus does not join with the original code flow. This, however, is not a required behavior. Instead, the compiled code could have a branch to the last return instruction in place of the 4 return instruction, i.e.
Method void catchOne()
0: aload_0
1: invokevirtual #6 // Method tryItOut:()V
4: goto 13
7: astore_1
8: aload_0
9: aload_1
10: invokevirtual #5 // Method handleExc:(LTestExc;)V
13: return
Exception table:
From To Target Type
0 4 7 Class TestExc
(e.g. at least one Eclipse version compiled the example exactly this way)
But it could also be vice versa, having a branch to instruction 4 in place of the last return instruction.
Method void catchOne()
0 aload_0
1 invokevirtual #6 // Method Example.tryItOut()V
4 return
5 astore_1
6 aload_0
7 aload_1
8 invokevirtual #5 // Method Example.handleExc(LTestExc;)V
11 goto 4
Exception table:
From To Target Type
0 4 5 Class TestExc
So you already have three possibilities to compile this simple example which doesn’t contain any conditionals. The conditional branches associated with loops or if instructions do not necessarily point to the instruction right after a conditional block of code. If that block of code would be followed by another flow control instruction, the conditional branch (the same applies to switch targets) could short-circuit the branch.
So it’s very hard to determine which code belongs to a catch block. On the byte code level, it doesn’t even have to be a contiguous block but may be interleaved with other code.
And at this time we didn’t even speak about compiling finally and synchronized or the newer try(…) with resources statement. They all end up creating exception handlers that look like catch blocks on the byte code level.
Since branch instructions within the exception handler might target code outside of the handler when recovering from the exception, traversing the code graph of an exception handler doesn’t help here as processing the branch instruction correctly requires the very information about the branch target you actually want to gather.
So the only way to handle this task is to do the opposite. You have to traverse the code graph from the beginning of the method for the non-exceptionally execution and consider every encountered instruction as not belonging to an exception handler. For the simple task of stripping exception handlers this is already sufficient as you simply have to retain all encountered instructions and drop all others.
In short, you will have to do am execution flow analysis. In your example:
public void test() {
try { // (1) try start
System.out.println("1");
} // (2) try end
catch(Exception e) {
//optionally rethrow e. // (3) catch start
} // (4) catch end
System.out.println("2"); // (5) continue execution
}
Graphically it will look like this:
---(1)-+--(2)---------------------+
| +--(5 execution path merged)
+--(3 branched here)--(4)--+
So, you need to build a graph of the code blocks and then remove nodes related to (3) and (4). Currently ASM doesn't provide execution flow analysis tools, though some users reported that they build such tools on top of ASM's tree package.
There are relatively common situations in which the end of the catch block is easy to detect. I'm assuming here that we are using a Java compiler.
when the try block (between the start and end label), ends with a GOTO(joinLabel). If the block does not throw an exception or return always, or break/continue out of a surrounding loop, then it will end with GOTO which points to the end of last handler.
same for catch blocks which are not the last block, they will jump over the handlers to follow using a GOTO which can help you identify the end of the last handler. So if the try block does not have such a GOTO, you might find one in the other handlers.
these non-last catch blocks can be detected by comparing the handler labels of TRYCATCH instructions with the same start and end labels. The start label of the next handler acts as the (exclusive) end of the previous handler.
At the bytecode level, excepting handling is essentially a goto. The code doesn't have to be structured, or even have a well defined catch block at all. And even if you are dealing only with normally compiled Java code, it is still quite complicated once you consider the possibilities of try with resources or complicated control flow structures inside the catch block.
If you just want to remove code associated with the "catch block", I would recommend simply removing the associated exception handler entry and then doing a dead code elimination pass. You can probably find an existing DCE pass somewhere (for example, Soot), or you could write your own.

JavaImp plugin not able to parse Java files

I have been using the JavaImp.vim script for auto importing Java statements in VIM
But trying out different directories in the JavaImpPaths, I am still unable to make JavaImp parse the Java files in the source to make auto imports possible
this is how my .vimrc looks like
let g:JavaImpPaths = "~/Documents/android-sdks/sources/android-21/android/content/"
let g:JavaImpClassList = "~/.vim/JavaImp/JavaImp.txt"
let g:JavaImpJarCache = "~/.vim/JavaImp/cache/"
This is what I get running JIG in new Vim window
:JIG
Do you want to create the directory ~/.vim/JavaImp/cache/?
Searching in path (package): ~/Documents/android-sdks/sources/android-21/android
/content/ ()
Sorting the classes, this may take a while ...
Assuring uniqueness...
Error detected while processing function <SNR>10_JavaImpGenerate:
line 75:
E37: No write since last change (add ! to override)
Done. Found 1 classes (0 unique)
Press ENTER or type command to continue
It might be late, but if anyone else comes along this might help them...
I got it working with the following changes to the script:
line 181 from
close
to
close!
And lines 207/208 from
let l:javaList = glob(a:cpath . "/**/*.java", 1, 1)
let l:clssList = glob(a:cpath . "/**/*.class", 1, 1)
to
let l:javaList = split(glob(a:cpath . "/**/*.java"), "\n")
let l:clssList = split(glob(a:cpath . "/**/*.class"), "\n")

Heredoc for Java from bash command line

As a JAVA teaching assistant, I get stuck with grading a lot of student's labs. A lot of these labs use a Scanner to get input from a user. Instead of repeated bashing numbers into the keyboard, is there a way I can utilize a heredoc to run all of the labs with the same input parameters without changing the student's code? What I have so far (which works for except the heredoc-esque code):
#!/bin/bash
for i in unzip/*; do
echo $i
javac $i/lab0/AddThree.java
cd $i/lab0
java AddThree <<EOF
2
3
4
EOF
cd ../../..
done
The code I'm trying to grade adds three integers that are provided by the user. unzip is the directory where each student has a folder (i.e. file structure is ./unzip/student/lab0/sourcecode.java)
Java gives:
unzip/student
Hello out there
I will add three numbers for you
Enter three whole numbers on a line :
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at AddThree.main(AddThree.java:10)
./lab0test: line 9: 2: command not found
./lab0test: line 10: 3: command not found
./lab0test: line 11: 4: command not found
./lab0test: line 12: EOF: command not found
Your heredoc looks good except it will send the spaces at the start of each line. To get rid of those, you can either use -EOF and start each line of the heredoc with Tab characters, which will get stripped:
cd $i/lab0
java AddThree <<-EOF
TabTab2
TabTab3
TabTab4
TabTabEOF
cd ../../..
Or unindent the heredoc contents. It's ugly, but it'll work.
cd $i/lab0
java AddThree <<EOF
2
3
4
EOF
cd ../../..
Alternatively, if the input is short enough you could do it inline:
java AddThree <<< $'2\n3\n4'
(Using $'...' tells the shell to interpret \n escape sequences.)

Porter2 Stemming Java Implementation Inquiry

I've seen other posts about this but I still couldn't get it to work.
http://snowball.tartarus.org/dist/libstemmer_java.tgz <<- this contains the java implementation of the porter2 algorithm.
What I did was extract the contents on my desktop (for easy access) and opened its .java file using Netbeans IDE. I ran it but it returned an error.
Netbeans doesn't read the other java files. Since all the java files are connected to each other, one error from javaX file produces error on javaY file and so on.
TestApp.java is the one which should be ran. But the following errors occur. See the screenshots.
Here are the screenshots:
http://img248.imageshack.us/img248/290/java1.jpg
http://img4.imageshack.us/img4/5196/java2l.jpg
http://img441.imageshack.us/img441/8625/java3i.jpg
I cannot see your images any longer. The ext folder will not compile because of 3 unreachable statements in frenchStemmer.java. They can easily be removed, or just delete the entire file if you are not using french.
case 13:
// (, line 155
// call RV, line 155
if (!r_RV())
{
return false;
}
// fail, line 155
// (, line 155
// <-, line 155
slice_from("ant");
return false;
break; <<<- remove this
I compiled and ran in the free Community Edition of Intellij, and also using the command line.

Categories

Resources