How to print all method declaration and invocation from ASTParser - java

I want to print all the method invocations within all methods of a Class. I am using ASTParser. Following is my code
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import java .io.*;
public class ASTParserDemo {
public static void main(String[] args) {
ASTParserDemo demo = new ASTParserDemo();
String rawContent = demo.readFile();
//String rawContent = "public class HelloWorld { public String s = \"hello\"; public static void main(String[] args) { HelloWorld hw = new HelloWorld(); String s1 = hw.s; } }";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(rawContent.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
AST ast = cu.getAST();
IdentifierVisitor iv = new IdentifierVisitor();
cu.accept(iv);
}
public String readFile() {
StringBuffer fileContent = new StringBuffer();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\research\\android-projects\\AsyncSearch.java"));
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine);
fileContent.append(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return fileContent.toString();
}
}
import org.eclipse.jdt.core.dom.*;
import java.util.*;
public class IdentifierVisitor extends ASTVisitor {
private Vector<String> identifiers = new Vector<String>();
public Vector<String> getIdentifiers(){
return identifiers;
}
public boolean visit(MethodDeclaration m){
System.out.println("METHOD DECLARATION : " + m);
return true;
}
public boolean visit(MethodInvocation m){
System.out.println("METHOD INVOCATION : " + m);
return true;
}
}
the output is showing only one method declaration. Please let me know how do I print all method invocations within all declared methods. Thanks

You're not using a good method to retrieve the string representation of your source code. You can use an alternative method for read a file from your path and return a string representation of source:
public static String readFileToString(String filePath) throws IOException {
StringBuilder fileData = new StringBuilder(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[10];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
// System.out.println(numRead);
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
Remember to always check whether it is an actual file before calling readFileToString(filePath) eg:
String filePath = file.getAbsolutePath();
if (file.isFile ()))
String source = readFileToString(filePath)
Alternatively you can print the contents of rawContent returned from your method readFile and check that the code you want to parse is actually the same as what you mean.

Related

how to use relative file path to read a file in java?

file path is not working, input1.txt is located in the same directory as library.java.
What should i do to correct it ?
How should i give path so that it read thr text file ?
package SimpleLibrarySystem;
import java.time.LocalDateTime;
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class Library
{
ArrayList <Book> var = new ArrayList<Book>();
HashMap<Book, LocalDateTime> var1 = new HashMap<Book, LocalDateTime>();
public Library(String person, LocalDateTime time)
{
try{
File myfile = new File("input1.txt") ;
Scanner br = new Scanner(myfile);
String line = br.nextLine();
while ((line != null))
{
String a = line;
line = br.nextLine();
String b = line;
Book a1 = new Book(a,b,person);
Book a2 = new Book (a,b, "");
var.add(a2);
var1.put(a1,time);
//System.out.println(a + " "+ b);
line = br.nextLine();
}
br.close();
}
catch (Exception e)
{
System.out.println("not working");
}
}
}
with code:
public class Main{
public static void main(String[] args) {
int counter = 0;
try (FileReader fileReader = new FileReader("src/file.txt"); Scanner sc = new Scanner(fileReader)) {
while (sc.hasNextLine()) {
++counter;
sc.nextLine();
}
} catch (Exception e) {
throw new IllegalStateException(e.getMessage());
}
System.out.println(counter);
}
}
checkout: how to read file in Java

Array returning null .. Generate random word

I am trying to make a class for generating random words. So far my choices are Scanner or a BufferReader I am guessing.
This is the code that I think is most efficient however when I run I get null.
Also will a public return randomWord getter grant access to the word in main class?
private static final String filepath = "/assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words = new ArrayList<String>();
public void WordGenerator() {
rand = new Random();
String line;
try {
InputStream WordsFile = getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
if(!br.ready()){
System.out.println("No File");
}
else while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
}
catch (IOException e) {
System.out.println("Something is wrong");
}
int size = words.size();
Random rn = new Random();
int randWord = rn.nextInt(size);
randomWord = words.get(randWord);
System.out.println(randomWord);
}
}
I think what you really need to read your file is to remove the InputStream line and just replace the BufferedReader with this one:
BufferedReader br = new BufferedReader(new FileReader(filepath));
So your code will look like this:
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
public class WordGeneratorClass
{
private static final String filepath="../assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words=new ArrayList<String>();
public void WordGenerator()
{
rand=new Random();
String line;
try
{
BufferedReader br = new BufferedReader(new FileReader(filepath));
if(!br.ready())
{
System.out.println("No File");
}
else while((line=br.readLine())!=null)
{
words.add(line);
}
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
int size=words.size();
Random rn=new Random();
int randWord=rn.nextInt(size);
randomWord=words.get(randWord);
System.out.println(randomWord);
}
public static void main(String args[])
{
WordGeneratorClass gen = new WordGeneratorClass();
gen.WordGenerator();
}
}
Ensure that your assets/words.txt exist.
Edit
Seems that the problem was also related to the path of your words.txt. The above code assumes that the assets/words/words.txt is in the same directory with the source code. For more information, please have a look here.

How to print tagged values from a file?

I had to write a code to identify the language of tweets and to print out the tweets of a certain language. I have written the language identification part, but cannot get to print only the lines necessary.
Here is the code:
import java.io.*;
import java.util.*;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.functions.SMO;
import weka.classifiers.trees.RandomForest;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
public class Lang_Detect
{
public static weka.classifiers.Classifier c;
public static HashMap<String,String> trigram=new HashMap<String,String>();
public static void initiate() throws Exception
{
c = loadModel("C:\\Users\\DIV\\ff\\Maithili\\nb.model"); // loads nb model
}
public static NaiveBayes loadModel(String path) throws Exception
{
NaiveBayes classifier;
FileInputStream fis = new FileInputStream(path);
ObjectInputStream ois = new ObjectInputStream(fis);
classifier = (NaiveBayes) ois.readObject();
ois.close();
return classifier;
}
public static void read_trigram()
{
try
{
FileInputStream fis = new FileInputStream("C:\\Users\\DIV\\ff\\Maithili\\Trigram.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
String words[]=line.split(":");
trigram.put(words[0].trim(), "");
}
fis.close();
}catch(IOException f){}
}
public static String feature_vector(String line)
{
String vector="";
String words[]=line.split(" ");
HashMap<String,String> local_word=new HashMap<String,String>();
for(int i=0;i<words.length;i++)
{
char ch[]=words[i].toCharArray();
for(int j=0;j<ch.length-2;j++)
{
local_word.put(ch[j]+""+ch[j+1]+""+ch[j+2], "");
}
}
for (Map.Entry<String, String> entry : trigram.entrySet())
{
if(local_word.containsKey(entry.getKey()))
{
vector+="1,";
}
else
{
vector+="0,";
}
}
return vector;
}
public static String lang_tag(String file) throws Exception
{
String tagged_sentence="";
int l=0,cntr=0;;
//String words[]=sentence.toLowerCase().split(" ");
StringBuffer str=new StringBuffer();
read_trigram();
// TODO Auto-generated method stub
int count=1;
str.append("#relation Language\n");
for (Map.Entry<String, String> entry : trigram.entrySet())
{
str.append("#attribute Trigram"+count+" numeric\n");
count++;
}
str.append("#attribute class {HN,NP,MT}\n");
str.append("#DATA\n");
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
String line;
while((line = br.readLine())!=null)
{
str.append(feature_vector(line)+"?\n");
}
fis.close();
}catch(IOException f){}
Global.file_update("C:\\Users\\DIV\\ff\\Maithili\\HN_NP_MT_Unlabelled.arff", str.toString());
Instances unlabeled = new Instances(
new BufferedReader(
new FileReader("HN_NP_MT_Unlabelled.arff")));
// set class attribute
unlabeled.setClassIndex(unlabeled.numAttributes() - 1);
Instances labeled = new Instances(unlabeled);
// label instances
for (int i = 0; i < unlabeled.numInstances(); i++)
{
double clsLabel = c.classifyInstance(unlabeled.instance(i));
String tag="";
if(clsLabel==0.0)
tag="HN";
else if(clsLabel==1.0)
tag="NP";
else if(clsLabel==2.0)
{
tag="MT";
Global.file_append("C:\\Users\\DIV\\ff\\Maithili\\Detected_Maithili_Tweets.txt", tag);
}
System.out.println(tag);
}
return tagged_sentence.trim();
}
public static void main(String[] args) throws Exception
{
initiate();
lang_tag("C:\\Users\\DIV\\ff\\Maithili\\tweets.txt");
}
}
As you can see in the lang_tag(), I want to print the lines which are tagged as MT, But I cannot get the lines in any particular variable.
Can someone help me?

