Saving Screenshot file - webdriver

My code for saving screenshot file is:
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\screenshots\\"+Filename+".jpg"));
The Error is :
The method copyFile (File, File)is undefined for the type FileUtil
I use an EventFiringWebDriver . Any ideas on this.

There are two possible explanations.
The error message you provided mentions FileUtil class instead of FileUtils You may have used wrong class by mistake.
Assuming you are using the correct FileUtils class you may have imported wrong package. Make sure that you have imported org.apache.commons.io.FileUtils

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
I guess you missed one or more of these imports.. The code given above works fine for me with these includes.

Plz put the exception then it will work fine.
EG: public static void main(String[] args) throws IOException

public class Testscreenshot {
public static void main(String[] args) throws IOException {
System.out.println("Images saved ..");
WebDriver driver = new FirefoxDriver();
driver.get("https://google");
File scrFile;
scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
org.apache.commons.io.FileUtils.copyFile(scrFile, new File("C:\\Users\\R&D\\Desktop\\Tulas\\Javafiles\\testimages.png"));
driver.quit();
}
}

Use import org.apache.commons.io.FileUtils.
This imports the FileUtils class you need.

Related

error: cannot find symbol FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());

I'm using flutter , and I tried to use Native Ads following this doc
all ads are working fine but Native ad doesn't work and it fails building the app showing this error
error: cannot find symbol FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());
this is MyActivity.java file :
package tech.devm.movies_torrent;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.formats.UnifiedNativeAdView;
import io.flutter.plugins.firebaseadmob.FirebaseAdMobPlugin.NativeAdFactory;
import java.util.Map;
public class MainActivity extends FlutterActivity {
#Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
flutterEngine.getPlugins().add(new FirebaseAdMobPlugin());
FirebaseAdMobPlugin.registerNativeAdFactory(flutterEngine, "moviesTorrentAdFactory", NativeAdFactoryExample());
}
#Override
public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
FirebaseAdMobPlugin.unregisterNativeAdFactory(flutterEngine, "moviesTorrentAdFactory");
}
}
class NativeAdFactoryExample implements NativeAdFactory {
#Override
public UnifiedNativeAdView createNativeAd(
UnifiedNativeAd nativeAd, Map<String, Object> customOptions) {
// Create UnifiedNativeAdView
}
}
is there should be any changes to Manifest.xml file ? or am I missing something ?
I've cleared the build using (flutter clean ) many times but nothing works
any help would be much appreciated
I was also having the exact same issue. This is how I fix it!
Seems that this error is related with the NativeAdFactory file (eg: ListTileNativeAdFactory.java) and the layout at app/src/main/res/layout/list_title_native_ad.xml
If you go to the Google Codelabs example at https://github.com/googlecodelabs/admob-inline-ads-in-flutter/tree/main/complete and copy those files exactly like the example you will solve that problem.

JxBrowser does not launch from another class

