How do I call actionPerformed method from another class in java - 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.

Related

Execute parser methods wihout the main method

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, ...

java value recieved from client-server program used in another program

My project looks like: I have a bike speedometer attached to simple bike and connected to Raspberry Pi, which is connected over ethernet cable to laptop.
What I want to do is: Raspberry measure the speed of bike wheel and send this value over ethernet cable to laptop. Laptop now uses recieved value and speed up a video, which is played in VLC.
I have working java program on RPi to measure speed of a wheel, I have a working client (on laptop)-server (on RPi) java program to send values from RPi to laptop, and I have a working java program to control speed of video playing in VLC on laptop.
But my problem is, that I don't know how to use values, recieved from RPi over client-server program, in my program, which control speed of video, playing in VLC.
Down are my codes for client and to control speed of video.
Client code:
package player;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class client {
public static int inputPlayer = 0;
public static void main(String[] args) throws UnknownHostException, IOException {
String accept;
int input;
DataInputStream inC = null;
Scanner sc1 = null;
Socket s = null;
try {
s = new Socket ("169.254.218.194", 1342);
Scanner sc = new Scanner (System.in);
System.out.println("Accept connection!");
accept = sc.next();
PrintStream p = new PrintStream (s.getOutputStream());
p.println(accept);
//inC = new DataInputStream(s.getInputStream());
}
catch (Exception e) {
e.printStackTrace();
}
while (true) {
sc1 = new Scanner (s.getInputStream());
input = sc1.nextInt();
if (input > 0) {
inputPlayer = input;
}
System.out.println("I" + input);
//System.out.println("IP" + inputPlayer);
}
}
public int getInputPlayer () {
return this.inputPlayer;
}
}
Player code:
package player;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.discovery.NativeDiscovery;
public class Player {
private final JFrame frame;
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public static void main(final String[] args) {
new NativeDiscovery().discover();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Player(args);
}
});
}
public Player(String[] args) {
frame = new JFrame("My First Media Player");
frame.setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
mediaPlayerComponent.release();
System.exit(0);
}
});
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
contentPane.add(mediaPlayerComponent, BorderLayout.CENTER);
Scanner in = new Scanner (System.in);
frame.setContentPane(contentPane);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("file:URL");
mediaPlayerComponent.getMediaPlayer().skip(1000);
client c = new client();
float i = c.getInputPlayer();
while (true) {
//float i = in.nextFloat();
//System.out.println(i);
mediaPlayerComponent.getMediaPlayer().setRate(i);
}
}
}
Everything I want to do is to use variable inputPlayer from client class as variable i in Player class.
As I have done, Eclipse return me error: "[000000001ade9eb0] core input error: input control fifo overflow, trashing type=2"
Thanks for your help.
Jan
There are several problems here:
the code in the client class (btw, class names should begin with uppercase) is never run. You've put all the code in that class in a main method, which only gets executed if you run the application by choosing that class. Essentially, you have two separate applications here. Even if you were to run them at the same time, it wouldn't help you since one would not have direct access to instances of classes in the other.
i is set only once and never updated inside the loop
you could turn that main method of the client class into an ordinary method, but even then you can't have two while(true) loops run at the same time if they are on the same thread.
If handling thread is a bit much for you at this stage, you could try simply combining both classes in one. One loop would scan for incoming data and set the players speed as it came. This might or might not work, depending on how the player itself is implemented, but you could give it a try.

Polarion WorkItem class getter methods returning null

