Static variable not getting update in Apache tomcat servlet instantiation - java

I am a tomcat/servlet newbie and have been stuck on this for the last 3/4 days. Any help is appreciated!
I have a servlet class that has a static variable name_print. The static function appInput takes in a string and sets name_print to that string. The code for this class, appmonitor.java, is below:
package AppMonitor_pack;
import statments...
private static String name_print;
public app_monitor() {
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args) {
// TOsDO Auto-generated method stub
}
public static void appInput (String name){
name_print = name;
System.out.println("From appInput " + name_print);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.println("<body> "+ name_print +" </body>");
}
}
I have included this simple project in another project called Sockets. In that, I have a Listening socket that recieves a string called name. I call the static function appInput of the first project and pass in the recieved string name to it, so that it sets name_print to this new value.
The relevant line in Socket.java for this is:
app_monitor.appInput(name);
WHen I compile and run this, I see that the value name is set to some input value "abc". Then the debugger goes into the appInput function of the other project, and sets the value of name_print to "abc" too.
But when I refresh the webpage where the tomcat server is running, it never shows the newly set value of name_print, but continues to show the old value "null" that was set when the appMonitor servlet class loads for the first time.
I have tried to figure out the problem to no avail for 4 days. Any ideas/help?
Thanks!

WHen I compile and run this, I see that the value name is set to some input value "abc". Then the debugger goes into the appInput function of the other project, and sets the value of name_print to "abc" too.
It sounds like you're running this separately from Tomcat. That means you've not just got two different classloaders - you've got two entirely separate JVMs which just happen to run on the same computer. The static variable isn't going to be shared between those processes.
It's not really clear what you're trying to achieve, but if you want information from one process to be available in a separate process, you'll need to use some cross-process communication, or share something more global than just a static variable - e.g. writing the data to a file within one process, then reading it from a file in the other process.

Related

Java Storing sequence of functions run

i have a program in java and what i want to do is somehow store all the functions that have been run whilst the program ran. but i can not seem to find anything on this matter. Also then have to find out which of the function has been ran the most amount out time.
my thought was that i could make an array, assign each function to have a variable with a name of the function and then everytime it is run return that char into the array, and print out the array at the end. But i dont know how to go about storing them in different arr[i] i's everytime same function is ran, also im not sure how i would then find the one that was ran most, any help is much appreciated.
What I'd recommend is creating a boolean for each method, and at the beginning of the method, set the boolean to true. Then create a save method using the java.io class and save the boolean name and value to the file.
EDIT
I just realized i put boolean instead of integer. Have an integer for each method and do integer++ for each method run.
AOP is great for something like this.
See https://dzone.com/articles/monitoring-performance-spring for an example that uses the Spring AOP library.
i tried a program that may help you or not. i created a Interceptor class which will print out the details you may need. You didnot mention about any frameworks, so i just gave you an example program with plain old java.
This approach also offers flexibility to print all the details at the end of program execution.
public class Test {
public void demoMethod() throws InterruptedException{
Intercept.printMethodStartTime(System.currentTimeMillis());
Intercept.printMethodName(Thread.currentThread().getStackTrace()[1].getMethodName());
Thread.sleep(5000);
Intercept.printMethodEndTime(System.currentTimeMillis());
}
public static void main(String[] args) throws InterruptedException {
new Test().demoMethod();
}
}
class Intercept{
private static Long startTime;
private static Long endTime;
public static void printMethodName(String methodName){
System.out.println("Current method name: "+methodName);
}
public static void printMethodStartTime(Long time){
startTime = time;
System.out.println("Method started at "+startTime);
}
public static void printMethodEndTime(Long time){
endTime = time;
System.out.println("Method ended at "+endTime);
printMethodRunTime();
}
public static void printMethodRunTime(){
System.out.println("Method ran for "+((endTime-startTime)/1000)+" seconds");
}
}

Get methods using Java Reflection Class