I have a problem that I cannot launch my JxBrowser from another class but it works fine on its own class. I will give the code for the internet browser class here
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import javax.swing.*;
import java.awt.*;
public class InternetBrowser
{
//properties
Browser browser;
BrowserView browserView;
JFrame frame;
//constructor
public InternetBrowser()
{
browser = new Browser();
browserView = new BrowserView(browser);
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(browserView, BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
browser.loadURL("https://www.youtube.com/embed/bO7yYDIOuXo");
}
public static void main( String [] args )
{
InternetBrowser browser = new InternetBrowser();
}
}
The error that I get is
Class StartIPCTask is implemented in both /private/var/folders/cs/1z68c1xs2q3crwrwm__fx_t80000gn/T/jxmaps-chromium-49.0.2623.110.unknown/data/Temp/libjxmaps-common64-397f2f15-9ac5-4806-91f6-88c8aaa29714.dylib (0x1288d5630) and /private/var/folders/cs/1z68c1xs2q3crwrwm__fx_t80000gn/T/browsercore-64.0.3282.24.6.21/data/Temp/libbrowsercore-common64-01e73e7f-2b85-4bd3-ac76-05d908fa4928.dylib (0x16b2576c8). One of the two will be used. Which one is undefined.
I need to define which one of the directories that the class should use but I do not know how. I am using the latest version of Netbeans. Also at the top of the class that im trying to construct a browser, the imports are highlighted as "unused import". Thank you for your help!
I realized that this is a bug seen in OSX.. The program works without any problem in windows computers.
In general, this warning doesn't affect the program, so you can just ignore it. If you don't want to receive it at all, then please try using the jxbrowser.jni.singleton.fix=false VM parameter.

Prtining method arguments using byte buddy API

I am working on a project where I need access method arguments during execution.
Is it possible to print method arguments using byte buddy framework? any sample code on this using javaagent is highly appreciated.
Yes, this is possible. You can use MethodDelegation or Advice to inject your code and then use the #AllArguments annotation to get hold of the actual arguments.
The question is, how do you create your code in your project? You can either use a Java agent with the AgentBuilder or create proxy subclasses using ByteBuddy instances. Refer to the documentation and the mentioned classes javadoc to find out how this is done.
Here is an example of how this can be implemented using MethodDelegation. I use it to measure the execution time of methods. I specifically did not begin to remove the extra code, because I want to more fully reveal the capabilities of Byte Buddy.
package md.leonis.shingler;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.matcher.ElementMatchers;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
public class MeasureMethodTest {
public static void main(String[] args) throws InterruptedException {
premain(ByteBuddyAgent.install());
for (int i = 0; i < 4; i++) {
SampleClass.foo("arg" + i);
}
}
public static void premain(Instrumentation instrumentation) {
new AgentBuilder.Default()
.type(ElementMatchers.nameStartsWith("md.leonis.shingler"))
.transform((builder, type, classLoader, module) ->
builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(AccessInterceptor.class))
).installOn(instrumentation);
}
public static class AccessInterceptor {
#RuntimeType
public static Object intercept(#Origin Method method, #SuperCall Callable<?> callable, #AllArguments Object[] args) throws Exception {
long start = System.nanoTime();
try {
return callable.call();
} finally {
if (method.getAnnotationsByType(Measured.class).length > 0) {
String params = Arrays.stream(args).map(Object::toString).collect(Collectors.joining(", "));
System.out.println(method.getReturnType().getSimpleName() + " " + method.getName() + "("+ params +") took " + ((System.nanoTime() - start) / 1000000) + " ms");
}
}
}
}
public static class SampleClass {
#Measured
static void foo(String s) throws InterruptedException {
Thread.sleep(50);
}
}
}
This example measures the execution time of all methods found in the md.leonis.shingler package and marked with the #Measured annotation.
To run it, you need two libraries: byte-buddy and byte-buddy-agent.
The result of work:
void foo(arg0) took 95 ms
void foo(arg1) took 50 ms
void foo(arg2) took 50 ms
void foo(arg3) took 50 ms
Note that the console displays the values of all arguments passed to the method. This is the answer to the question asked.
Here is the annotation example:
package md.leonis.shingler;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Measured {
}
To be honest, I was not able to directly configure filtering by annotations in the Agent. Here is an example (not working):
new AgentBuilder.Default()
.type(ElementMatchers.isAnnotatedWith(Measured.class))
.transform((builder, type, classLoader, module) ->
builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(AccessInterceptor.class))
).installOn(instrumentation);
If someone knows how to do this, please comment below.

Spring boot how to handle throwable