I am attempting to write a Java program that gets work record information off of Polarion and writes it to a DAT file for later use.
I have successfully connected to our servers and have retrieved the WorkItem objects, but none of the getter methods (besides getUri()) seem to work, which poses a problem since I need to use the WorkItem class's getWorkRecords() method to satisfy the requirements of the project.
I have tried all of the getter methods for the class on both our main Polarion server and our 'staging' server, which we use as a kind of testing area for things such as the program I am trying to write and on which I have full permissions.
Regardless of permissions, I am only querying for some dummy workitems I created and assigned to myself, so there shouldn't be any permissions issues since I am only attempting to view my own workitems.
Here is the code for the program:
package test;
//stg= 10.4.1.50
//main= 10.4.1.10
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.xml.rpc.ServiceException;
import com.polarion.alm.ws.client.WebServiceFactory;
import com.polarion.alm.ws.client.session.SessionWebService;
import com.polarion.alm.ws.client.tracker.TrackerWebService;
import com.polarion.alm.ws.client.types.tracker.WorkItem;
import com.polarion.alm.ws.client.types.tracker.WorkRecord;
public class WorkrecordImporter {
private WebServiceFactory factory;
private TrackerWebService trackerService;
private SessionWebService sessionService;
private WorkItem[] workItems;
private ArrayList<WorkRecord> workRecords;
private String password = //insertpasswordhere;//no peaking
public WorkrecordImporter()throws ServiceException, IOException, ClassNotFoundException{
initializeFields();//initializes all of the Web Services and arrays
//step one
getWorkItems();
//readDATFile();
//step two
getWorkRecords();
//$$$
printWorkRecords();
//$$$$$
writeDATFile();
}
//you know what this does.
public void printWorkRecords(){
for(int temp = 0; temp < workItems.length; temp++){
System.out.println(workItems[temp].getUri().toString());
}
}
public void writeDATFile() throws IOException{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\sweidenkopf\\workspace\\test\\filename.dat"));
try {
out.writeObject(workRecords);
} finally {
// Make sure to close the file when done
out.close();
}
}
/**
* This method sets up the WebServiceFactory at the specified URL. It then initializes the web services, logs in the
* session service, and initializes the arrays.
* #throws MalformedURLException
* #throws ServiceException
* #throws RemoteException
*/
public void initializeFields() throws MalformedURLException, ServiceException, RemoteException{
factory = new WebServiceFactory("//insert url here");
trackerService = factory.getTrackerService();
sessionService = factory.getSessionService();
sessionService.logIn("sweidenkopf", password);
workRecords = new ArrayList<>();
}
public void getWorkItems()throws MalformedURLException, ServiceException, RemoteException{
sessionService.beginTransaction();
workItems = trackerService.queryWorkItems("workRecords.user.id:sweidenkopf", null, null);
sessionService.endTransaction(false);
}
public void getWorkRecords()throws MalformedURLException, ServiceException, RemoteException{
sessionService.beginTransaction();
for(int k = 0; k < workItems.length; k++)
{System.out.println("This is working");
try{//not every work item has work records
System.out.println(workItems[k].getWorkRecords());
WorkRecord[] temp;
temp = workItems[k].getWorkRecords();
for(int x = 0; x < temp.length; x++){
System.out.println("This is working fine");
workRecords.add(temp[x]);
}
}catch(NullPointerException e){
System.out.println("I must regretfully inform you that I have grave news; your endeavors have not been successfull.");
continue;
}
}
System.out.println(workRecords.toString());
sessionService.endTransaction(false);
}
public void readDATFile() throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:\\Users\\sweidenkopf\\workspace\\test\\filename.dat"));
try{
Object temp = in.readObject();
workRecords = (ArrayList) temp;
}
finally{
in.close();
}
}
}
The most important part is of course the getWorkRecords() method within my code. As you can see, it contains the statement System.out.println(workItems[k].getWorkRecords()); that I am using for debugging purposes. This statement returns null, and the only WorkItem method that does not return null when substituted in that statement is getUri(). Also, the try-catch block in that method always catches a NullPointerException because of the for loop contains temp.length, temp being a variable that should contain the return of the getWorkRecords() method.
To summarize the main issue here is that I am unable to return anything from getWorkRecords() or any other getter methods from the WorkItem class. This is puzzling because the getUri() method is executing successfully, as the printWorkRecords() method from my code successfully prints the URIs of all of the WorkItem objects erturn from my query.
Are there any Polarion experts that have encountered this issue before? Does anyone know what I am doing wrong? I am inclined to think it is a bug based on the circumstances.
If you look at my calling of the queryWorkItems() method, you will notice that after the query parameter I specify two null parameters. The first specifies how you want the returned work items sorted (which is inconsequential at the moment), but the second is a String array called fields that is used to specify which of the WorkItem fields you want returned along with the WorkItems themselves. Apparently, if you set that to null like I did, it defaults to only returning the URI. For other things, like author, workrecord, and type, you have to place them in the String array and and pass that array when you call the method.

405 http method get is not supported by this url

