I would like to use a function to read from a properties file and than use the object of that file at various places.here is what I have tried so far with no luck.
public class all_the_functions
{
public FileInputStream loadPropertiesFile(FileInputStream obj2) throws IOException
{
//reading from the properties file
Properties obj = new Properties();
FileInputStream fileobj = new FileInputStream("//Users//macuser//Desktop//selenium//project_Mat//input_properties.properties");
obj.load(fileobj);
return fileobj;
}
}
And than in my main function I am using the following code
public class searchdynamic();
{
FileInputStream Obj;
all_the_functions func = new all_the_functions();
func.loadPropertiesFile(Obj);
WebDriver driver = new FirefoxDriver();
driver.navigate().to(Obj.getproperty("valid URL");
}
The end goal is to read from. The input file by using the function and stroung the properties file so that I can always call the same function when I need to read from the file. Can someone please point me to what I am doing wrong here.
Thanks.
Can u try this
public class searchdynamic();
{
FileInputStream Obj;
all_the_functions func = new all_the_functions();
Obj=func.loadPropertiesFile(Obj);
WebDriver driver = new FirefoxDriver();
driver.navigate().to(Obj.getproperty("valid URL");
}
What is the string that your property is returning? "http://www..."
In theory, this should work (although I'm used to webdriver being navigate().GoToUrl(string url). Give that a shot...
Also, friendly warning about this being not oop or compiling. Might be a good idea to tie your properties to values somehow. I understand this is a keyword driven framework, but it is better practice to have a user input "Google" and have your code digest that into something like
driver.Navigate().GoToUrl("http://google.com"); // (c#)
This way, you can count on correct input and handle incorrect input appropriately.
Regardless, try .Navigate().GoToUrl()
Related
I am given an assignment where we are not allowed to use a DB or libraries but only textfile for data storage.
But it has rather complex requirements, for e.g. many validations, because of that, we need to "access the db" (i.e. read the textfile) many times.
My question is: should I create a class like this:
class SomeRepository{
static ArrayList<Users> users = new ArrayList();
public SomeRepository(){
//instantiate this class on program load
//In constructor, we read the text file, instantiate and store everything inside the arraylist.
}
//public getOneUser(){ // for get methods, we don't read from text file at all }
/public save() { //text file saving code overhere }
}
Is this a good approach to solve the above problem? Currently, what we are doing is reading and writing to the text file every time we want to retrieve some data or write something new.
Wouldn't this be too expensive in terms of heap space memory? Or should I just read/write to the text file for every method?
public class IOManager {
public static void writeObjToTxtFile(String fileName, Object object) {
File file = new File(fileName + ".txt");//File will be created in the root directory where the program runs.
try (FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);) {
oos.writeObject(object);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object readObjFromTxtFile(String fileName) {
Object obj = null;
File file = new File(fileName + ".txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return obj;
}
}
Add this class to your project. Since it's general for all Objects, you can pass and receive Objects like these as well: ArrayList<Users>. Play around and Tinker with it to fit whatever your specific purpose is. Hint: You can write other custom methods that calls these methods. eg:
public static void writeUsersToFile(ArrayList<Users> usersArrayList){
writeObjToTxtFile("users",usersArrayList);
}
Ps. Make sure your Objects implement Serializable. Eg:
public class Users implements Serializable {
}
I would suggest reading the contents of your file to a dynamic list such as an arraylist at the start of your program. Make the required queries/changes to your arraylist and then write that arraylist to your file when the program is set to close. This will save significant time over repeated file reads/writes.
This isn't without it's drawbacks, though. You don't want to hogg up memory in case of very large files - but considering this is an assignment, that may not be the case. Additionally, should your program terminate prior to the write at the end, all changes made to your database during the current execution will be lost.
I want to read data from an XML file. I am using Java & Selenium WebDriver. I have found many solutions while researching. The problem is none seems to apply to my problem.
My XML file is as such :
<Enviroment>
<Parameter>Test_Url</Parameter>
<value>https://www.google.com</value>
<Parameter>Distributed_Test</Parameter>
<value>no</value>
<Parameter>Result_Name</Parameter>
<value>Google_Results</value>
</Enviroment>
The code I am using to read this xml file is here.
public class ReadXML {
static String value;
public static void main(String[] args) throws FileNotFoundException,IOException {
File file = new File("path of the file");
FileInputStream fileInput =new FileInputStream(file);
Properties prop =new Properties();
//prop.load(fileInput);
prop.loadFromXML(fileInput);
fileInput.close();
Enumeration enumKeys=prop.keys();
while(enumKeys.hasMoreElements()){
//String node = "Environment";
String subnode= "Parameter";
if(((String) enumKeys.nextElement()).contains(subnode)){
value = prop.getProperty(subnode);
System.out.println(value);
}
}
return ;
}
When I am using prop.load(fileInput), output is printed as null thrice for the three parameter values, I believe.
But if I use prop.loadFromXML(fileInput), InvalidPropertiesFormatException is shown.
Please help..Thanks in Advance!!
The error in the properties format can be checked via xmllint:
xmllint foo.properties
In this case, the closing tag is:
</Enviroment>
but needs to be:
</Environment>
References
Class Properties
# Compulsory Dimension to create port
xOffset=-3
yOffset=50
How to get these xOffset and YOffset in java file.I tried with inputstream but not getting.These variable should get loaded in java file.
You can use Properties class from Java library
Properties prop = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
prop.load(inputStream);
The you can get the values as
prop.getProperty("propertyname");
Try the following code:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("your_config.properties");
prop.load(input);
System.out.println(prop.getProperty("xOffset"));
System.out.println(prop.getProperty("yOffset"));
} catch (IOException e) {
// ...
}
As above explained Create a Function to read the property File During or Before Selenium Driver Constructor . So you can use them in test ( Help in Desire Capability Impl).
Store the values in Public Static final ( If you don not want to change them in Selenium and use as Default Property input)
As the values are read by Java Propertie file or .config file before selenium Driver so you can use them in Driver constructor or if you don't want you can use those properties stored as Static anywhere in the project. These values act as GLOBAL param.
My homework assignment is to read a URL and print all hyperlinks at that URL to a file. I also need to submit a junit test case with at least one assertion. I have looked at the different forms of Assert but I just can't come up with any use of them that applies to my code. Any help steering me in the right direction would be great.
(I'm not looking for anyone to write the test case for me, just a little guidance on what direction I should be looking in)
public void saveHyperLinkToFile(String url, String fileName)
throws IOException
{
URL pageLocation = new URL(url);
Scanner in = new Scanner(pageLocation.openStream());
PrintWriter out = new PrintWriter(fileName);
while (in.hasNext())
{
String line = in.next();
if (line.contains("href=\"http://"))
{
int from = line.indexOf("\"");
int to = line.lastIndexOf("\"");
out.println(line.substring(from + 1, to));
}
}
in.close();
out.close();
}
}
Try to decompose your method into simpler ones:
List<URL> readHyperlinksFromUrl(URL url);
void writeUrlsToFile(List<URL> urls, String fileName);
You could already test your first method by saving a sample document as a resource and running it against that resource, comparing the result with the known list of URLs.
You can also test the second method by re-reading that file.
But you can decompose things further on:
void writeUrlsToWriter(List<URL> urls, Writer writer);
Writer createFileWriter(String fileName);
Now you can test your first method by writing to a StringWriter and checking, what was written there by asserting the equality of writer.toString() with the sample value. Not that methods are becoming simpler and simpler.
It would be actually a very good excercise to write the whole thing test-first or even play ping-pong with yourself.
Good luck and happy coding.
I have a code in Java that opens a excel template by aspose library (it runs perfectly):
import com.aspose.cells.*;
import java.io.*;
public class test
{
public static void main(String[] args) throws Exception
{
System.setProperty("java.awt.headless", "true");
FileInputStream fstream = new FileInputStream("/home/vmlellis/Testes/aspose-cells/template.xlsx");
Workbook workbook = new Workbook(fstream);
workbook.save("final.xlsx");
}
}
After I run this on Ruby with RJB (Ruby Java Bridge):
require 'rjb'
#RJM Loading
JARS = Dir.glob('./jars/*.jar').join(':')
print JARS
Rjb::load(JARS, ['-Xmx512M'])
system = Rjb::import('java.lang.System')
file_input = Rjb::import('java.io.File')
file_input_stream = Rjb::import('java.io.FileInputStream')
workbook = Rjb::import('com.aspose.cells.Workbook')
system.setProperty("java.awt.headless", "true")
file_path = "/home/vmlellis/Testes/aspose-cells/template.xlsx"
file = file_input.new(file_path)
fin = file_input_stream.new(file)
wb = workbook.new(fin)
I get this error:
test.rb:57:in `new': Can't find file: java.io.FileInputStream#693a317a. (FileNotFoundException)
from aspose-test.rb:57:in `<main>'
Why? I run the same code... but in Ruby is not working! How do I fix this?
Update:
In documentation there is the the initializer: Workbook(java.io.InputStreamstream)... but it's not working in RJB. (How is this possible?)
Your program should have worked, but I could not find any reason why it didn't and I am looking into it.
Now the alternate approaches.
Approach 1
Use Workbook(String) constructor instead of Workbook(FileInputStream). This worked flawlessly at my end. The sample code is
require 'rjb'
#RJM Loading
JARS = Dir.glob('/home/saqib/cellslib/*.jar').join(':')
print JARS
Rjb::load(JARS, ['-Xmx512M'])
system = Rjb::import('java.lang.System')
workbook = Rjb::import('com.aspose.cells.Workbook')
system.setProperty("java.awt.headless", "true")
file_path = "/home/saqib/rjb/template.xlsx"
save_path = "/home/saqib/rjb/final.xlsx"
wb = workbook.new(file_path)
wb.save(save_path)
Approach 2
Write a new Java class library. Write all your Aspose.Cells related code in it. Expose very simple and basic methods that needs to be called from Ruby (RJB).
Why?
It is easy to write program in native Java language. If you use RJB, you need to perform a lot of code conversions
It is easy to debug and test in Java.
Usage of RJB will only be limited to calling methods from your own Java library. The RJB code will be small and basic.
Similar Example using own library
Create a new Java project, lets say "cellstest". Add a new public class in it.
package cellstest;
import com.aspose.cells.Workbook;
public class AsposeCellsUtil
{
public String doSomeOpOnWorkbook(String inFile, String outFile)
{
String result = "";
try
{
// Load the workbook
Workbook wb = new Workbook(inFile);
// Do some operation with this workbook
// ..................
// Save the workbook
wb.save(outFile);
// everything ok.
result = "ok";
}
catch(Exception ex)
{
// Return the exception to calling program
result = ex.toString();
}
return result;
}
}
Like this, add as many methods as you like, for each operation.
Build the project and copy the "cellstest.jar" in same folder where you copied Aspose.Cells jar files. You can return a String from your methods and check the return value in Ruby program for success or error code. The Ruby program will now be like
require 'rjb'
#RJM Loading
JARS = Dir.glob('/home/saqib/cellslib/*.jar').join(':')
print JARS
Rjb::load(JARS, ['-Xmx512M'])
system = Rjb::import('java.lang.System')
AsposeCellsUtil = Rjb::import('cellstest.AsposeCellsUtil')
system.setProperty("java.awt.headless", "true")
file_path = "/home/saqib/rjb/template.xlsx"
save_path = "/home/saqib/rjb/final.xlsx"
# initialize instance
asposeCellsUtil = AsposeCellsUtil.new()
# call methods
result = asposeCellsUtil.doSomeOpOnWorkbook(file_path, save_path)
puts result
PS. I work for Aspose as Developer Evangelist.
In your Java code, you pass a file name string into FileInputStream() constructor:
FileInputStream fstream = new FileInputStream("/home/vmlellis/Testes/aspose-cells/template.xlsx");
In your Ruby code, you pass a file object:
file = file_input.new(file_path)
fin = file_input_stream.new(file)
Have you tried to do the same thing as in Java?
fin = file_input_stream.new(file_path)