I must check downloaded PDF and open it using Selenium. For that, I am using Robot class. This is not the permanent or we can say general solution of this.
Question : Can anyone please help and provide more reliable solution for the same ?
Please find below code:
public boolean CommonEvents(WebDriver driver) throws InterruptedException {
try {
Thread.sleep(2000);
Robot robot = new Robot();
robot.mouseMove(100, 700);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(10000);
} catch(Exception e) {
BaseTest.reportPass(driver, null, "Should click on PDF to open", "Failed to click on PDF to open");
}
}
Just in case you really need to open every downloaded PDF then I would simply add this line to your preferences (e.g. for Firefox):
ffprofile.setPreference("browser.helperApps.neverAsk.openFile", "application/pdf");
Then it will automatically open the downloaded file after finishing the download.
You can use something similar to this if you have a fixed directory where you are saving the downloaded pdf files .
public static void main(String[] args) {
try {
File pdfFile = new File("c:\\Hello.pdf");
if (pdfFile.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(pdfFile);
} else {
System.out.println("Awt Desktop is not supported.");
}
} else {
System.out.println("File doesn't exists.");
}
System.out.println("File opened.");
} catch (Exception ex) {
ex.printStackTrace();
}
}
Reference : https://docs.oracle.com/javase/6/docs/api/java/awt/Desktop.html
We use below logic:
First set preference for a download location, so that the file will be downloaded to your desired location.
chromePrefs.put("download.default_directory", downloadFilepath);
Set Preference so that it won't ask the pop to download.
chromePrefs.put("profile.default_content_settings.popups", 0);
As #Mudit_ has answered check for the *.pdf with regex pattern, if you want to make it dynamic.
Related
Attempting to have a button in my Java GUI open a PDF. My PDF is in the src folder, the same folder where my code is but I get a 'file not found' error and am unsure what is wrong with my pathing.
aboutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
try {
File aboutPDF = new File("./aboutGUI.pdf");
Desktop.getDesktop().open(aboutPDF);
} catch (Exception ex) {
System.out.println(ex);
}
}
}
});
You'll have to put it in your resources folder as that is where your IDE looks by default for files unless specified otherwise. Then do "filename.pdf" or "src/main/resources/filename.pdf"
I'm making plugin for eclipse which opens frame with some table's when plugin command is activated. Now I want to add help file to plugin's frame, so that when clicked on help file's link in frame, file opens (executes). File is suppose to be part of plugin. My problems are:
Don't know how to make link and add it to frame.
Don't know how to locate that file in plugin from run time application.
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
/* Add code for opening file from plugin.*/
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
Found this code somewhere, now I need to implement link, any thoughts?
If i understand you question correct, something like this should work:
JLabel lblFileLink = new JLabel("Help");
lblFileLink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblFileLink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
java.awt.Desktop.getDesktop().edit(INSERTYOURFILEHERE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
This will open the standard text editor and show your file. Just replace INSERTYOURFILEHERE with your own text file.
Edit: If you want to open it in Eclipse maybe look at this
Edit2: The gist of the link above:
File fileToOpen = new File("externalfile.xml");
if (fileToOpen.exists() && fileToOpen.isFile()) {
IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditorOnFileStore( page, fileStore );
} catch ( PartInitException e ) {
//Put your exception handler here if you wish to
}
} else {
//Do something if the file does not exist
}
I'm running a series of automated GUI tests using Selenium in Java. These tests regularely takes screenshots using:
public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
} catch(Exception e) {
e.printStackTrace();
}
}
This works excellently in Chrome and IE, however in firefox I keep getting large pieces of whitespace under the screenshots. I suspect that the whitespace is actually a part of the page itself, but normally hidden from view in the browser(the scrollbar stops before the whitespace). I did a quick test with
driver.get("http://stackoverflow.com/");
takeScreenshot("D:\\TestRuns\\stackoverflow.png", driver);
and found that when using the Firefox driver the entire page in captured in the screenshot, while with the Chrome driver only what's shown in the browser is captured.
Is there any way to force the Firefox driver to take a screenshot containing ONLY what can actually be seen in the browser (what an actual user would see)?
Based on answers from this question I was able to add 4 lines of code to just crop the image down to the browser size. This does solve my problem, although it would have been nicer if it could be solved through the driver instead of cropping after the screenshot has been taken.
public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
int height = driver.manage().window().getSize().getHeight();
BufferedImage img = ImageIO.read(scrFile);
BufferedImage dest = img.getSubimage(0, 0, img.getWidth(), height);
ImageIO.write(dest, "png", scrFile);
FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
} catch(Exception e) {
e.printStackTrace();
}
}
Try this :
private static void snapshotBrowser(TakesScreenshot driver, String screenSnapshotName, File browserFile) {
try {
File scrFile = driver.getScreenshotAs(OutputType.FILE);
log.info("PNG browser snapshot file name: \"{}\"", browserFile.toURI().toString());
FileUtils.deleteQuietly(browserFile);
FileUtils.moveFile(scrFile, browserFile);
} catch (Exception e) {
log.error("Could not create browser snapshot: " + screenSnapshotName, e);
}
}
Hey Guys I did a little App, where I type into a textbox a specific value (height, weight) and save it into a file.
I did this but I do not know, which path I have to use for Android.
Hope you can help :)
public void SaveList(View view) {
//Pf`enter code here`ad, im privaten Speicherbereich
File file = new File("I need this path :)");
try {
OutputStreamWriter fdg = new OutputStreamWriter(new FileOutputStream(file));
fdg.write(""+this.weight);
fdg.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can use Environment.getDataDirectory() to get the root directory, if you dont have an SD card.
If you have an SD card, use Environment.getExternalStorageState()
Read more about them in the docs
Thus, change your code as follows
File file = new File(Environment.getDataDirectory()+"/your_folder_name/your_file_name");
This will create a file with name your_file_name in the folder your_folder_name in your internal storage.
Sound does not play when I run the JAR, but it does when I run it in eclipse.
Here is where I load the clips:
public void init(){
System.out.println("grabbing Music");
String currentDir = new File("").getAbsolutePath();
name=new File(currentDir+"\\music\\").list();
clip=new Clip[name.length];
soundFile=new File[name.length];
for(int x=0;x<name.length;x++){
System.out.println(currentDir+"\\music\\"+name[x]);
try {
soundFile[x]= new File(currentDir+"\\music\\"+name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile[x]);
DataLine.Info info= new DataLine.Info(Clip.class, sound.getFormat());
clip[x] = (Clip) AudioSystem.getLine(info);
clip[x].open(sound);
clip[x].addLineListener(new LineListener(){
public void update(LineEvent event) {
if (event.getType() == LineEvent.Type.STOP) {
event.getLine().close();
}
}
});
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
}
I do not get any errors when running it in Eclipse. There should be no possibility of an invalid directory error, so what is wrong?
-When the jar is run in CMD i get no errors.
edit: I feel like I am loading the audio wrong, hence why I pasted the code I used to load the files in. In my searches I haven't seen anyone use File to load in a sound file. Wonder if that is the problem?
First thing that goes into my mind is that you didn't attached your sound library classes into your jar.
In order to run your current code, the folder music should be in the same folder the jar file is located in.
Another solution is to package your music folder inside the jar file and then change your code to:
InputStream is = getClass().getResourceAsStream("/music/" + name[x]);
AudioInputStream sound = AudioSystem.getAudioInputStream(is);
How about-
Right click on your project in Eclipse. Then New -> Source Folder.
Name the source folder anything. e.g. music_src.
Copy or drag the entire music directory in music_src. Then make the jar.
File systems have a hard time looking into jars.
Try using URL instead. A URL can locate a location within a jar. This happens a lot with folks trying to access resources in jars for the first time.
Otherwise things look fine.