I have written a servlet for approval of leaves. In this servlet I have also written code to send a mail. Due to this, it shows HTTP 405 error. If I remove the code which sends a mail, then it does not show the error, but I need the mail code.
package mis;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.jdo.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class approve extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
try{
HttpSession session = req.getSession(true);
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery(Leave_bal.class);
query1.setFilter("emp_Id == emp");
query1.declareParameters("String emp");
List<Leave_bal> results1 = (List<Leave_bal>)query1.execute(session.getAttribute("emp_Id").toString());
String plan="";
String unplan="";
String planleave_result="" ;
String unplanleave_result="";
for (Leave_bal e : results1)
{
plan=e.getplan_leave();
resp.getWriter().println("Planned_Leave"+plan);
unplan=e.getunplan_leave();
resp.getWriter().println("Unplanned:"+unplan);
}
int plan_leave=Integer.parseInt(plan);
int unplan_leave=Integer.parseInt(unplan);
String ID=req.getParameter("id");
resp.getWriter().println(ID);
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Leave_detail.class);
query.setFilter("id == ID");
query.declareParameters("String ID");
List<Leave_detail> results = (List<Leave_detail>)query.execute(ID);
String plan_detail="";
String duration="";
for (Leave_detail e : results)
{
plan_detail=e.getLeave_Type();
duration=e.getdurtn();
//f=e.getfrom();
//t=e.getto();
}
resp.getWriter().println("duration "+duration);
resp.getWriter().println("Planned_selected "+plan_detail);
int duration_integer=Integer.parseInt(duration);
resp.getWriter().println("duration "+duration_integer);
//String duration=req.getParameter("date");
// resp.getWriter().println("diffrence:"+duration);
//int workingdays=Integer.parseInt(duration);
//String Leave = req.getParameter("a");
// resp.getWriter().println("planned:"+Leave);
if(plan_detail.equals("UNPLAN"))
{
unplan_leave=unplan_leave-duration_integer;
unplanleave_result=String.valueOf(unplan_leave);
planleave_result=plan;
resp.getWriter().println("Planned After Change"+unplanleave_result);
//st="Applied";
}
if(plan_detail.equals("PLAN"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("LWP"))
{
plan_leave= plan_leave-duration_integer;
planleave_result=String.valueOf(plan_leave);
resp.getWriter().println("Planned After Change"+planleave_result);
unplanleave_result=unplan;
}
if(plan_detail.equals("Onduty"))
{
planleave_result=plan;
unplanleave_result=unplan;
}
Leave_detail status_update = pm.getObjectById(Leave_detail.class,ID);
status_update.setstatus("Approved");
pm.makePersistent(status_update);
Leave_bal ed1=new Leave_bal(session.getAttribute("emp_Id").toString(),planleave_result,unplanleave_result);
pm.makePersistent(ed1);
//code for mail
RequestDispatcher dispatcher = getServletConfig ( ) .getServletContext ().getRequestDispatcher("/MailServiceapply");
dispatcher.forward (req, resp) ;
pm.close();
}
catch(Exception a )
{
resp.getWriter().println(a .getMessage());
} finally{
}
resp.sendRedirect("hr.jsp#LMS");
}
}
This thread on Java Forums provides some hints for this error, like
HTML form invokes POST operation and servlet doesn't implement doPost (direct link)
Inital HTML form not declared in web.xml file (or misspelled) (direct link)
At the bottom of this servlet you're forwarding the request to another servlet:
RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/MailServiceapply");
dispatcher.forward(req, resp);
This is not only a poor approach, certainly because you've written data to the HTTP response before in the servlet and you thus risk IllegalStateException (writing to the response should take place in a JSP), but doing so also requires that the servlet in question also implements doGet(). The error which you're facing suggests that this mail service servlet has only the doPost() implemented.
You need to add a doGet() method to the mail service servlet and use RequestDispatcher#include() to invoke it.
dispatcher.include(req, resp);
Needless to say that this is still a poor approach. You'd rather like to refactor the mail code logic into a standalone Java class which you then import and invoke in both servlets and put all the presentation logic in a JSP.

HTTP Request Object

Is there an object within the standard Java SE that can accept a HTTP request from a socket? I have found how to create and send one, however I have not found a way to retrieve a HTTP object from a socket. I can create one my self, but I would rather rely on a heavily tested object.
This seems like something that would be readily available given the structure of JSP.
There is a small HTTP server in the Java 6 SDK (not sure if it will be in the JRE or in non-Sun JVM's).
From http://www.java2s.com/Code/Java/JDK-6/LightweightHTTPServer.htm :
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpServerDemo {
public static void main(String[] args) throws IOException {
InetSocketAddress addr = new InetSocketAddress(8080);
HttpServer server = HttpServer.create(addr, 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );
}
}
class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
Headers requestHeaders = exchange.getRequestHeaders();
Set<String> keySet = requestHeaders.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
List values = requestHeaders.get(key);
String s = key + " = " + values.toString() + "\n";
responseBody.write(s.getBytes());
}
responseBody.close();
}
}
}
Yeah, you make a new HTTP Request object from what you accept on the socket. What you do after that is up to you, but it should probably involve an HTTP Response.
import java.io.*;
import java.net.*;
import java.util.*;
public final class WebServer {
public static void main(String args[]) throws Exception {
int PORT = 8080;
ServerSocket listenSocket = new ServerSocket(PORT);
while(true) {
HttpRequest request = new HttpRequest(listenSocket.accept());
Thread thread = new Thread(request);
thread.start();
}
}
}
From: http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=396
There's some more work to be done in the tutorial, but it does look nice.
It looks like you are looking for a Servlet. A servlet is an API that lets you receive and respond to an HTTP request.
Your servlet gets deployed in a container, which is basically the actual Web server that will take care of all the protocol complexities. (The most populare are Tomcat and Jetty)

Categories

Resources