I am able generate the extent reports with screenshots on my local machine.
But when i mail the reports to someone else, or open the html on a differant machine, the screenshots are not visible. It says that the path is invalid.
While attaching the screenshot, i am giving the path of my local machine. And it is searching the same path on other machine too.
I tried zipping the html and pics in one folder too.
Please help me how to attach the screenshots into html file without local machine dependency.
You can do this by using base64 conversion of the obtained screenshots.
Use the following code in your framework and try it.
public static String addScreenshot() {
File scrFile = ((TakesScreenshot) BasePage.driver).getScreenshotAs(OutputType.FILE);
String encodedBase64 = null;
FileInputStream fileInputStreamReader = null;
try {
fileInputStreamReader = new FileInputStream(scrFile);
byte[] bytes = new byte[(int)scrFile.length()];
fileInputStreamReader.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "data:image/png;base64,"+encodedBase64;
}
I faced same issue.
Share the folder in which you are storing the screenshots with everyone and return same path in below method.
public static String getScreenshot(WebDriver oDriver, String ScreenShotName) throws IOException
{
String dateName=new SimpleDateFormat("YYYYMMDDHHMMSS").format(new Date());
TakesScreenshot ts=(TakesScreenshot)oDriver;
File source=ts.getScreenshotAs(OutputType.FILE);
String destination=System.getProperty("user.dir")+"/FailedScreenshots/"+ScreenShotName+dateName+".png";
File finalDestination=new File(destination);
FileUtils.copyFile(source, finalDestination);
String Imagepath="file://Machinename/FailedScreenshots/"+ScreenShotName+dateName+".png";
return Imagepath;
}
Hope this helps!
Related
I'm trying to open different types of files using webdriver(.txt and pdf). So I have the files in the resources folder but when I open them I get the following error message: malformed exception
But if I open the file from my desktop it works perfectly fine:
So for example this is what I have:
String file_loc = logInPage.getFile(file_name);
logInPage.navigateToFileLoc(file_location);
These are the implementation of the two methods
public String getFile(String fileName) {
String result = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
result = IOUtils.toString(classLoader.getResourceAsStream(fileName), java.nio.charset.StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public void navigateToFileLoc(String fileLoc){
webDriver.get(fileLoc);
}
But when I try to get the file from the desktop it works perfectly fine:
For example webDriver.get("file:///C:/Users/test.pdf")
It's like as if you are trying to open a pdf or html in an IDE
Can you please change the getFile method as follow :
public String getFile(String fileName) {
String filePath = null;
ClassLoader classLoader = getClass().getClassLoader();
try {
filePath= classLoader.getResource(fileName).getPath();
} catch (Exception e) {
e.printStackTrace();
}
return "file://"+filePath;
}
This is the code
public static void readCharacters() {
try (FileInputStream fi = new FileInputStream("main/characters.dat"); ObjectInputStream os = new ObjectInputStream(fi)) {
characterList = (LinkedList<Character>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is the structure:
And this is the Error
java.io.FileNotFoundException: main\characters.dat (The system cannot find the path specified)
What I want is to include the characters.dat file in my jar, and be able to read and write it while the program runs. Is there a different way to write the path? or to put the .dat file in a different position.
Also the writing method:
public static void writeCharacters() {
try (FileOutputStream fs = new FileOutputStream("main/characters.dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing Characters...");
os.writeObject(characterList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can't. You can do one or the other. JAR files are not file systems, and their entries are not files. You can read it with an input stream:
InputStream in = this.getClass().getResourceAsStream("/main/characters.dat");
Check it for null before proceeding.
The jar is for read-only resources. You can use it for the initial file, as a kind of template.
Path path = Paths.get(System.getProperty("user.home") + "/myapp/chars.dat");
Files.mkdirs(path.getParentPath());
if (!Files.exists()) {
try (InputStream in =
Controller.class.getResourceAsStream("/main/characters.dat")) {
Files.copy(in, path);
}
}
The above copies the initial.dat resource from the jar to the user's home "myapp" directory, which is a common solution.
System.getProperty("user.dir") would the running directory. One can also take the jar's path:
URL url = Controller.class.getResource("/main/characters.dat");
String s = url.toExternalForm(); // "jar:file:/.... /xxx.jar!/main/characters.dat"
From that you can also construct the jar's directory. Mind to check Windows, Linux, spaces and such.
URL url = Controller.class.getProtectionDomain().getCodeSource().getLocation();
The solution above risks a NullPointerException, and works a bit differenly running inside the IDE or stand-alone.
Important note:
When using getResourceAsStream, you must start your path by slash /, this specifies the root of your jar, .getResourceAsStream("/file.txt");
In my case my file was a function argument, String filename, I had to do it like this:
InputStream in = this.getClass().getResourceAsStream("/" + filename);
I have coded a AJAX file upload feature in my application. It works perfectly when running it from my laptop. When I try the exact same file using the same app, but deployed on a jBoss server, I get the following exception:
2013-02-18 11:30:02,796 ERROR [STDERR] java.io.FileNotFoundException: C:\Users\MyUser\Desktop\TestFile.pdf (The system cannot find the file specified).
getFileData method:
private byte[] getFileData(File file) {
FileInputStream fileInputStream = null;
byte[] bytFileData = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (fileInputStream != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytBuffer = new byte[1024];
try {
for (int readNum; (readNum = fileInputStream.read(bytBuffer)) != -1;) {
byteArrayOutputStream.write(bytBuffer, 0, readNum);
}
} catch (IOException e) {
e.printStackTrace();
}
bytFileData = byteArrayOutputStream.toByteArray();
}
return bytFileData;
}
Getting the file content in a variable (from the method above):
byte[] bytFileData = this.getFileData(file);
Making the file:
private boolean makeFile(File folderToMake, File fileToMake, byte[] bytFileData) {
Boolean booSuccess = false;
FileOutputStream fileOutputStream = null;
try {
if (!folderToMake.exists()) {
folderToMake.mkdirs();
}
if (!fileToMake.exists()) {
if (fileToMake.createNewFile() == true) {
booSuccess = true;
fileOutputStream = new FileOutputStream(fileToMake);
fileOutputStream.write(bytFileData);
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
booSuccess = false;
}
return booSuccess;
}
Any idea?
Thank you
Charles
It seems you're just passing the file path as part of the request to the server, not actually uploading the file, then attempting to use that file path to access the file.
That will work on your laptop because the code, when running locally, has access to your file system and will be able to locate the file. It won't work deployed on a server because it's an entirely separate machine, and as a result won't have access to your file system.
You'll need to modify your client-side (AJAX) code to actually upload the file, then modify your server-side code to use that uploaded file. Note that AJAX file uploads aren't generally possible - there are plugins for frameworks such as jQuery that provide this functionality using workarounds.
I'm not 100%, but I think proper AJAX file uploads may be possible using HTML5 features, but browser support for that is likely going to be pretty poor right now.
I've hosted a text file which I would like to load into a string using java.
My code doesn't seem to work producing errors, any help?
try {
dictionaryUrl = new URL("http://pluginstudios.co.uk/resources/studios/games/hangman/dictionary.dic");
} catch (MalformedURLException catchMalformedURLException) {
System.err.println("Error 3: Malformed URL exception.\n"
+ " Dictionary failed to load.");
}
// 'Dictionary' scanner setting to file
// 'src/Main/Dictionary.dic'
DictionaryS = new Scanner(new File(dictionaryUrl));
System.out.println("Default dictionary loaded.");
UPDATE 1: The file doesn't seem to load going to the catch. But the file exists.
You could do something that this tutorial does
public class WebPageScanner {
public static void main(String[] args) {
try {
URLConnection connection =
new URL("http://java.net").openConnection();
String text = new Scanner(
connection.getInputStream()).
useDelimiter("\\Z").next();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You need to use HttpClient and retrieve the data as a string or string buffer.
then use parse or read as file.
Something like this should work in your case:
DictionaryS = new Scanner(dictionaryUrl.openStream());
JavaDoc tells us:
File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
We can't create and use a File instance for any other resource type (like http).
I have a saved a file in the root folder and am trying to open it in a webview.
This is my code for saving:
OutputStream outstream = null;
outstream = openFileOutput(fileName ,MODE_WORLD_READABLE);
/// if file the available for writing
if (outstream != null) {
/// prepare the file for writing
OutputStreamWriter outputreader = new OutputStreamWriter(outstream);
BufferedWriter buffwriter = new BufferedWriter(outputreader);
/// write the result into the file
buffwriter.write(result);
}
/// close the file
outstream.close();
} catch (java.io.FileNotFoundException e) {
System.out.println("File not found in the writing...");
} catch (IOException e) {
System.out.println("In the writing...");
}
This is my code for recalling the file:
fileView.getSettings().setJavaScriptEnabled(true);
fileView.loadUrl("file:///" + name); <---
and inside the app it gives me a file not found error.
Any insight is helpful.
WebView mWebView=(WebView)findViewById(R.id.mWebView);
mWebView.loadUrl("file:///book.html");
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSaveFormData(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.setWebViewClient(new MyWebViewClient());
private class MyWebViewClient extends WebViewClient
{
#Override
//show the web page in webview but not in web browser
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl (url);
return true;
}
}
try this
Actually when you open a URL using file:///...
Then it means that you should save the file under assets directory (say test.html ).
Now suppose you have to access test.html file, you need to write like this
loadURL("file:///android_asset/test.html');
The path is wrong, assuming the exceptions weren't hit.
file:/// tells the browser to look for /name
openFileOutput(fileName) tells the app to write in <application-files-directory>/fileName
Your url should be "file:///"+getFilesDir()+File.separator+fileName
For files that will be bundled with the application you can add an "asset" folder to your project by right clicking your app in the project explorer then select
New=> Folder=> Assets Folder.
Add the HTML file to your asset folder then load it by:
fileView.loadUrl("file:///android_asset/"+name);
same URL can be used in your HTML to link to other HTML or CSS files.
You can read your asset file first and then display it on webview via asd
like this
BufferedReader read = null;
StringBuilder data = new StringBuilder();
try {
read = new BufferedReader(new InputStreamReader(getAssets().open("htmlFile.html"), "UTF-8"));
String webData;
while ((mLine = read.readLine()) != null) {
data.append(mline);
}
} catch (IOException e) {
log(",e.getmessage()) } finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log(",e.getmessage())
}
}
}
and then load this data in webview
webview.loadData(data, "text/html", "UTF-8");
Please refer to the youtube video https://youtu.be/n2KbDqoCv_Q?t=173
I've tested its solution and it works.