Is it possible to add a variable where code should be? - java

I am currently trying to create an automation framework using Java and Selenium.
I want to create a line of code which essentially can read any input and make it a line of runnable code. For example, in an external file, a user could post 'id' into a field, that field will then be read by my program and execute the line. driver.findElement(By.id(.......)
Currently I'm using a bunch of if statements to do this for each identifier e.g. id, cssSelector, Xpath etc etc but then I'll need to do the same for the actions used by the program .click, .sendKeys etc so the program will just keep expanding and look overall very messy.
Is there a solution that would allow me to do this in a nicer way or am I stuck with my original approach?

Reflection is probably the most direct way to solve this. It essentially allows classes and methods to be looked up by their string names.
Here's a fag-packet example of how you might approach this using the snippet you provided, but I suggest you read some documentation before diving in.
Element findElementReflectively(Driver driver, String elementType, String thingToSearchFor) {
try {
Method m = By.class.getMethod(elementType, String.class);
if(!Modifier.isStatic(m.getModifiers())) {
throw new NoSuchMethodException("'By' method is not static.");
}
return driver.findElement(m.invoke(null, thingToSearchFor));
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new IllegalArgumentException("Unknown element type: " + elementType, e);
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to find requested element.", e.getCause());
}
}

It depends on what you actually want to do.
Reading an id from a file and then execute code can be achieved through config file with this : Properties
Or if you want to execute full input code just search a little bit more
How to execute console or GUI input as if it was actual Java code?

Related

How to correctly handle a spark.sql.AnalysisException

I've been using Spark Dataset API to perform operations on a JSON to extract certain fields as needed. However, when the specification that I provide to let spark know what field to extract goes wrong, spark spits out an
org.apache.spark.sql.AnalysisException
How can unchecked runtime exceptions be handled in a distributed processing scenario like this ? I understand that throwing a try-catch would get things sorted but what is the recommended way to handle such a scenario
dataset = dataset.withColumn(current, functions.explode(dataset.col(parent + Constants.PUNCTUATION_PERIOD + child.substring(0, child.length() - 2))));
In scala, you should simply wrap the call in a Try and manage Failure. Something like:
val result = Try(executeSparkCode()) match {
case s: Success(_) => s;
case Failure(error: AnalysisException) => Failure(new MyException(error));
}
Note 1: If your question implies how to manage exception in scala, there are a lot of doc and post about this subject (i.e. don't throw). For example, you can check that answer (of mine)
Note 2: I don't have a scala dev env right here, so I didn't test this code)
In java there is a tricky situation however: the compiler doesn't expect an AnalysisException which is unchecked so you cannot catch this exception specifically. Probably some scala/java misunderstanding because scala doesn't track checked exceptions. What I did was:
try{
return executeSparkCode();
} catch (Exception ex) {
if(ex instanceOf AnalysisException){
throw new MyException(ex);
} else {
throw ex; // unmanaged exceptions
}
}
Note: In my case, I also tested the content of the error message for a specific exception that I must managed (i.e "path does not exist") in which case I return an empty dataset instead of throwing another exception. I was looking for a better solution and happened to get here...

Freemarker ignore missing variables

I'm using freemarker to generate files and I'm struggling with the templateExeptionHandler part. I have variables in my template that don't have to be replaced (if they are not present in the data-model). I don't like to put these variables inside my data-model with the same value (can't get it to work either) and I know I can 'escape' variables in the template itself but I don't really like that solution.
MyTemplateExceptionHandler looks as follows:
class MyTemplateExceptionHandler implements TemplateExceptionHandler {
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
try {
out.write("${" + te.getBlamedExpressionString() + "}");
} catch (IOException e) {
throw new TemplateException("Failed to print error message. Cause: " + e, env);
}
}
}
The problem is that once I'm parsing variables in the form of:
${workflow.input.myVariable}
the result in my new generated file is showing only the first part of this variable:
${workflow}
Any thoughts on how I can get the full variable back and returned in my generated file?
That use case is not supported, as of 2.3.27 at least. It's not even clear how it should work, like, what if the missing variable is a parameter to a directive? Certainly it could be solved for the case of ${} only (even then, only when it appears outside a string literal), but I'm not sure if that addresses the need, or it just lures uses into using it and then they hit a wall later on with a directive parameter... (Or, another tricky case, what's with ${thisIsMissing + thisExists}? I guess it should become to something like ${thisIsMissing + 123}... so doing this right can complicate the core quite much.)

Java: Writing Variables to File, and Reading back

I am currently using Eclipse Java Neon for my builder, and I am trying to implement a save and load feature into a project i am currently working on. I know it requires me to use a Try/Catch block, but I have no idea how to really handle it. Not only that, but what I tried out is giving me a bit of an error:
try {
System.out.println("Writing to file...");
charWrite = new FileWriter("player.dat");
charWrite.write(player.getName()); //String
charWrite.write(player.getJob()); //String
charWrite.write(player.getLevel()); //Int
charWrite.write(player.getCurrency()); //Int
charWrite.write(player.getHealth()); //Int
charWrite.write(player.getExp()); //Int
}
catch (IOException excpt) {
System.out.println("Caught IOException: " + excpt.getMessage());
}
The system seems to recognize what is happening, but when I go to open it and see if it has written, the document is still blank.
And if I am this lost on writing, I am going to be so lost when reading to place it into the Class's parameters.
Thanks for the help.
You are trying to write an object of type java.lang.Class to a file. If you want the String representation of the class name use toString():
charWrite.write(player.getClass().toString());

exception handling, creating log and continue the program in JAVA

I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the program must not stop here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file.
You're looking for the try-catch block. See, for example, this tutorial.
OutputStream os = ....;
PrintStream ps = new PrintStream(os);
while(notDone) {
try {
doStuff();
}
catch(Throwable t) {
t.printStackTrace(ps);
}
ps.print(results);
}
the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
To do all of these, it is better to surround your code with try catch block

How to run one test against multiple sites using Selenium and TestNG

Given 3 web applications under test with given URLs:
www.A.com
www.B.com
www.C.com
How do I proceed to design a way using Selenium to run a single TestNG test against these three browsers and print out the results.
Current Strategy:
I have a java class with a main method, a properties file containing the the 3 urls listed above.
In this class i have a while loop that parses these properties file like below snippet, and for each url, programmatically calls an ant task that automates the build from compilation to test-run to result archiving. The problem is that after the first run completes, it doesn't return to the while loop to do it again. You might ask why i want to run it three times. The idea as already explained is to be able to run a suite of tests against multiple websites automatically and printout results without intervention. Code Snippet
try {
reader = new BufferedReader(new FileReader(new File(filename)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
while((line=reader.readLine()) != null){
//call ant target to archive result
userprops.setProperty("url", line);
org.apache.tools.ant.Main.start(target, userprops, loader);
}
}catch (IOException e) {
e.printStackTrace();
}
I hope somebody understands what am trying to do and can help me understand why the while loop terminates after the first test run. Also maybe can offer another easier strategy with TestNG.
thanks Guys. Y.ou guys Rock!!
It seems to me that if you are using ANT you shouldn't need your class. I would just use three targets and assign the different properties within those targets.

Categories

Resources