Selenium - Java - How to implement XML variables - java

I am setting up a Selenium automated testing system written in Java.
I have the following structure:
src/
modules/
LoginForm
browsers/
Chrome
Firefox
This application has to be able to test multiple websites with different username and passwords etc..
I do not want to have to go into each of the classes in order to change the parameters (e.g. if we have to change the website and/or the username and password). I'm therefore wondering if it's possible to have an XML file that we can store all of these values in that then can be read at run time?

What you need to do is create a file with all the parameters and load them at run time. Then you can pick each value within the loop: For example
public void read(File file) throws IOException{
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
line=scanner.nextLine();
//Split the line to get the variables
//pass variables to selenium object at each line:
}
}
That way you will be able to get the job done

There are several frameworks to read XML files. You can create a XML file as follows and read it.
You may also use a properties file
data.properties
A scanner also works fine. So, now you have many options. Go do it. :)

Related

Read a txt file in Eclipse/Java using blackbox class

I'm a Uni student trying to multiply two matrices stored in txt files via java and Eclipse. We were given a pre-compiled class file, but not the source code for the class file, essentially making it a blackbox class. We're supposed to use vim and the Linux terminal to program and execute our java code, but I find that Ecplise is far more time-efficient. However, when using the Linux terminal and vim my program works as intended, whereas when using Eclipse it does not.
Here's my source code with only the LOCs using the blackbox class
String fileOne = ArrayReader.getFileName("Enter the file name of matrix one");
int[][] matrixOne = ArrayReader.readArray(fileOne);
String fileTwo = ArrayReader.getFileName("Enter the file name of matrix two");
int[][] matrixTwo = ArrayReader.readArray(fileTwo);
The getFileName function outputs the argument, expecting the user to enter the file name (including the extension) of the file with the elements of the matrix in it. If it doesn't find the file, it returns an error message stating so, then asking for the file name again. The readArray function simply gets the elements and assigns them to the elements of the integer matrix.
I've tried putting the txt files in both my src and bin folders in my project directory, and inputting the file names with and without the file extension multiple times, but to no avail.
Any ideas?
I should put this in a comment but i don't have enough reputations
*Can you provide more details about the error so we can help and try to decompile the class to view it's source code you may find your answer also you can hardcode the file name (write it directly in the code) to test if everything works correctly *
The ArrayReader class expects the computer to be using Linux, not Windows.

Is there a way to determine if a java program is run for the first time?

I am not talking about android development,i want to know if i could know if a java program is run for the first time.My program is supposed to get a user input for a password and check if the password matches the stored encrypted password and then fill some arrays and variables.But if it is the first time running the program then the user is supposed to create a password and then create the .txt and write the data.Apart from creating the .txt first is there a way to do this?
public class MyClass {
AccountReader reader = new AccountReader();
AccountWriter writer = new AccountWriter();
public static void main(String args[]) {
if(its the first time launching) do something
else{
reader.readFromFile();
do something else
}
.
.
.
writer.writeToFile();
}
}
You cant "remember" that in the programm, but you can save it in a file. Thats because all variables in your programm "resets", when your programm is terminated.
So you can write that into a file:
How do I create a file and write to it in Java?
or create a file on the first launch and look every start, if that file already exists:
How do I check if a file exists in Java?
Java programs run as a process in some container, for example JVM or a server like tomcat. Any process can be "killed" and restarted, thus your Java program will never be able to tell if it ran for the first time. From the java programs perspective, every time it is launched, it is the first time.
How we typically come around it is by persisting that information in a place outside the program. This is typically a database or a file in a non-temp folder.
You have to decide what constitutes a "first" run. Can the absence of your password file be considered as a first run? If so, you can use that check. Else, you can get inspiration from other applications, for example, bash or git etc, they will typically create a .rc file in the home directory. ~/.bashrc. You can treat it as your store. You can create your own .rc file and store your preferences there. Absence of that file can be treated as the "first run".
So thanks to #Donatic I figured out i need to checked if the wanted .txt exists and if not then this is the first time launching the program.If i want to make it somewhat flexible so that it works in every computer will something like that work?Sorry for not testing myself but i can only work in an online editor and i don't think i can check it from there.
URL main = Main.class.getResource("Main.class");
File javaFile = new File(main.getPath());
String absolutePath = javaFile.getAbsolutePath();
String javaFileFolderPath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
String txtFilePath = javaFileFolderPath+"\\wantedTxt.txt";
File txtFile = new File(txtFilePath);
if(txtFile.exists() && !txtFile.isDirectory()) {
// this is not the first time running the program
}
else{
//this is the first time running the program
}

Storing Instances with Serialization

