Serenity screenplay pattern- upload file - java

We are trying cucumber serenity framework for end to end tests. I am fairly new the technology and I tired this simple code below.
actor.attemptsTo(Enter.theValue(path).into(Upload));
where path is the location of file i am trying to upload using browser's upload widget.Has anyone ever managed to perform actions like this using serenity screen play pattern.
Its really making us think of giving up serenity and just use cucumber-selenium framework as I can easily perform this using Upload.sendkeys(path);
Any help is much appreciated. Thanks in advance.
AS requested: Listing Steps:
public class ListingSteps
{
#Before
public void set_the_stage() {
OnStage.setTheStage(new OnlineCast());
}
#Given("^(.*) is able to click import products$") public void userIsAbleToClick(String actorName) throws Throwable
{
theActorCalled(actorName).wasAbleTo(Start.theApplication());
}
#When("^s?he imports a single item successfully$") public void heImportsASingleItemSuccessfully() throws Throwable
{
theActorInTheSpotlight().attemptsTo(Import.spreadsheet());
}
#Then("^(.*) are listed on ebay and amazon with all the right information$") public void itemsAreListedOnEbayAndAmazonWithAllTheRightInformation(String actorName, String SKU)
throws Throwable
{
//pending
}
Ignore then for now as its work in progress.
Import class:
public class Import implements Task
{
protected String path =
"C:\\somePathToFile\\populated_excel.xlsx";
public static Import spreadsheet()
{
return instrumented(Import.class);
}
#Override public <T extends Actor> void performAs(T actorName)
{
actorName.attemptsTo(Click.on(Products.ProductsScreen));
actorName.attemptsTo(Click.on(Products.Upload));
actorName.attemptsTo(Enter.theValue(path).into(Browse).thenHit(Keys.RETURN));//this is the line which is giving errors
actorName.attemptsTo(Click.on(Products.UploadButton));
}
}
Target Browse
public class Products
{
public static Target Browse = Target.the("browse file").locatedBy("//input[#type='file']");
}

Did you try removing these lines?
actorName.attemptsTo(Click.on(Products.ProductsScreen));
actorName.attemptsTo(Click.on(Products.Upload));
You don't need to open the upload file component, only write the file path directly to the input file element and perform the submit.

The way I managed to get this working was by using the FileToUpload class:
import net.thucydides.core.pages.components.FileToUpload;
FileToUpload fileToUpload = new FileToUpload(driver, fileName);
fileToUpload.fromLocalMachine().to(webElement);

I got this working with a simple:
import java.nio.file.*;
Path data = null;
try {
data = Paths.get(ClassLoader.getSystemResource(file).toURI());
} catch (URISyntaxException ignore) {}
ACTOR.attemptsTo(Upload.theFile(data).to(target));
file is an actual file that exists on your classpath, in src/test/resources if you have a Maven project.
target is something like:
Target.the("Image upload").located(By.xpath("//input[#type='file']"));

Related

Standalone Apache Camel application doesn' run

I'm on this problem: can't get my apache camel batch run. Here is the code:
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
public class Launch {
private Main main;
public static void main(String[] args) {
Launch l = new Launch();
System.out.println(System.getProperty("from") +" -> "+System.getProperty("to"));
try {
l.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute() throws Exception {
main = new Main();
main.enableHangupSupport();
main.addRouteBuilder(new FromFileToFile());
main.run();
}
private static class FromFileToFile extends RouteBuilder {
#Override
public void configure() throws Exception {
onException(Exception.class).handled(true).process(new Processor() {
public void process(Exchange arg0) throws Exception {
arg0.getException().printStackTrace();
}
});
from(System.getProperty("from") + "")
.filter(body().contains("DOTHIS"))
.process(new Processor() {
public void process(Exchange arg0) throws Exception {
System.out.println(arg0.getIn().getBody()
.toString());
}
}).to(System.getProperty("to"))
.to(System.getProperty("to") + ".BAK");
}
}
}
I don't want to use the Thread.sleep(...) workaround. I simply copied and modified the source stuff posted on this official docs page. When I run my dummy program using Eclipse, application simply hangs. I can't figure out what's wrong.
Your application doesn't probably hang, it just won't do anything. :)
You have defined filter that checks if Camel Message body contains word "DOTHIS". When you consume file with File consumer the body will be of type GenericFile. Then when your filter checks for that string it surely won't find it since the body is not string.
Solution: Convert file body to string first and then your filter will work and you get the result you were expecting. Conversion can be done like this
from(System.getProperty("from") + "")
.convertBodyTo(String.class, "UTF-8")
.filter(body().contains("DOTHIS"))
You might also want to increase logging level so you can get the grasp of what's going on in your route.
It was a problem about path. I passed arguments as options like this:
file://Users/francesco/..
As I'm using windows I must specify uri like this
file:///C:/Users/francesco/..
The batch doesn't hangs, it continues to poll directory for new files to consumes.

org.openide.util.Lookup Cannot Find Any Classes Implementing

SQLUtils.java:
import org.openide.util.Lookup;
import java.util.ServiceLoader; // This doesn't work either
public class SQLUtils {
public static DBDriver getDriver(String prefix) {
for(DBDriver e : Lookup.getDefault().lookupAll(DBDriver.class)) {
System.out.println(e.getPrefix());
if(e.getPrefix().equalsIgnoreCase(prefix)) {
return e;
}
}
return null;
}
}
MySQLDriver.java:
public class MySQLDriver implements DBDriver {
#Override
public String getPrefix() {
return "mysql";
}
}
DBDriver.java:
import java.io.Serializable;
public interface DBDriver extends Serializable {
public String getPrefix();
}
Main.java:
public class Main {
public static void main(String[] args) {
DBDriver d = SQLUtils.getDriver("mysql");
}
}
This does nothing when running it, it cannot find any classes implementing.
What the program is trying to do is get the driver that is entered as a parameter for SQLUtils.getDriver(String prefix) (in Main.java).
For some reason I cannot get this to work.
I'm not familiar with OpenIDE Lookup mechanism, but I am familiar with the Java ServiceLoader mechanism.
You need to provide a file in the META-INF/services/ folder describing what classes implement specific interfaces. From the Java Docs describing the ServiceLoader class is this example:
If com.example.impl.StandardCodecs is an implementation of the
com.example.CodecSet service then its jar file also contains a file
named
META-INF/services/com.example.CodecSet
This file contains the single line:
com.example.impl.StandardCodecs # Standard codecs implementing com.example.CodecSet
What you are missing is a similar file that needs to be included on your classpath or within your JAR file.
You don't include you package names so I cannot provide a more direct example to help solve your problem.
I dropped the NetBeans API and switched to Reflections. I implemented Maven and ran it with IntelliJ. Works well for me.

Open any file from within a java program

Opening files in java seems a bit tricky -- for .txt files one must use a File object in conjunction with a Scanner or BufferedReader object -- for image IO, one must use an ImageIcon class -- and if one is to literally open a .txt document (akin to double-clicking the application) from java, this code seems to work:
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("notepad Text.txt");
}
}
I'm not positive, but I think other file-types / names can be substituted in the parenthesis after exec -- anyway, I plan on opening certain files in a JFileChooser when the user clicks on a file to open (when the user clicks on a file, the path to the file can be obtained with the getSelectedFile() method). Though I'm more specifically looking to be able to open an Arduino file in the Arduino IDE from a java program, like a simulated double-click.. perhaps something like this?
import java.io.*;
public class LiterallyOpenFile {
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("Arduino C:\\Arduino\\fibonacci_light\\fibonacci_light.ino");
}
}
A point in the right direction would be appreciated.
Have you tried this? If there is a registered program for your file in windows, this should work. (i.e. the default application should open the file)
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
The file parameter is a File object.
Link to API
Link to use cases and implementation example of the Desktop class
This is what I do in my projects using java.awt.Desktop
import java.awt.Desktop;
import java.io.IOException;
import java.io.File;
public class Main
{
public static void main(String[] args) {
try {
Desktop.getDesktop().open(new File("C:\\Users\\Hamza\\Desktop\\image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Swing - How to double click a project file on Mac to open my application and load the file?

I have created a Mac Java Swing application, and i have set a file extension(*.pkkt) for it in the "Info.plist" file, so when double clicking that file it opens my application.
When i do that the program runs fine. Now i need to load the (*.pkkt) project in the program, but the file path is not passed as an argument to the main(...) method in Mac as happens in Windows Operating System.
After some search i found an Apple handling jar "MRJToolkitStubs" that has the MRJOpenDocumentHandler interface to handle such clicked files. I have tried using it to load that file by implementing that Interface in the main program class, but it is not working. The implemented method is never called at the program start-up.
How does this Interface run ?
------------------------------------------------- Edit: Add a Code Sample
Here is the code i am using :
public static void main( final String[] args ) {
.
.
.
MacOpenHandler macOpenHandler = new MacOpenHandler();
String projectFilePath = macOpenHandler.getProjectFilePath(); // Always Empty !!
}
class MacOpenHandler implements MRJOpenDocumentHandler {
private String projectFilePath = "";
public MacOpenHandler () {
com.apple.mrj.MRJApplicationUtils.registerOpenDocumentHandler(this) ;
}
#Override
public void handleOpenFile( File projectFile ) {
try {
if( projectFile != null ) {
projectFilePath = projectFile.getCanonicalPath();
System.out.println( projectFilePath ); // Prints the path fine.
}
} catch (IOException e) {}
}
public String getProjectFilePath() {
return projectFilePath;
}
}
As mentioned in the comment above "getProjectFilePath()" is always Empty !
On Java 9, use Desktop.setOpenFileHandler()
The proprietary com.apple.eawt packages have been removed from recent versions of Java and has been incorporated into various methods in the Desktop class. For your specific example:
import java.awt.desktop.OpenFilesHandler;
import java.awt.desktop.OpenFilesEvent;
import java.io.File;
import java.util.List;
public class MyOpenFileHandler implements OpenFilesHandler {
#Override
public void openFiles​(OpenFilesEvent e) {
for (File file: e.getFiles​()) {
// Do whatever
}
}
}
Then elsewhere, add this:
Desktop.getDesktop().setOpenFileHandler(new MyOpenFileHandler());
The OpenFilesEvent class also has a getSearchTerm() method. Say that a person used Spotlight on macOS to search for the word "StackOverflow", then decided to open up a document. With this method, can you determine that "StackOverflow" was the word they searched for, and choose to do something with that (perhaps highlight the first occurrence of the word).
You're going to want to use the Apple Java Extensions.
They should be included in any JDK that runs on Mac OS X, but the documentation is kind of hard to get. See this answer for more details.
Specifically, you'll want to make an OpenFilesHandeler.
This code snippet should work:
import com.apple.eawt.event.OpenFilesHandeler;
import com.apple.eawt.event.AppEvent;
import java.io.File;
import java.util.List;
class MacOpenHandler implements OpenFilesHandeler {
#Override
public void openFiles(AppEvent.OpenFilesEvent e) {
List<File> files = e.getFiles();
// do something
}
}
And somewhere:
import com.apple.eawt.Application;
...
MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);

how to store java.util.prefs.Preferences in file?

I'm using java.util.prefs.Preferences for application preferences.
And I need ability to edit those preferences manually.
Is it possible to store it into file instead of Windows Registry?
Or I should use another mechanism instead of java.util.prefs.Preferences?
If you want to continue using the Preferences API, but write to a file, you will need a new PreferencesFactory, as detailed in this SO post.
You are going to want to use the following two method :
Preferences.exportSubtree(OutputStream os)
and
Preferences.importPreferences(InputStream is)
This code should help you [http://java.sun.com/developer/technicalArticles/releases/preferences/]:
public class PrefSave {
private static final String PACKAGE = "/pl/test";
public static void main(String[] args) {
doThings(Preferences.systemRoot().node(PACKAGE));
doThings(Preferences.userRoot().node(PACKAGE));
}
public static void doThings(Preferences prefs) {
prefs.putBoolean("Key0", false);
prefs.put("Key1", "Value1");
prefs.putInt("Key2", 2);
Preferences grandparentPrefs = prefs.parent().parent();
grandparentPrefs.putDouble("ParentKey0", Math.E);
grandparentPrefs.putFloat("ParentKey1", (float) Math.PI);
grandparentPrefs.putLong("ParentKey2", Long.MAX_VALUE);
String fileNamePrefix = "System";
if (prefs.isUserNode()) {
fileNamePrefix = "User";
}
try {
OutputStream osTree = new BufferedOutputStream(
new FileOutputStream(fileNamePrefix + "Tree.xml"));
grandparentPrefs.exportSubtree(osTree);
osTree.close();
OutputStream osNode = new BufferedOutputStream(
new FileOutputStream(fileNamePrefix + "Node.xml"));
grandparentPrefs.exportNode(osNode);
osNode.close();
} catch (IOException ioEx) {
// ignore
} catch (BackingStoreException bsEx) {
// ignore too
}
}
Try the following class which allows you to use some simple put() and get() functions using a local configuration.xml file.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
public class SimpleProperties
{
private String propertiesFilePath;
private Properties properties;
public SimpleProperties() throws InvalidPropertiesFormatException, IOException
{
propertiesFilePath = "configuration.xml";
properties = new Properties();
try
{
properties.loadFromXML(new FileInputStream(propertiesFilePath));
} catch (InvalidPropertiesFormatException e)
{
}
}
public void put(String key, String value) throws FileNotFoundException, IOException
{
properties.setProperty(key, value);
store();
}
public String get(String key)
{
return properties.getProperty(key);
}
private void store() throws FileNotFoundException, IOException
{
String commentText = "Program parameters";
properties.storeToXML(new FileOutputStream(propertiesFilePath), commentText);
}
}
It is explained in another post, here
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close()
I think you can use property files instead. They are stored in the file system. You can define the path you want. And you can edit it by hand. See this question for more details.
A while back I had to come up with an implementation of the Preferences class that would read settings from but not write to the registry. I derived a ReadOnlyPreferences class from AbstractPreferences to accomplish this. Later, I needed this exact same functionality you require to go to/from files. I just extended my ReadOnlyPreferences class to override sync() and flush() to keep the file in sync. The cool part about this it would use the exact same logic to apply defaults to the values just like the usual use of the prefs since nothing actually existed in the registry to read. I kept the file in sync by using exportSubtree() and importPreferences() from the base class to do all the heavy lifting for me.
I am sorry I cannot post the code as I don't own it but I used the encrypted preferences stuff you can find at the following link as a start point. That's what I did and it took me about an hour to distill it down to just what I needed which was mainly throwing code away which is much easier than writing code! It is also published in Dr Dobbs at the following link if you don't want to click on the first one. I just never saw an easy place on the dobbs article to download the entire source. Regardless, the article is the best I've seen for extending the preferences stuff.
http://www.panix.com/~mito/articles/#ep
http://www.drdobbs.com/security/encrypted-preferences-in-java/184416587?pgno=4

Categories