Hi guys im new to all this test automation stuff and trying to learn following a tutorial but im stuck trying to run this code.
I get an exception
Exception in thread "main" java.lang.NullPointerException
at executionEngine.DriverScript.execute_Actions(DriverScript.java:45)
at executionEngine.DriverScript.main(DriverScript.java:39)
dunno whats wrong as im following a tutorial so i assume everything should be working.
package executionEngine;
import java.lang.reflect.Method;
import config.ActionKeywords;
import utility.ExcelUtils;
public class DriverScript {
//This is a class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static ActionKeywords actionKeywords;
public static String sActionKeyword;
//This is reflection class object, declared as 'public static'
//So that it can be used outside the scope of main[] method
public static Method method[];
//Here we are instantiating a new object of class 'ActionKeywords'
public DriverScript() throws NoSuchMethodException, SecurityException{
actionKeywords = new ActionKeywords();
//This will load all the methods of the class 'ActionKeywords' in it.
//It will be like array of method, use the break point here and do the watch
method = actionKeywords.getClass().getMethods();
}
public static void main(String[] args) throws Exception {
//Declaring the path of the Excel file with the name of the Excel file
String sPath = "D://Tools QA Projects//trunk//Hybrid Keyword Driven//src//dataEngine//DataEngine.xlsx";
//Here we are passing the Excel path and SheetName to connect with the Excel file
//This method was created in the last chapter of 'Set up Data Engine'
ExcelUtils.setExcelFile(sPath, "Test Steps");
//Hard coded values are used for Excel row & columns for now
//In later chapters we will use these hard coded value much efficiently
//This is the loop for reading the values of the column 3 (Action Keyword) row by row
//It means this loop will execute all the steps mentioned for the test case in Test Steps sheet
for (int iRow = 1;iRow <= 9;iRow++){
//This to get the value of column Action Keyword from the excel
sActionKeyword = ExcelUtils.getCellData(iRow, 3);
//A new separate method is created with the name 'execute_Actions'
//You will find this method below of the this test
//So this statement is doing nothing but calling that piece of code to execute
execute_Actions();
}
}
//This method contains the code to perform some action
//As it is completely different set of logic, which revolves around the action only,
//It makes sense to keep it separate from the main driver script
//This is to execute test step (Action)
private static void execute_Actions() throws Exception {
//This is a loop which will run for the number of actions in the Action Keyword class
//method variable contain all the method and method.length returns the total number of methods
for(int i = 0;i < method.length;i++){
//This is now comparing the method name with the ActionKeyword value got from excel
if(method[i].getName().equals(sActionKeyword)){
//In case of match found, it will execute the matched method
method[i].invoke(actionKeywords);
//Once any method is executed, this break statement will take the flow outside of for loop
break;
}
}
}
}
The problem is that you do never fill something into your method[] array. In the constructor, the array would be filled, but it is never called. Therefore, try calling the constructor inside the main method.
public static void main(String[] args) throws Exception {
new DriverScript();
...
In this line you need to change "Test Steps" to 'Sheet1' (or change the Excel sheet name to "Test Steps"):
ExcelUtils.setExcelFile(sPath, "Test Steps");

Java chat room program

I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.
Client.java
public class Client {
Server.names();
}
Server.java
public class Server {
public static HashSet<String> names = new HashSet<String>();
public static void main(String[] args) throws Exception{
while(true){
name = in.readLine();
if(name == null){
return;
}
if(!names.contains(name)){
names.add(name);
break;
}
}
}
}
Your Q is a bit unclear, but if you want to get the HashSet, names from your Server class, you need to get the reference to it by calling Server.name, not Server.name() as it is not a method.
Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names. In this case you can call the main method of Server (see this related Q here) but unless you really want that to be your main method of Server, I would recommend renaming the method to populateNames() or something similar.

Custom Console nullPointerException when checking for existing text

i have created a custom console for a program. I have a method that adds a message to the console called toConsole this asks for the string where it checks and adds the time to the string. it then goes to my function addConsole which checks if existing text is present if so it will then add the pre-existing text to the new text, else it just puts the new text in. so here is the error. i may also point out that if i enter text manually on the consoles input text box it does not produce this error.
Exception in thread "main" java.lang.NullPointerException
at com.michael.tech.api.console.RunConsole.addConsole(RunConsole.java:188)
at com.michael.tech.api.console.RunConsole.toConsole(RunConsole.java:204)
at com.michael.tech.api.console.RunConsole.toConsole(RunConsole.java:223)
at com.michael.tech.api.testerFile.main(testerFile.java:25)
here is the addConsole method
private static void addConsole(String s){
console.setText( ( console.getText().isEmpty()) ? s : (console.getText() + "\n" + s) );
}
the toConsole method
public static void toConsole(String s, boolean timeStamp, boolean classPath, String className){
if(s.startsWith("/")){
doCommand(s);
return;
}
Time t = new Time();
t.getSYSPrint();
String time = "[" + t.toMilitary() + "] ";
if(EchoTime || timeStamp){
addConsole(time + s);
}
else if(classPath){
addConsole(className);
}
else{
addConsole(s);
}
}
and lastly the Main method in testerFile class
public static void main(String[] args) {
RunConsole.startConsole();
RunConsole.toConsole("test");
}
Thanks in advance for any help. I assume it is some small mistake i overlooked (I hope too).
EDIT:
paste bin to see line numbers
RunConsole class
http://pastebin.com/2yUAwQc5
testerFile class
http://pastebin.com/R5ViLekp
The problem is that the JTextArea console still has its default null value as it has not been instantiated. This is because there is no instance of RunConsole created — Instead, you are accessing the methods of this class in a static way:
RunConsole.startConsole();
RunConsole.toConsole("test");
Using static methods is poor design especially since your application needs to have state. Make all static methods in RunConsole instance methods and replace the above lines with:
RunConsole runConsole = new RunConsole();
runConsole.startConsole();
runConsole.toConsole("test");
Also, when you do this, don't forget to remove your instance created in startConsole, otherwise you will not see the initial message from toConsole. Change:
new RunConsole().setVisible(true);
to
setVisible(true);

File class object doesn't delete files when running in a server java

I've been working on my final programming class project, and I am stuck right now, I have to create an inventary for a company. I use textpad to write the code and the icarnegie workbench, to put the classes on it and run it, so the thing is that i have this servlet and from there I call the class called Delete, this class has various methods, each of them deletes a file, something like this:
import java.io.*;
public class Delete{
String nombre;
public Delete(String n){
nombre=n;
}
public void deleteNombre(){
File objt = new File("C:/Inventario/"+nombre+"/nombre.txt");
objt.delete();
}
public void deleteCodigo(){
File objt = new File("C:/Inventario/"+nombre+"/codigo.txt");
objt.delete();
}
public void deletePrecio(){
File objt = new File("C:/Inventario/"+nombre+"/precio.txt");
objt.delete();
}
public void deleteCantidad(){
File objt = new File("C:/Inventario/"+nombre+"/cantidad.txt");
objt.delete();
}
}
When I try to call this from the servlet, I can compile successfully, I don't get any errors. when I put this code on a main class and run it, in terminal, the files are deleted, but when I use this method, calling it from a servlet, it just doesn't happen. How can this happen and how can I fix it?
The files are most likely still open somewhere else in the code.
A good starting point would be to check whether the file exists before deleting it and check for the return value of that delete() call. Something like:
File f = new File(something);
if(f.exists()) {
if(!f.delete()) {
System.out.println("Deleting " + f + " failed");
}
} else {
System.out.println("The file " + f + " doesn't exist");
}
Assuming that you've traced the code and these methods are actually getting called, this is possibly a permissions issue. Does the servlet container user have permission to access and alter those files?
That said, you probably wouldn't design a servlet application to mess around with the filesystem for non-binary data; typically you'd put this information in a database. It will avoid these permission issues, give you greater flexibility, and you wouldn't get into concurrent access issues (e.g. what happens if two users of your servlet try to access the file at the same time?)

Categories

Resources