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");
}
}
Related
I am writing junit test cases for my project but i am facing one problem
Here is a method that i am using in one of my java class (GraphNodes.java)
public static ArrayList<String> getCSList() {
System.out.println(CSList.size()); // Output : 3
return CSList; // returns 3 elements in list
}
Now here is my test class for Junit
#Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size(); // My exceptation here is 3 but in console it shows 0
int excepted = 3;
assertEquals(excepted,actual);
}
My junit is failing by saying excepted<3> but actual<0>
Also i cannot change the static method to only public because it will affect some functionality of the code and since i am new to junit, i am not getting idea how to fix this.so can anyone help me out here
Thanks in Advance!!
You need to validate how you populate the object CSList() during runtime and do exactly the same when you are running the test.
One option is to have a #BeforeEach method in your test where it will set the values of what you need during the test.
#BeforeEach
public void setUp() {
GraphNodes.setCSList(Arrays.asList("A","B","C"));
}
#Test
public void checkCSListCount(){
int actual= GraphNodes.getCSList().size();
int excepted = 3;
assertEquals(excepted,actual);
}
I think you are trying to write an integration test. So you should call the method, that fills the list with your 3 elements, before checking the list size. If all the logic for that is in your main method you should extract it into its own method.
I am quite a new coder in Java, I have already used it before but without going deep into it, but now that I learned the basic I am searching for a way to be more efficient in my way of coding, so I ask how could I do lines of code to run one after another each time I use a certain word, for example, I would like my code to run several fighting commands that I premade using only the word "fight" in my code
All you need to do is set up a scanner that waits for a string input after which is process the string received through the scanner and if said string is "fight" then call the fight method.
Like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String command = in.next();
in.close();
ProcessCommand(command);
}
static void ProcessCommand(String command) {
if (command.equalsIgnoreCase("fight")) {
fight();
}
}
static void fight() {
// Do Stuff..
}
Hope this helps! :D
So I have written a Java program that has a function handInExam() that may not be called twice in a row, thus the program is history-sensitive. The problem that then occurs is that I need a variable canHandInExam to check whether this method has already been called and update this variable in each method, which leads to very poor maintainability. Below is a code snippet to show the problem.
public class NotAllowedException extends Exception {
public NotAllowedException(String message) {
super(message);
}
}
import java.util.Scanner;
public class Exam {
String[] exam;
String[] answers;
boolean canHandInExam;
public Exam(String[] questions) {
exam = questions;
answers = new String[exam.length];
canHandInExam = false;
}
// This method may only be called once in a row
public void handInExam throws NotAllowedException() {
if (canHandInExam) {
// Send exam to teacher
canHandInExam = false;
} else {
throw new NotAllowedException("You may not hand in this exam!");
}
}
public void otherMethod() {
// Do something
canHandInExam = true;
}
}
In this small example it is feasible to slightly adapt each method, however if you would have lots of methods you would need to adapt all of them. Since after all these methods you may again call handInExam() thus the variable canHandInExam would need to be set to true.
Is there a way to solve this problem in a way that is more maintainable? I am open to other possible programming languages that are not OO, but at this point I am unsure of what would be suitable.
I have considered using functional programming (e.g. Haskell) as those languages are not history-sensitive, however I did not know how to limit that you may only call a function once in a row. I tried searching for how to limit a function call to n times in a row both in Java and Haskell, but this ended up with only references to how to call a function n times.
If you speak about handing in an exam, than this doesn't mean that something is done with that exam, but that there is some entity to which the exam is given. So instead of storing within the exam whether it was handed in or can be handed in, something like this would be more appropriate:
//or whatever you call this
public interface Institution {
void handInExam(Exam exam) throws DuplicateExamException;
boolean isHandedIn(Exam exam);
}
Implementations of Institution store the exams that were handed in (possibly using a Set).
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.
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.