Java I/O writing, mixingcase and getExtension problems

I am changing names of all files in directory and if it's text file I am changing the content but it doesn't seem to work the name of the file is changed right but content is blank/gone heres is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There is several issue with your code:
Your rewrite function is perform on old name File. It should be done on the renamed File:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
you are trying to read docx and pdf file like regular text file. This cannot work. You will have to use external library like POI and pdf Box
Your rewrite function is not safe. You must unsure to close the ressources:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}
You can't re-write a file on top of itself. you need to write the new content to a new file, then rename again.

How to write content on a text file using java?

i am having a program in java.which system.out some strings,i need to save each of them in a text file
it is showing in a format
ruo1 row2 row3
i want it in
row1
row2
row3
how can i do that in java?
import java.util.Arrays;
import java.io.*;
public class BruteForce {
public static FileOutputStream Output;
public static PrintStream file;
public static String line;
public static void main(String[] args) {
String password = "javabeanc";
char[] charset = "abcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 8);
String attempt = bf.toString();
while (true) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
writer.write(attempt+"\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
attempt = bf.toString();
System.out.println("Tried: " + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
public String toString() {
return String.valueOf(cg);
}
}
Very quick code. I apologize if there are compile errors.
import java.io.FileWriter;
import java.io.IOException;
public class TestClass {
public static String newLine = System.getProperty("line.separator");
public static void main(String[] a) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
for(int i=0;i<3;i++){
writer.write(row+i+newLine);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how about adding a new line character "\n" to each row ?
u can use PrintWriter pw;
pw.println(row+i)
in above instead of hard coding newLine
Using JDK 11 one can write:
public void writeToFile() {
String content = "Line 1\nLine 2";
Path path = Paths.get("./resources/sample-new.txt");
Files.writeString(path, content);
}

Categories