Execute parser methods wihout the main method - java

When I try to invoke parserAction() method inside an another servlet class I'm getting a blank array. I cant print the nouns inside my servlet. But inside this class with the MAIN METHOD noun array is printing correctly. What is the reason for this ?
package com.books.servlet;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import com.sun.corba.se.impl.orb.ParserAction;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
public String line = "I need the java book";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
// System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : "+nounPhrases);
}
}
Below is my sample servlet class. It shows me a blank array with []
public class test extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.......
.......
.......
ParserTest pt = new ParserTest();
pt.parserAction();
System.out.println("List of Noun Parse : "+pt.nounPhrases);
System.out.println("List of Noun Parse : "+ParserTest.nounPhrases);
}
}
Here I need to extract nouns without executing a main method. Since I'm developing a web application. I need to show these extracted nouns inside one of my servlet class.

You need to write what you want in the response, for example by doing:
response.getWriter().println("Whatever you want to write in the response");
But first I would suggest to read some good Java books as your code is not very good, also servlets are an old way of doing Java web application, nowadays people use other technologies, like templates using JSP or JSF, JAX-RS for REST applications, JAX-WS for SOAP applications, ...

Related

How can I list all methods of all imported classes in a file using Java?

My objective is to look at some lines of codes of an external file and count the number of functions of a class are called then.
For example, if I have the following code:
import java.io.BufferedReader;
import whatever.MyClass;
import java.util.ArrayList;
...
...
public void example(){
InputStreamReader isr = new InputStreamReader (whatever);
MyClass object = new MyClass();
someArrayList.add(whatever2)
someArrayList.add(whatever3)
}
In this case, BufferedReader and MyClass functions were called once, and ArrayList functions were called twice.
My solution for that is get a list of all methods inside the used classes and try to match with some string of my code.
For classes created in my project, I can do the following:
jar -tf jarPath
which returns me the list of classes inside a JAR . And doing:
javap -cp jarPath className
I can get a list of all methods inside a JAR whit a specific class name. However, what can I do to get a external methods names, like add(...) of an "external" class java.util.ArrayList?
I can't access the .jar file of java.util.ArrayList correct? Anyone have another suggestion to reach the objective?
The compiler doesn't put the imports into the object file. It throws them away. Import is just a shorthand to the compiler.(Imports are a compile-time feature ).
first step :
use Qdox https://github.com/paul-hammant/qdox to get all the imports in a class :
String fileFullPath = "Your\\java\\ file \\full\\path";
JavaDocBuilder builder = new JavaDocBuilder();
builder.addSource(new FileReader( fileFullPath ));
JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();
for ( String imp : imports )
{
System.out.println(imp);
}
second step :
inspire from that code , loop through your imports (String array) and apply the same code and you will get the methods .
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Tes {
public static void main(String[] args) {
Class c;
try {
c = Class.forName("java.util.ArrayList");
Arrays.stream(getAccessibleMethods(c)).
forEach(System.out::println);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
result.add(method);
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
}
Output :
public void java.util.ArrayList.add(int,java.lang.Object)
public boolean java.util.ArrayList.add(java.lang.Object)
public boolean java.util.ArrayList.remove(java.lang.Object)
public java.lang.Object java.util.ArrayList.remove(int)
public java.lang.Object java.util.ArrayList.get(int)
public java.lang.Object java.util.ArrayList.clone()
public int java.util.ArrayList.indexOf(java.lang.Object)
public void java.util.ArrayList.clear()
.
.
.
All the code - one class :
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.JavaSource;
public class Tester {
public static void main(String[] args) {
// put your .java file path
// CyclicB is a class within another project in my pc
String fileFullPath =
"C:\\Users\\OUSSEMA\\Desktop\\dev\\OCP_Preparation\\src\\w\\CyclicB.java";
JavaDocBuilder builder = new JavaDocBuilder();
try {
builder.addSource(new FileReader( fileFullPath ));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JavaSource src = builder.getSources()[0];
String[] imports = src.getImports();
for ( String imp : imports )
{
Class c;
try {
c = Class.forName(imp);
Arrays.stream(getAccessibleMethods(c)).
forEach(System.out::println);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
result.add(method);
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
}
Output all the methods within the classes imported in the file CyclicB.java :
private void java.lang.Throwable.printStackTrace(java.lang.Throwable$PrintStreamOrWriter)
public void java.lang.Throwable.printStackTrace(java.io.PrintStream)
public void java.lang.Throwable.printStackTrace()
public void java.lang.Throwable.printStackTrace(java.io.PrintWriter)
public synchronized java.lang.Throwable java.lang.Throwable.fillInStackTrace()
.
.
.
You may look into OpenJDK project that has a Java compiler. Learn to build the modified versions. Investigate the syntax analysis layer of this compiler and find where the method calls are handled. Put the logging into these locations and now you only need to build your java file with the modified compiler to get the information about the calls.
The build is complex, but you will likely only need a careful editing in a few files. It is not exactly very low hanging fruit but I think it should be possible to discover these files and make changes in them, and still may be a simpler/cleaner approach than to implement the own Java syntax parser (also doable with JavaCC).
If you also need to track calls from the external libraries, build them with the modified compiler as well and you will have the needed records.
GNU Classpath is another open source project where you can do the similar thing, and it may be easier to build. However, unlike OpenJDK, GNU Classpath java system library is not complete.
This approach may not discover some methods called during reflection. But it would discover that reflection framework methods have been called. If it is a security - related project, the simplest would be to agree that reflection is not allowed. It is uncommon to use reflection in a normal Java application that is not a framework.

How do I call actionPerformed method from another class in java

How do I call
actionPerformed(ActionEvent e)
from another method, that is,
returnHolder()
in my case, so that the arraylist can have all the data so then I can use servlet to write the data on the localhost. For now, in my
doGet
method,
System.out.println("size of the list is " + list.size());
gives me zero. Hope someone could help me out. Thank you so much.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Dummy extends JFrame{
public static ArrayList<String> list = new ArrayList<String>();
public static ArrayList<String> holder = new ArrayList<String>();
public static JButton play;
public Dummy() {
Container content = getContentPane();
play = new JButton("fuck");
play.setEnabled(true);
PlayListener playListener = new PlayListener();
play.addActionListener(playListener);
content.add(play, BorderLayout.SOUTH);
}
class PlayListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
list.add("what");
list.add("the");
list.add("hell");
for(int i = 0; i < list.size(); i++){
holder.add(list.get(i));
}
}
}
public static ArrayList<String> returnHolder() {
//play.doClick();
return holder;
}
public static void main(String args[]) {
JFrame frame = new Dummy();
frame.pack();
frame.show();
}
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.tutorials.Dummy;
public class ListJson extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ArrayList<String> list = Dummy.returnHolder();
System.out.println("size of the list is " + list.size());
resp.setContentType("application/json");
PrintWriter writer = resp.getWriter();
for(int i = 0; i < list.size(); i++) {
writer.println(list.get(i));
}
writer.flush();
writer.close();
}
}
After reading Your other question it is more clear what you want to do.
Servlet and your main program live in different JVM and can not talk directly.
To communicate between them you need some kind of remote communication. In this case the simplest method is to use http as you already running http server.
For example, you can add doPost method to your servlet and from your main program post some json data there. There are enough tutorials on sending http from client, e.g. look here
Note that you can not just keep data as a non-static field in servlet instance, because it is not guaranteed that doGet will be invoked on same instance as doPost.
For real-life system you would keep data in a data storage, probably abstracted by a framework or persistence layer. I guess for you it is not the case yet. For study / tutorial purposes, you can keep the data in some static member, so doGet and doPost access the same data instance. You need also guard retrieve/update e.g. with synchronized, because doGet and doPost may come from different threads.
You can look at this question for servlet update from standalone client example.

read only text from url using java

I have been trying to execute this program, but it shows error saying that urlconnectionreader cannot be resolved. I'm new to programming. Can someone help me with this?
This is my code:
import java.net.*;
import java.io.*;
public class ReadTextFromUrl {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
// enter code here
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
There are Many Libraries to read text from URL,
You can Try jsoup library to read or extract only text.
import java.io.IOException;
import org.jsoup.Jsoup;
public class ReadTextFromURL {
public static void main(String[] args) throws IOException {
String text = Jsoup.connect("https://stackoverflow.com/questions/40741265/read-only-text-from-url-using-java").get().text();
System.out.println(text);
}
}
In your case the class name should be URLConnectionReader or you can change the the calling function via your class name .
String content = ReadTextFromUrl.getText(args[0]);
what you need to study more is objects.you must know that the classes are the blueprints.you cant use a saw blueprint to saw a tree.you need the saw itself.and by creating a object from that class you will have the saw.so when you have the saw in your hands you can saw the tree.making an object from a class works exactly the same.and using the ways(methods) to saw the tree with the actual saw is like using the methods of the class.
lets think you have a class named Saw and it has a method named sawTheTree.
public class Saw {
public void sawTheTree {
// do the sawing
}
}
its the blueprint by now.to use this saw and the method you need this :
Saw saw = new Saw();
now you have the saw in your hands.lets go and saw the tree.for this you need this code in your main method or where ever you feel the need of sawing the tree.
saw.sawTheTree();
now the the saw will saw the tree for you.
P.S: in your code you have declared the getText method static so you don't need the object creation part.if you are asking why look again at static statement description.but to use a non static method from a class you need to create the object.

"Attributes and objects cannot be resolved" - error

The following code is for reading or writing files with java, but:
Eclipse prints these errors:
buffer_1 cannot be resolved to a variable
file_reader cannot be resolved
also other attributes...
what is wrong in this code here:
//Class File_RW
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class File_RW {
public File_RW() throws FileNotFoundException, NullPointerException {
File file_to_read = new File("C:/myfiletoread.txt");
FileReader file_reader = new FileReader(file_to_read);
int nr_letters = (int)file_to_read.length()/Character.BYTES;
char buffer_1[] = new char[nr_letters];
}
public void read() {
file_reader.read(buffer_1, 0, nr_letters);
}
public void print() {
System.out.println(buffer_1);
}
public void close() {
file_reader.close();
}
public File get_file_to_read() {
return file_to_read;
}
public int get_nr_letters() {
return nr_letters;
}
public char[] get_buffer_1() {
return buffer_1;
}
//...
}
//main method # class Start:
package R_2;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.lang.NullPointerException;
public class Start {
public static void main(String[] args) {
File_RW file = null;
try {
file = new File_RW();
} catch (NullPointerException e_1) {
System.out.println("File not found.");
}
//...
}
}
I can't find any mistake. I have also tried to include a try catch statement into the constructor of the class "File_RW", but the error messages were the same.
Yes, there are errors in your code - which are of really basic nature: you are declaring variables instead of fields.
Meaning: you have them in the constructor, but they need to go one layer up! When you declare an entity within a constructor or method, then it is a variable that only exists within that constructor/method.
If you want that multiple methods can make use of that entity, it needs to be a field, declared in the scope of the enclosing class, like:
class FileRW {
private File fileToRead = new File...
...
and then you can use your fields within all your methods! Please note: you can do the actual setup within your constructor:
class FileRW {
private File fileToRead;
public FileRW() {
fileToRead = ..
but you don't have to.
Finally: please read about java language conventions. You avoid using "_" within names (just for SOME_CONSTANT)!
javacode already running...thx
same program edited with c++ in visual Studio express...
visit the stackoverflow entry link:
c++ file read write-error: Microsoft Visual C++ Runtime libr..debug Assertion failed, expr. stream.valid()

Getting error: Route() in Route cannot be applied to String

I'm designing a Java based MongoDB app and I've ran into a snag when working with Spark.
package com.tengen;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
public class HelloWorldSparkStyle {
public static void main(String[] args) {
Spark.get(new Route("/") {
#Override
public Object handle(Request request, Response response) {
return "Hello World From Spark";
}
});
}
}
On new Route("/") I get the error Route() in route cannot be applied to java.lang.string.
I'm confused as to why this doesn't work as I've followed their code exactly.
This should probably be posted on the MongoDB class forum, but I ran into a similar issue. Looks like the get method changed from when the course material was produced. The get now requires a path and a Route
get(path, Route)
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Spark;
public class HelloWorldSparkStyle {
public static void main(String[] args){
Spark.get("/", new Route() {
public Object handle(final Request request, final Response response){
return "Hello World from Spark";
}
});
}
}
Actually I used spark-core-1.1.1.jar it worked fine for me, may be the newer versions of Spark(version 2.0.0) support some different syntax.So if you are using the latest version then you can follow the example given by Mike or just add spark-core-1.1.1.jar to your classpath your example will work fine
That would work in Spark 1. In Spark 2 is recommended by Spark the following (source: http://sparkjava.com/news.html):
import static spark.Spark.*;
public class HelloWorld {
public static void main(String[] args) {
get("/", (req, res) -> "Hello World From Spark");
}
}
Currently, Implementation of Spark Java framework needs to use directory out of Route. So you have to correct your code as follow:
public static void main(String[] args) {
spark.Spark.port(PortNumber);
Spark.get("/", new Route() {
public Object handle(Request request, Response response) throws Exception {
return "This is a sample page";
}
});
}
actually, "/" is the resource to your program. And if you want to change the default spark.Spark.port(PortNumber).
Change the version of Spark in the POM file from the exercise files you download from handout. That fixed issue for me.

Categories

Resources