I am making a program that needs to save objects for retrieval at a future date. The program will be given out away as a jar file to different people.
I can already store and retrieve instances of classes when giving the Object input/output stream a absolute path (String) as a parameter.
I can also save images and text files in the resources folder and get it as a resource with getClass().getResource(String path).
Here is the problem:
I have tried every way possible to save/get Objects to/from the resources folder. It gets really weird dealing with URLS and Files and not ordinary Strings. Can someone please help me? I need to be able to save and retrieve objects relative to the classpath so that i can access the objects when the program is a jar file saved in different paths on the computer.
1: resource folder (in jar), is read-only.
You can create datas, store in the jar when you package, but after, it is finished: only to read.
2: so you want user can read and write (and it is not embedded in your app).
if it is personal datas, you can use (for PC):
String appdata= System.getenv("APPDATA");
System.out.println(appdata);
String dataFolder = System.getProperty("user.home") + "\\Local Settings\\ApplicationData";
System.out.println(dataFolder);
String dataFolder2 = System.getenv("LOCALAPPDATA");
System.out.println(dataFolder2);
on my PC, it gives:
C:\Users\develop2\AppData\Roaming
C:\Users\develop2\Local Settings\ApplicationData
C:\Users\develop2\AppData\Local
see this: What is the cross-platform way of obtaining the path to the local application data directory?
it is is for everybody, same principles, but you can encounter security issues
like this:
String programdata = System.getenv("PROGRAMDATA");
System.out.println(programdata);
String allusersprofile = System.getenv("ALLUSERSPROFILE");
System.out.println(allusersprofile); // same thing !
String publicdir = System.getenv("PUBLIC");
System.out.println(publicdir);

How do you set up command line args in Eclipse for the MAC? (Intent is to submit to online programming challenges)

I know that you must add command line arguments into the "Run Configurations" in Eclipse to get your command line arguments to be passed every time by default. This worked fine on my PC.
The purpose of this question is to create a simple program that can be submitted to an online programming challenge site (like codeeval). The system provides a file path to the command line args[0] and then you manipulate the file and its data.
On the PC I had my Class folder > Default Package > (file.txt and TestCode.java)
The project was set up with a run configuration with simply file.txt in the program arguments section.
On the MAC this doesn't seem to be working. I get a fileNotFoundExcepion. I'm new to MAC so I'm thinking this might be a problem with file extensions not being what I think they are. I saved a file as "file.txt" but if I save it as "file" MAC doesn't show the file extensions and I'm not sure if MAC supports .txt by default.
If it doesn't support .txt, what file type is a "text document"? I tried saving the text document as "file" leaving off any extension, and then adding file.rtf or file.txt or even file to the Program arguments and none of that works. It all gives me a fileNotFoundException.
EDIT
The intent is to be able to develop solutions to the CodeEval (or similar) website and submit them. I have previously solved many problems on CodeEval and turned them in with the code below from a PC. This, however, doesn't work on MAC. The answer involving the use of the URL does not work when run from the solution checking platform (presumably because the program is not actually saved onto the system).
EDIT 2
My entire program:
public class TestCode {
public static void main (String[] args)throws IOException{
File filename = new File(args[0]);
Scanner file = new Scanner(filename); // returns the fileNotFoundException
while( file.hasNextLine()){
String line = file.nextLine();
System.out.println(line);
}
}
}
Under "Run Configurations" in the Arguments tab > Program Arguments I have tried putting file, file.txt, file.rtf all three with a "text document" in the same directory as the above program. I have tried naming that file file, file.txt and file.rtf And i tried every combination of these names.
Did you try to use the absolute file name as command line parameter? This should be something like /Users/name/path/to/your/file. If the file is part of your project, you can also use a variable such as ${project_loc}/file (try the button Variables… below the Program Arguments field.
Replace your code with this
URL resource = TestCode.class.getResource(args[0]);
Scanner file = new Scanner(new File(resource.getFile()).getAbsoluteFile());

Get image path in non-servlet

I have a scheduled task running in JBoss 5.1 on a daily basis for sending birthday wishes.
The mail content is HTML and I embed images in the mail.
Now I would like to get the path of that image for embedding, how would it be possible to get path of image in a non-servelt environment.
Ofcourse I could have placed the images at a static location and accessed them, for which I don't want to hardcode the path.
The image is at "WebContent/images/birthday.jpg" location.
How are you generating the email content? Are these also static html files?
If you are going to use simple static html files, you will have to hard code the image paths. There is no other way around it.
You could write a simple Java application, which runs as a standalone application (without any servers,servlets etc), which will create the email content.
The java code can send out the emails for you too if you want.
These are some of the things you can do, if you use java
Use property files to specify the location of images. These are files which hold simple key/value pairs.
You can easily create multiple email content to different users, with the same template.
You will be able to easily redesign the html content for multiple users.
An example of using property files.
Create a file ex: "email_template.properties"
Enter the following into the file and save it.
image_server=http://www.mywebsite.com
image_folder=/WebContent/images/
Create a jave program to create your html email, and use the property file to generate the image locations.
Properties properties = new Properties();
try
{
properties.load(new FileInputStream("C://email_template.properties")); //specify path here
String sServerLocation = properties.getProperty("image_server");
String sImageFolder = properties.getProperty("image_folder");
StringBuilder strEmail = new StringBuilder();
strEmail.append("<html><body> <img src=\"" + sServerLocation + sImageFolder +"birthday.jsp\""> </body> </html>" );
// Write code to generate complete email dynamically
// write code to send out the email or to save as html file to you machine, where you can send it manually.
} catch (IOException e)
{
//
}
You get the idea. using plain html you will have to hard code.
However if you use a simple java file you can get more flexibility.
If you need code to send out email from java, check this link out.
How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Categories