Custom Console nullPointerException when checking for existing text - java

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);

Related

How to get string value from another class using selenium and testng in java

I am trying to get the value of string in the first class and use it to another class. Below is my code :
public class Add extends driver {
public static String reportV1;
#Test
public String export() throws InterruptedException, IOException {
// Report Name
WebElement report1 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nReportName")));
reportV1 = report1.getAttribute("value");
if (reportV1.equals(reportV)) {
System.out.println(" PASSED - Report Name: " + reportV1);
} else {
System.out.println(" FAILED - Report Name: " + reportV1);
soft.assertTrue(false);
}
soft.assertAll();
return reportV1;
I'm new to java, so can someone help me to get the value of string?
Thank you in advance.
I think you should read about static fields first to get clear picture about this thing.
Anyway, static variables can be accessed by calling with the class name ClassName.VariableName.
Add.reportV1 in your case. Btw in your example reportV1 is not initialized yet, fyi.

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 Swing Components not working in public void main(String[]args) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm running the main method by clicking a jButton in this class. First tried by using
public static void main(String[]args)
All the java swing components started to show non static variable cannot be referenced from static content errors. So I changed
public static void main(String[]args)
to
public void main(String[]args)
No errors shown for the swing components but expected result are not displaying in the jTextArea. IF i print the expected output in System.out.println, it shows correctly. What am I doing wrong here? This is how i trigger main() to run by clicking on jButton
jButton4.setText("Analyze");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try{
TestTextRazor test = new TestTextRazor();
test.main(new String[0]);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
This is my main()
public void main(String[] args) throws NetworkException, AnalysisException {
File textSRC = new File("MyText.txt");
String myTextCount = null;
BufferedReader myTextBr = null;
String check = "";
try {
String myTextCurrentLine;
myTextBr = new BufferedReader(new FileReader(textSRC));
while ((myTextCurrentLine = myTextBr.readLine()) != null) {
myTextCount = myTextCount + " " + myTextCurrentLine;
}
// Sample request, showcasing a couple of TextRazor features
String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";
TextRazor client = new TextRazor(API_KEY);
client.addExtractor("words");
client.addExtractor("entities");
client.addExtractor("entailments");
client.addExtractor("senses");
client.addExtractor("entity_companies");
String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";
client.setRules(rules);
AnalyzedText response = client.analyze(myTextCount);
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
for (Sentence sentence : response.getResponse().getSentences()) {
for (Word word : sentence.getWords()) {
System.out.println("----------------");
System.out.println("Word: " + word.getLemma());
for (Entity entity : word.getEntities()) {
///System.out.println("Matched Entity: " + entity.getEntityId());
}
for (Sense sense: word.getSenses()) {
//System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
}
}
}
// Use a custom rule to match 'Company' type entities
for (Custom custom : response.getResponse().getCustomAnnotations()) {
for (Custom.BoundVariable variable : custom.getContents()) {
if (null != variable.getEntityValue()) {
for (Entity entity : variable.getEntityValue()) {
String CompanyFound = ("Variable: " + variable.getKey() +"\n"+ "Value:" + entity.getEntityId());
System.out.println(CompanyFound);
jTextArea3.append(CompanyFound);
writer.write(CompanyFound);
writer.flush();
writer.close();
}
}
}
}
String ObjButtons[] = {"Yes","No"};
int PromptResult;
PromptResult = JOptionPane.showOptionDialog(null,"Completed Analysis!\nIs there any error in the Analysis?","Homonym Entity Extraction Application",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
//JOptionPane.getAlignmentX(Component.BOTTOM_ALIGNMENT);
if(PromptResult==JOptionPane.YES_OPTION)
{
System.out.println("YEs!!!!!");
jTextArea2.setEditable(true);
jTextArea3.setEditable(true);
jButton4.setEnabled(false);
jButton5.setEnabled(true);
}
else{
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
System.out.println("No!!!!!!!!!!");
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
jButton4.setEnabled(false);
}
}catch (IOException ex) {
}
}
Please guide me.
Basically, the error is saying, you are trying to reference non-static variables from a static context.
Non-static variables (often referred to as instance variables or fields) require an instance of their parent class in order to have some kind referencing context.
Take a look at Understanding Instance and Class Members for more details.
Without much more of an example to go by, I would create a class constructor and move the contents of the main method to it.
I would then fix the main method to be static and create a new instance of the class from the main method...
The reason I would refrain from making Swing components static is it's way to easy to mix up you references and end up referencing something that isn't actually displayed on the screen...
Updated
Two things.
Make sure that the context of your main method is correct, that the UI components that you have created are not static and you are referencing them correctly.
Don't call the TestTextRazor class directly. This is just an example of how the API works. Take the time to understand it and incorporate into your own class(es) as required
Firs of all, what you need to understand is that a static method cannot access class fields or other methods that are non-static. So look at your code. The main has to be static as that is its natural signature, which must remain in tact as is. So all your class fields that you are trying to access in the main method, need to be static. Is this good practice? Absolutely not. You can browse through the Swing tutorial to pick up on good practices. I'm sure if you run through 20 examples, you'll pick up on a lot of good coding practices for Swing. Good Luck!
"I'm running the main method by clicking a jButton in this class"
One thing I noticed that you are doing complete wrong is trying to call the main method from inside your actionPerformed. The main method should never be called. The JVM using that method as an entry point for your program.
Another thing you have to understand is that a Swing program is event-driven. One button, should not run a complete program, unless it is a very small program.
I would consider creating methods for different tasks like
public String getSomethingFromFile(String filename) throws IOExceptions {
}
where you can call that method from an actionPerformed or something to append data to a text area.
Learn to use class members and initialize them in your constructor or some initialization method.
If you want everything that's going on the main method to be performed on a button click, put all that code in the actionPerformed , not in the main. A typical form of what goes inside the main is just something like this, where you just need to initialize your class to get the program running
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new JFrame();
frame.add(new MyGUIPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
where new MyGUIPanel() is an instance of your Main class
Another option is to create a method to perform all the tasks that are in the main like
public void performTextRazorTask() throws NetworkException, AnalysisException {
...
}
and just call that method from the actionPerformed
Again, I stress that you have a look at the tutorials I linked for better practices, as this site isn't really a tutorial site, I don't want to get into a tutorial type answer.
First of all you can not make main method as non static.
As per this line non static variable cannot be referenced from static content errors. make those variables as static

Code Structure for Parsing Command line Arguments in Java

I have a question regarding structuring of code.
I have let us say three types of packages A,B and C.
Now, classes in package A contains classes which contain the main() function. These classes
need some command line arguments to run.
In package B, there are classes which contains some public variables, which need to be configured, at different times. For example before calling function A, the variable should be set or reset, the output differs according to this variable.
In package C, uses the classes in package B to perform some tasks. They do configure their variables as said before. Not only when the object is created, but also at intermediate stage.
Package A also has classes which in turn use classes from package B and package C. In order to configure the variables in classes of B and C, class in package A containing the main() function, reads command line arguments and passes the correct values to respective class.
Now, given this scenario, I want to use Apache Commons CLI parser.
I am unable to understand how exactly I should write my code to be structured in an elegant way. What is a good design practice for such scenario.
Initially I wrote a class without Apache to parse the command line arguments.
Since I want a suggestion on design issue, I will give an excerpt of code rather than complete code.
public class ProcessArgs
{
private String optionA= "default";
private String optionB= "default";
private String optionC= "default";
public void printHelp ()
{
System.out.println ("FLAG : DESCRIPTION : DEFAULT VALUE");
System.out.println ("-A <Option A> : Enable Option A : " + optionA);
System.out.println ("-B <Option B> : Enable Option B : " + optionB);
System.out.println ("-C <Option C> : Enable Option C : " + optionC);
}
public void printConfig()
{
System.out.println ("Option A " + optionA);
System.out.println ("Option B " + optionB);
System.out.println ("Option C " + optionC);
}
public void parseArgs (String[] args)
{
for (int i=0;i<args.length;i++)
{
if (args[i].equalsIgnoreCase ("-A"))
optionA = args[++i];
else if (args[i].equalsIgnoreCase ("-B"))
optionB = args[++i];
else if (args[i].equalsIgnoreCase ("-C"))
optionC = args[++i];
else
throw new RuntimeException ("Wrong Argument : " + args[i] + " :: -h for Help.");
}
}
}
Points to note -
I already have 50+ command line options and they are all in one place.
Every class uses only a group of command line options.
I tried to write an interface, somehow but I am unsuccessful. I am not sure if this is a good way to do it or not. I need some design guidelines.
Here is the code which I wrote -
public interface ClassOptions
{
Options getClassOptions();
void setClassOptions(Options options);
}
public class Aclass implements ClassOptions
{
private String optionA="defaultA";
private String optionB="defaultB";
public Options getClassOptions()
{
Options options = new Options();
options.addOption("A", true, "Enable Option A");
options.addOption("B", true, "Enable Option B");
return options;
}
public void setClassOptions(Options options, String args[])
{
CommandLineParser parser = new BasicParser();
CommandLine cmd=null;
try
{
cmd = parser.parse( options, args);
} catch (ParseException e)
{
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("ignored option");
}
if(cmd.hasOption("A"))
optionA = "enabled";
if(cmd.hasOption("B"))
optionB = "enabled";
}
}
I think the problems in such writing of code are -
There are different types of arguments like int, double, string, boolean. How to handle them all.
getClassOption() and setClassOption() both contain the arguments "A", "B" for example. This code is prone to errors made while writing code, which I would like to eliminate.
I think the code is getting repetitive here, which could be encapsulated somehow in another class.
Not all the arguments are required, but can be ignored.
Thank You !
I would recommend to you JCommander.
I think it's a really good Argument Parser for Java.
You define all the Argument stuff within annotations and just call JCommander to parse it.
On top of that it also (based on your annotations) can print out the corresponding help page.
You don't have to take care about anything.
I believe you will love it! :)
Take a look at it: http://jcommander.org/
There are a lot of examples and such!
Good Luck! :)
simple example for command line argument
class CMDLineArgument
{
public static void main(String args[])
{
int length=args.length();
String array[]=new String[length];
for(int i=0;i<length;i++)
{
array[i]=args[i];
}
for(int i=0;i<length;i++)
{
System.out.println(array[i]);
}

What would be a safe way to split a string into multiple parts in Java?

Let me clarify the question I am asking. I have a java program I am working on that takes input from the keyboard via a readline library called JLine2. The library takes the entire line types as a command instead on breaking it up into space separated commands and arguments. What I am looking for is a safe way to break up the string that is passed as input.
I have tried using an array but since I am in the early stages of concept I don't yet know how many arguments my largest command will have so using a pre-initialized array I don't think will work. The problem I have ran into is when I check for null values in the array or when I check to see if a particular command or argument is present. Java keeps throwing an exception about the array index being out of scope or something. Because the array does not actually have a value for say array index 1 which is an argument to command in array index 0.
So what I am looking for is a way to take a string and safely split it into parts without having Java yelling at me when and array exception has occurred.
Here is the very slim code I can provide...
ConfigShell.class
package shell;
import java.io.IOException;
import configFS.ConfigFS;
import jline.console.ConsoleReader;
public class ConfigShell {
private ConfigFS config;
public ConfigShell() throws IOException {
config = new ConfigFS();
}
public void init() throws IOException {
ConsoleReader console = new ConsoleReader();
// When the program starts we want to be placed at / (root).
console.setPrompt(">> ");
// In this case an infinite loop is better than a loop based on whether line is equal to null.
// This allows line to be equal to null and still stay inside the shell.
while (true) {
String line = console.readLine();
if (line != null) {
// If pre-initialize the array I can check for null as a value for an array index.
// If I did this at time I needed the array and there were not enough index occupied the system would return an exception.
String[] cmdArgs = new String[4];
// We need to split up the incoming line because JLine2 does not do it for me.
// This allows me to evaluate the entire command piece by piece rather all at once.
cmdArgs = line.split("\\s+");
if (cmdArgs[0] != null && cmdArgs[0].equals("add")) {
if (cmdArgs[1] != null && cmdArgs[1].equals("server")) {
if (cmdArgs[2] != null) {
config.addServer(cmdArgs[2]);
System.out.println("Added server " + cmdArgs[2] + " to the configuration successfully.");
}
}
}
if (cmdArgs[0].equals("exit")) {
System.exit(0);
}
}
}
}
}
Note for testing: My Start.class main method makes a call to the init method in the above file.
You can do:
String cmdArgs = line.split("\\s+");
and then, before accessing any particular index, check the size of the array so that you do not get ArrayIndexOutOfBoundException
Something like this:
if(cmdArgs.length>=2){
//It means you have at least 2 elements
//Now its safe to access cmdArgs[0] and cmdArgs[1]
}
If all your problem is to have a storage for a variable number of strings you can use ArrayList<String> object.
You declare it like ArrayList<String> as = new ArrayList<String>();
Then when you split something from your command string you will simply use add method:
as.add(yourString);
If you need to retrieve a particular element of the ArrayList you can use its get method:
as.get(0);
You can process all elements with for each loop:
for(String str: as) {
println(str):
}
Have a look here for info and here for an example.
As I think you can use StringTokenizer class and its methods for your requirement.
see the sample code below:
if(line!=null)
{
StringTokenizer st=new StringTokenizer(line);// by default it takes space as delimiter....you can use as required as second argument in constructor...
while(st.hasMoreTokens())
{
String token1=st.nextToken();
// do your stuffs here..........
// I don't know exactly about your required logic here......
/* if(token1.equals("add"))
{
String token2=st.nextToken();
if(token2.equals("server"))
{
String token3=st.nextToken();
config.addServer(token3);
System.out.println("Added server " + token3 + " to the configuration successfully.");
}
}
*/
}// while closing...
}// outer if closing...
Or as PM 77-1 told you can use ArrayList. But as my opinion LinkedList should be a better option here.

Categories

Resources