I made a project like this sample. So the controllers are like this
package mypackagename.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
#RequestMapping("/")
public class StoresRestController {
#RequestMapping(method = RequestMethod.GET)
public String stores() {
return ...
}
}
I like to handle all throwables and make my customized unified response. The problem is I cannot find a guide or a sample to do this correctly.
First of all, I tried ExceptionHandler, with Throwable, but it didn't work, so I decided to move on. Then, the most close approach that I found is this, so I tried jersey, by adding something like this. But it's not working for all throwables. Also, it's ignoring my controllers, by complaining
o.g.jersey.internal.inject.Providers : A provider mypackagename.controller.StoresRestController registered in SERVER runtime does not implement any provider interfaces applicable in the SERVER runtime. Due to constraint configuration problems the provider mypackagename.controller.StoresRestController will be ignored.
I searched for this error and found this, which I'm not using ContainerResponseFilter in my project as I provided the sample above. So I'm clueless. The main problem is how to handle all throwables, but if you can give me some suggestions about how to solve Providers problem, I'll be so appreciated.
In my project I use #ControllerAdvice to handle my exceptions. Here's an example. Hope this helps. Just make sure this class is on your component scan so it gets picked up.
#RestController
#ControllerAdvice
public class StoresExceptionHandler {
#ExceptionHandler(Throwable.class)
public ResponseEntity<Object> handleThrowable(final Throwable ex) {
return new ResponseEntity<Object>("Unable to process request.", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Finally this post helped me to handle all Throwables, except authentication exceptions. The important part was to use #EnableWebMvc and ResponseEntityExceptionHandler. To handle authentication exceptions I used this answer. Hope it's helping someone.
as #carlos-cook said, you could use a #ControllerAdvice and, ProblemDetail defined in RFC 7807 which could look like:
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(RuntimeException.class)
public ProblemDetail handleUnexpectedException(RuntimeException rte, WebRequest wr) {
ProblemDetail pd = this.createProblemDetail(HttpStatus.INTERNAL_SERVER_ERROR, rte);
pd.setType(URI.create("http://your-site.com/internal-server-error"));
pd.setTitle("Internal server error");
return pd;
}
#ExceptionHandler(YourCustomeException.class)
public ProblemDetail handleUnexpectedException(YourCustomException rte, WebRequest wr) {
ProblemDetail pd = this.createProblemDetail(HttpStatus.INTERNAL_SERVER_ERROR, rte);
pd.setType(URI.create("http://your-site.com/custom-error-page"));
pd.setTitle("Internal server error");
return pd;
}
}
Then in your controller you could simply throw YourCustomException
This controller advice will handle every exception and YourCustomException separately.

How can I open the default system browser from a java fx application?

I'm trying to open a web url in the default system browser from javafx. I didn't find any official documentation regard this. Any clue?
EDIT:
I've found a tutorial but it doesn't work.
I'm using MacOsX and I tried launching
java.awt.Desktop.getDesktop().browse(new URI(url));
but I get an HeadlessExcelption
Use hostServices.showDocument(location).
Try placing the following code in your application's start method:
getHostServices().showDocument("http://www.yahoo.com");
Complementing jewelsea's answer, if you don't know how to call getHostServices() then try this at your main class:
HostServicesDelegate hostServices = HostServicesFactory.getInstance(this);
hostServices.showDocument(WEBSITE);
http://docs.oracle.com/javafx/2/api/javafx/application/HostServices.html#showDocument(java.lang.String)
Another option is to use ProcessBuilder:
public static void openWebpage(String url) {
try {
new ProcessBuilder("x-www-browser", url).start();
} catch (IOException e) {
e.printStackTrace();
}
}
You can use this option if Desktop.getDesktop().browse(uri) for some reason hangs without any error.
Try This:
try {
Desktop.getDesktop().browse(new URL("https://google.com").toURI());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
It cannot be done, seems, because this feature is not implemented : https://javafx-jira.kenai.com/browse/RT-210
The matter is that you will not be able to launch anything, what requires awt-stack and jfx in the same VM. The decision - is to use a separate JVM. Just launch a separate VM, and accept commands on browsing by socket.
That is one way, another way - is to find any other way of browser call from java - this is a task not specific to javafx-2, but to java at all.
But developer has added a comment :
Anthony Petrov added a comment - May, 17 2013 05:09 PM
Note that FX8 allows headful AWT to run in the same VM with FX. So the AWT API should work.
Here is a script that works inside the scene controller, when a button is activated:
package sample;
import com.sun.deploy.uitoolkit.impl.fx.HostServicesFactory;
import com.sun.javafx.application.HostServicesDelegate;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.stage.Stage;
public class Controller extends Application {
public void openBrowser(ActionEvent actionEvent) throws Exception {
HostServicesDelegate hostServices = HostServicesFactory.getInstance(this);
getHostServices().showDocument("http://www.yahoo.com");
}
#Override
public void start(Stage primaryStage) throws Exception {
}
}

Resources