Unable to save screenshots in the designated path or attach the screen shot to extentreports in MAC - macos

I have tried many ways to take screenshot on test case failure but nothing works. unable to take a screenshot and attach it to extentreport in MAC os while using selenium.
public void onTestFailure(ITestResult tr)
{
logger=extent.createTest(tr.getName()); // create new entry in the report
logger.log(Status.FAIL,MarkupHelper.createLabel(tr.getName(),ExtentColor.RED)); // send the passed information to the report with GREEN color highlighted
String screenshotPath="./Stest-output/"+tr.getName()+".png";
TakesScreenshot ts = (TakesScreenshot)driver;
File img =ts.getScreenshotAs(OutputType.FILE);
File destination =new File(screenshotPath);
try {
FileUtils.copyFile(img,destination);
logger.addScreenCaptureFromPath(screenshotPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(img != null)
{
System.out.println("Screenshot is below:"+tr.getName());
try {
logger.info("Screenshot is below:" + logger.addScreenCaptureFromPath(screenshotPath));
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
throws null pointer exception when trying to copy the image from source to destination.
Have all the methods available in stack overflow.

You are unable to attach screenshot into extent report html because you forget to call flush() method that appends the report HTML file with all the tests result/screenshots. There must be at least one ended test for anything to be appended to the report.
Note: If flush() is called before any of the ended tests, no information will be appended to report.
#AfterTest
public void tearDown() {
extent.flush();

Related

Chromecast receiver using sendLoadComplete() doesn't update status

I'm writing a Chromecast receiver to play different kind of contents (including embedded flash videos). I'd like to use my own JS library to create the player canvas, not to rely on the html video element.
I'm currently blocked because I can't get a media to be loaded using a custom behaviour :
Receiver :
Nothing fancy in the HTML, I just load my library in the #mediaWrapper div. Then I create a MediaManager from it.
var node = $( "#mediaWrapper" )[0];
var phiEngine = new phi.media.Player( node );
window.mediaManager = new cast.receiver.MediaManager( phiEngine );
window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
/* Override Load method */
window.mediaManager['origOnLoad'] = window.mediaManager.onLoad;
window.mediaManager.onLoad = function (event) {
console.log('### Application Load ', event);
/* Custom code (load lib, set metadata, create canvas ...) */
window.mediaManager.sendLoadComplete(); // Doesn't seem to do anything
// window.mediaManager['origOnLoad'](event);
// -> Fails 'Load metadata error' since url is not a video stream
// -> ex: youtube url
}
/* Will never be called */
window.mediaManager['origOnMetadataLoaded'] = window.mediaManager.onMetadataLoaded;
window.mediaManager.onMetadataLoaded = function (event) {
...
}
Sender :
I use my own android application to cast to the device. I can't use the Companion library because it will be a Titanium module.
private void createMediaPlayer() {
// Create a Remote Media Player
mRemoteMediaPlayer = new RemoteMediaPlayer();
mRemoteMediaPlayer.setOnStatusUpdatedListener(
new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
Log.e(TAG, "onStatusUpdated");
}
}
});
mRemoteMediaPlayer.setOnMetadataUpdatedListener(
new RemoteMediaPlayer.OnMetadataUpdatedListener() {
#Override
public void onMetadataUpdated() {
Log.e(TAG, "onMetadataUpdated");
}
});
try {
Cast.CastApi.setMessageReceivedCallbacks(mApiClient,
mRemoteMediaPlayer.getNamespace(), mRemoteMediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating media channel", e);
}
mRemoteMediaPlayer
.requestStatus(mApiClient)
.setResultCallback(
new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(MediaChannelResult result) {
Log.e(TAG, "Request status : ", result.toString());
if (!result.getStatus().isSuccess()) {
Log.e(TAG, "Failed to request status.");
}
}
});
}
private void loadMedia( MediaInfo mediaInfo, Boolean autoplay ) {
try {
mRemoteMediaPlayer.load(mApiClient, mediaInfo, autoplay)
.setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(MediaChannelResult result) {
Log.e(TAG, "loadMedia ResultCallback reached");
if (result.getStatus().isSuccess()) {
Log.e(TAG, "Media loaded successfully");
} else {
Log.e(TAG, "Error loading Media : " + result.getStatus().getStatusCode() );
}
}
});
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
}
}
Expected behaviour :
I basically first call createMediaPlayer() once, then call loadMedia(...). The first call to loadMedia will show nothing in the log : nor success or fail. Next calls issue with errorCode 4.
I get the load event on the receiver side. But, back to the sender side, I can't manage to end the load phase and get a media session to be created.
I was expecting sendLoadComplete() to do so but I might be wrong. How can I have the media status to update and the loadMedia ResultCallback to be reached ?
My goal is to use RemoteMediaPlayer.play(), pause(), ... but for now I get stuck with 'No current media session' because the media isn't loaded yet.
Also, I'd really enjoy to be able to log any message the Sender receives, before being processed. Is it possible ?
Hope I did not forget any information,
Thanks for your help !
edit: I solved this by using a custom message channel since it seems that I can't use RemoteMediaPlayer the way I want to.
I believe the error code 4 you are receiving is bogus; see https://plus.google.com/u/0/+JimRenkel2014/posts/aY5RP7X3QhA . As noted there, I created a Chromecast issue for this (https://code.google.com/p/google-cast-sdk/issues/detail?id=305&thanks=305&ts=1403833532). Additional support for this issue will help it get fixed faster! :-)
.sendLoadComplete(true)
The boolean value helped me to receive the loaded event on sender. Might help you as well.

BlueJ picture in jar

I've just finished a GUI project and I want to figure out how to get an image that I reference into the completed jar file. As of right now I just reference it as:
try {
img = ImageIO.read(new File("<name>.png"));
} catch (IOException e) {
}
in my project.
What do I need to do to get it to show up in my program?
By the time of Jarring, those resources will have become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.
General Tip
Change code of the form
catch (Exception e) {
// ..
To:
catch (Exception e) {
e.printStackTrace(); // very informative!
// ..

BIRT csv emitter and EJB

I want to use csv emitter plugin in a Java EE application. Is it possible? I get the following error:
org.eclipse.birt.report.engine.api.UnsupportedFormatException: The output format csv is not supported.
at org.eclipse.birt.report.engine.api.impl.EngineTask.setupRenderOption(EngineTask.java:2047)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:96)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
My code:
protected String generateReportFile(IRunAndRenderTask task, IReportRunnable design, IReportEngine engine, String reportType, String reportPrefix, String baseDir) throws BirtReportGenerationFault {
CSVRenderOption csvOptions = new CSVRenderOption();
csvOptions.setOutputFormat(CSVRenderOption.OUTPUT_FORMAT_CSV);
csvOptions.setOutputFileName("C:/birt/logs/csvTestW.csv");
csvOptions.setShowDatatypeInSecondRow(false);
csvOptions.setExportTableByName("data");
csvOptions.setDelimiter("\t");
csvOptions.setReplaceDelimiterInsideTextWith("-");
task.setRenderOption(csvOptions);
task.setEmitterID("org.eclipse.birt.report.engine.emitter.csv");
try {
task.run();// Error here
} catch (EngineException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
task.close();
return "C:/birt/logs/csvTestW.csv";//fileName;
}
Same code works in a Java SE app.
I had the same problem, but with the pdf format. I solved it by adding org.eclipse.birt.report.engine.emitter.pdf to the plugin Dependencies.
I think the problem here is case of output format passed to in CSVRenderOptions.
instead of using csvOptions.setOutputFormat(CSVRenderOption.OUTPUT_FORMAT_CSV);
try using csvOptions.setOutputFormat("CSV");

how to prevent hadoop job to fail on corrupted input file

I'm running hadoop job on many input files.
But if one of the files is corrupted the whole job is fails.
How can I make the job to ignore the corrupted file?
maybe write for me some counter/error log but not fail the whole job
It depends on where your job is failing - if a line is corrupt, and somewhere in your map method an Exception is thrown then you should just be able to wrap the body of your map method with a try / catch and just log the error:
protected void map(LongWritable key, Text value, Context context) {
try {
// parse value to a long
int val = Integer.parseInt(value.toString());
// do something with key and val..
} catch (NumberFormatException nfe) {
// log error and continue
}
}
But if the error is thrown by your InputFormat's RecordReader then you'll need to amend the mappers run(..) method - who's default implementation is as follows:
public void run(Context context) {
setup(context);
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
cleanup(context);
}
So you could amend this to try and catch the exception on the context.nextKeyValue() call but you have to be careful on just ignoring any errors thrown by the reader - an IOExeption for example may not be 'skippable' by just ignoring the error.
If you have written your own InputFormat / RecordReader, and you have a specific exception which denotes record failure but will allow you to skip over and continue parsing, then something like this will probably work:
public void run(Context context) {
setup(context);
while (true) {
try {
if (!context.nextKeyValue()) {
break;
} else {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
} catch (SkippableRecordException sre) {
// log error
}
}
cleanup(context);
}
But just to re-itterate - your RecordReader must be able to recover on error otherwise the above code could send you into an infinite loop.
For your specific case - if you just want to ignore a file upon the first failure then you can update the run method to something much simpler:
public void run(Context context) {
setup(context);
try {
while (context.nextKeyValue()) {
map(context.getCurrentKey(), context.getCurrentValue(), context);
}
cleanup(context);
} catch (Exception e) {
// log error
}
}
Some final words of warning:
You need to make sure that it isn't your mapper code which is causing the exception to be thrown, otherwise you'll be ignoring files for the wrong reason
GZip compressed files which are not GZip compressed will actually fail in the initialization of the record reader - so the above will not catch this type or error (you'll need to write your own record reader implementation). This is true for any file error that is thrown during record reader creation
This is what Failure Traps are used for in cascading:
Whenever an operation fails and throws an exception, if there is an associated trap, the offending Tuple is saved to the resource specified by the trap Tap. This allows the job to continue processing without any data loss.
This will essentially let your job continue and let you check your corrupt files later
If you are somewhat familiar with cascading in your flow definition statement:
new FlowDef().addTrap( String branchName, Tap trap );
Failure Traps
There is also another possible way. You could use mapred.max.map.failures.percent configuration option. Of course this way of solving this problem could also hide some other problems occurring during map phase.

File being used by another process in a Windows Service with a StreamReader

I have searched numerous articles and tried several different ways of solving this issue.
Note that this process works fine in a Console app or a Windows app with the exact same code. So, there's nothing wrong with the logic. It's the way the Windows Service is processing these files that is somehow not letting subsequent files get through.
I tried reading a simple article to actually debug the service, but I don't have the "Attach To Process" selection under my Debug menu using Visual Studio 2010.
http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.100).aspx
I really need some help here, because my options have really run out.
Here is the simple scenario:
I have a FileSystemWatcher in the OnStart method that kicks off another method to process a file on my local machine. These are just simple txt files. When the first file is processed, everything is normal and I get the following in my Event log:
Data successfully inserted for file 20121212_AZM_Journey_MIS.txt
When I try and process subsequent files (exact same format, but a different name --- with the date), I get the following in my Event log:
The process cannot access the file 'C:\Projects\Data\VendingStats\20121213_AZM_Journey_MIS.txt' because it is being used by another process.
Note that the files are watched for in this same directory when created.
Here is my code in my Windows Service. Can someone please let me know how I can solve this issue? Note that e.FullPath evaluates to "C:\Projects\Data\VendingStats" on my local machine.
public partial class VendingStatsService : ServiceBase
{
public VendingStatsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Projects\Data\VendingStats");
Watcher.EnableRaisingEvents = true;
Watcher.Created += new FileSystemEventHandler(**Watcher_Created**);
Watcher.Filter = "*.txt";
Watcher.IncludeSubdirectories = false;
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
try
{
using (TextReader tr = new StreamReader(e.FullPath))
{
// code here to insert data from file into a DB
}
Dispose();
}
catch (Exception ex)
{
EventLog.WriteEntry("VendorStats", "Error in the Main:" + "\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.InnerException);
return;
}
}
public void Dispose()
{
GC.Collect();
}

Resources