I am using 2 classes for my basic Maven and Selenium project-openGmail. I am using Selenium 3.5 with Firefox 47.0.1 and Gecodriver 0.18.
My Main class is:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MainClass {
WebDriver driver = new FirefoxDriver();
public void setup() {
String Path_GecoDriver="C:/Personal/Selenium/setup/geckodriver-v0.18.0-win64";
System.setProperty("webdriver.firefox.marionette", Path_GecoDriver+"/geckodriver.exe");
System.setProperty("webdriver.gecko.driver", Path_GecoDriver+"/geckodriver.exe");
}
public void OpenBrowser() {
String url="http://google.co.in";
driver.get(url);
}
public void LoginGmail() throws InterruptedException {
String username ="username";
String passwd = "passwd";
driver.findElement(By.linkText("Gmail")).click();
driver.findElement(By.id("identifierId")).sendKeys(username);
WebElement cli=driver.findElement(By.xpath("//*[text()='Next']"));
cli.click();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(passwd);
driver.findElement(By.xpath("//*[text()='Next']")).click();
}
public void CloseBrowser() {
driver.close();
}
}
My other class is:-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestngClass {
MainClass mc=new MainClass();
#Before
public void sp() {
mc.setup();
mc.OpenBrowser();
}
#Test
public void LG() throws InterruptedException {
mc.LoginGmail();
}
#After
public void CB() {
mc.CloseBrowser();
}
}
I am getting the error
java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information
I have tried to execute it the test by putting my System.setProperty (prop, path/to/driver) in my #Before, and # test also but no change, I am still getting the error.
If I use a single class then everything works fine so I think I am placing my system.setProperty at the wrong place.
I have started with Java and Selenium very recently. I have even tried to put my Gecko driver exe in src/main/resources of my Maven project as mentioned in In System.setProperty("webdriver.gecko.driver", "<Path to your WebDriver>"), what is meant by "Path to your WebDriver"?
You have set the property two times as below :-
System.setProperty("webdriver.firefox.marionette", Path_GecoDriver+"/geckodriver.exe");
System.setProperty("webdriver.gecko.driver", Path_GecoDriver+"/geckodriver.exe");
Remove :-
System.setProperty("webdriver.firefox.marionette", Path_GecoDriver+"/geckodriver.exe");
Another thing is you have to set it before creating the firefox instance. You have define the instance first and then you are setting up the preference .
Try something like below :-
WebDriver driver =null;
public void setup() {
String Path_GecoDriver="C:/Personal/Selenium/setup/geckodriver-v0.18.0-win64";
System.setProperty("webdriver.gecko.driver", Path_GecoDriver+"/geckodriver.exe");
driver= new FirefoxDriver();
}
Hope it will help you :)
Related
I have a quarkus-camel batch application that needs to run under a lambda in AWS. This is working fine with pure java and spring-boot.
I need to be able to start the Quarkus Application from the AWS lambda handler method.
Running in batch works fine, but under lambda I get the following error:
Caused by: io.quarkus.bootstrap.BootstrapException: Failed to determine the Maven artifact associated with the application /var/task
This is the main java class. I need to know what to do in the handleRequest method to start the Quarkus (CAMEL) application.
package com.example;
import io.quarkus.runtime.annotations.QuarkusMain;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.QuarkusApplication;
import io.quarkus.arc.Arc;
import io.quarkus.runtime.QuarkusApplication;
import org.apache.camel.quarkus.core.CamelRuntime;
import javax.inject.Inject;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
#QuarkusMain
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
public static void main(String... args) {
Quarkus.run(CamelApp.class, args);
}
public static class CamelApp implements QuarkusApplication {
#Inject
ProducerTemplate camelProducer;
#Inject
CamelContext camelContext;
#Override
public int run(String... args) throws Exception {
System.out.println("Hello Camel");
CamelRuntime runtime = Arc.container().instance(CamelRuntime.class).get();
runtime.start(args);
camelProducer.sendBody("direct:lambda", "how about this?");
return runtime.waitForExit();
}
}
public Object handleRequest(final Object input, final Context context) {
logger.info("input: {}", gson.toJson(input));
logger.info("context: {}", gson.toJson(context));
Quarkus.run(CamelApp.class);
// CamelRuntime runtime = Arc.container().instance(CamelRuntime.class).get();
// runtime.start(new String[] {"A","B","C"});
// camelProducer.sendBody("direct:lambda", "how about this?");
// runtime.waitForExit();
return input;
}
}
Having following configuration for my integration tests I ran into following exception:
Driver org.testcontainers.jdbc.ContainerDatabaseDriver claims to not accept jdbcUrl, jdbc:postgresql://localhost:32864/test?loggerLevel=OFF
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebApplication.class)
#AutoConfigureMockMvc
#Testcontainers
#TestPropertySource(ResourceUtils.CLASSPATH_URL_PREFIX + "application-test.properties")
public abstract class AbstractIntegrationTest {
#Autowired
protected MockMvc mockMvc;
#Container
protected static PostgreSQLContainer<?> postgresqlContainer = new PostgreSQLContainer<>();
#DynamicPropertySource
static void postgresqlProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgresqlContainer::getJdbcUrl);
registry.add("spring.datasource.username", postgresqlContainer::getUsername);
registry.add("spring.datasource.password", postgresqlContainer::getPassword);
}
#Test
void contextLoads() {
Assertions.assertThat(mockMvc).isNotNull();
Assertions.assertThat(postgresqlContainer.isRunning()).isTrue();
}
}
The postgresqlContainer.getJdbcUrl() returns jdbc:postgresql://localhost:32864/test?loggerLevel=OFF
But it should return jdbc:tc:postgresql://..., its missing the tc part.
Any solution to this ?
Hardcoding it like: String.format("jdbc:tc:postgresql://localhost:%s/%s", postgresqlContainer.getFirstMappedPort(), postgresqlContainer.getDatabaseName()) seems to work.
What am I doing wrong here?
Please see the big orange warning here:
https://www.testcontainers.org/modules/databases/jdbc/
You should use either the JDBC URL with tc: prefix and ContainerDatabaseDriver or container instance with getJdbcUrl() and the original driver (or let the system detect the driver for you), not both.
In my case just added the postgresql dependency (it includes the driver) and it worked:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.3.0</version>
</dependency>
My test class:
import org.junit.Rule;
import org.junit.Test;
import org.junit.platform.commons.annotation.Testable;
import org.testcontainers.containers.PostgreSQLContainer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import static org.junit.jupiter.api.Assertions.assertEquals;
#Testable
public class PostgreSqlContainerLiveTest {
#Rule
public PostgreSQLContainer postgresContainer = new PostgreSQLContainer("postgres:9.4");
static {
// Postgres JDBC driver uses JUL; disable it to avoid annoying, irrelevant, stderr logs during connection testing
LogManager.getLogManager().getLogger("").setLevel(Level.OFF);
}
#Test
public void whenSelectQueryExecuted_thenResultsReturned() throws Exception {
ResultSet resultSet = performQuery(postgresContainer, "SELECT 1");
resultSet.next();
int result = resultSet.getInt(1);
assertEquals(1, result);
}
private ResultSet performQuery(PostgreSQLContainer postgreSQLContainer, String query) throws SQLException {
String jdbcUrl = postgreSQLContainer.getJdbcUrl();
String username = postgreSQLContainer.getUsername();
String password = postgreSQLContainer.getPassword();
Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
return conn.createStatement().executeQuery(query);
}
}
I hope that this could help to you or someone else.
Make sure you have both dependency testcontainers postgresql & dependency postgresql at your config file.
I am learning the Spring-Boot(I am new to it), reading the Spring Boot Document. In the 23.6 Accessing application arguments, It talk about the ApplicationArguments, and the code is:
package com.example.project;
import org.springframework.boot.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import java.util.*;
#Component
public class MyBean {
#Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
System.out.println(debug);
System.out.println(files);
}
}
It says if run with "--debug logfile.txt" debug=true, files=["logfile.txt"].
But in my project, I don't know how to run it. I create the spring-boot using Maven: The Project Structure
In Spring Boot doc ApplicationArguments is autowired in a bean. Here is a more hands on example where it's used in a Main method.
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args).stop();
}
#Override
public void run(ApplicationArguments args) throws Exception {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
System.out.println(debug);
System.out.println(files);
}
}
Assuming that you have an Application class with annotation #SpringBootApplication like in the answer provided by a.b.d.
To be able to provide the arguments within IntelliJ IDEA environment you will need to first Run the main method and then Edit 'Run/Debug Configurations' and under Main Class fill Program arguments field with "--debug logfile.txt":
In one word like a thousand :
the 'Program arguments' in your IDE field prefixed by -- is simply the same name as the 'Option' expected in the 'ApplicationArguments'.
Hence you can match --debug and "args.containsOption("debug")".
I have written some exception mappers to catch and handle the in-built rest easy exceptions like NotFoundException,MethodNotAllowedException, etc., Sample code as shown:
#Provider
public class NotFoundExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.NotFoundException>
{
#Override
Response toResponse(org.jboss.resteasy.spi.NotFoundException exception) {
return Response.status(500).build();
}
}
I have also written a try catch block in my web filter class. Whenever a NotFoundException occurs, it is not caught in the mapper, but it goes to the catch block in the Filter.
Whereas I have tried another exception mapper class to handle JsonParsingException. This is working correctly and giving a proper response from the mapper whenever a Json Parse exception occurs.
The issue is only with the case of resteasy exceptions.
Also, the Provider has been registered in the application context using the include-filter tag inside component scan.
Please guide me as to what needs to be done to catch rest easy in-built exceptions in the mapper class itself.
Regards,
RM
I had the same problem. Annotating the NotFoundExceptionMapper with #Component should fix it (or adding NotFoundExceptionMapper as a bean to your application context (xml-file)).
When your Spring context is started the NotFoundExceptionMapper should be registered (you should something like "Pre-instantiating singletons in ... " in your logging)
Here is my demo project
1) a simple RESTful app with 3 java files:
1.1) RestNotFoundExceptionHandler.java
package demo.app;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class RestNotFoundExceptionHandler implements ExceptionMapper<NotFoundException> {
#Override
public Response toResponse(NotFoundException e) {
return Response.ok().entity(e.toString() + "\n").type(MediaType.TEXT_PLAIN).build();
}
}
1.2) AppRest.java
package demo.app;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
#Path("/")
public class AppRest {
#GET
#Path("millis")
#Produces(MediaType.TEXT_PLAIN)
public String refresh(#Context HttpServletRequest request) {
try {
return Long.toString(System.currentTimeMillis()) + "\n";
} catch (Exception e) {
return e.toString() + "\n";
}
}
}
1.3) AppMain.java
package demo.app;
import javax.ws.rs.NotFoundException;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
public class AppMain {
private static final int PORT = 8080;
public static void main(String[] args) {
AppRest appRest = new AppRest();
TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
tjws.setPort(PORT);
tjws.setRootResourcePath("/rest");
tjws.start();
tjws.getDeployment().getRegistry().addSingletonResource(appRest);
tjws.getDeployment().getProviderFactory().getExceptionMappers()
.put(NotFoundException.class, new RestNotFoundExceptionHandler());
}
}
2) project dependencies, 4 jar files
jaxrs-api-3.0.9.Final.jar
resteasy-jaxrs-3.0.9.Final.jar
servlet-api-2.5.jar
tjws-3.0.9.Final.jar
3) curl test cases:
3.1) normal case:
$ curl http://127.0.0.1:8080/rest/millis
1419167594504
3.2) RestNotFoundExceptionHandler case:
$ curl http://127.0.0.1:8080/rest/bad
javax.ws.rs.NotFoundException: Could not find resource for full path: http://127.0.0.1:8080/rest/bad
I tried the same thing and fell into trouble while trying to map UnsupportedMediaTypeException.
According to http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/html/ExceptionHandling.html and the first line under Exception Mappers section it seems you can only map application Exceptions.
I want to test my Jersey resources with the Jersey Test-Framework.
I followed the descriptions provided here
http://blogs.oracle.com/naresh/entry/jersey_test_framework_makes_it
http://zhanghaoeye.javaeye.com/blog/441759
to create a simple example. My example is hosted as git repository on http://github.com/rmetzler/Jersey-Test .
$ mvn jetty:run works as expected but I keep getting NullPointerExceptions when running $ mvn clean test.
java.lang.NullPointerException
at com.sun.jersey.spi.container.ContainerResponse.mapException(ContainerResponse.java:429)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1295)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1239)
at com.sun.jersey.test.framework.impl.container.inmemory.TestResourceClientHandler.handle(TestResourceClientHandler.java:119)
at com.sun.jersey.api.client.Client.handle(Client.java:616)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:559)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:182)
at example.jersey.spring.MyResourceTest.testMyResource(MyResourceTest.java:30)
...
I bet I made a small mistake that I'm unable to find. I would show my source to another developer but unfortunately I work alone at home. So maybe someone of you could help me?
UPDATE
I created an Eclipse project by running $ mvn eclipse:eclipse . Now when I run the test as JUnit Test in Eclipse it is green. When running it as TestNG Test it fails. So I guess it has something to do with how the test is executed by TestNG.
I did the same thing except for I am using guice, not spring. This is my implementation (sorry, no time to clean up, you'll have to extract the interesting parts yourself). Note that I used a delegate jerseytest class so I can inherit some code from my base test class. Also you have to map the junit pre- and post-methods to testng ones.
Hope this helps a bit.
package mypackage;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.lang.UnhandledException;
import org.apache.xerces.dom.DOMInputImpl;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.w3c.dom.Document;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.reflect.core.Reflection.staticMethod;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.spi.container.WebApplication;
import com.sun.jersey.spi.container.WebApplicationFactory;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import com.sun.jersey.test.framework.impl.container.inmemory.TestResourceClientHandler;
import com.sun.jersey.test.framework.spi.container.TestContainer;
import com.sun.jersey.test.framework.spi.container.TestContainerException;
import com.sun.jersey.test.framework.spi.container.TestContainerFactory;
import com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory;
import mypackage.StaticConfig;
import mypackage.MediaTypes;
public abstract class JerseyIntegrationTestBase extends TransactionalIntegrationTestBase {
private static final Logger LOG = LoggerFactory.getLogger( JerseyIntegrationTestBase.class );
private static final class GuiceInMemoryTestContainerFactory extends InMemoryTestContainerFactory {
#Override
public TestContainer create( final URI baseUri, final AppDescriptor ad ) {
return new GuiceInMemoryTestContainer( baseUri, (LowLevelAppDescriptor) ad );
}
/**
* Kopie der Klasse im inmemory-Testcontainer von Jersey, leicht an Guice-Injection angepasst. The class defines methods for
* starting/stopping an in-memory test container, and for running tests on the container.
*/
private static class GuiceInMemoryTestContainer implements TestContainer {
final URI baseUri;
final ResourceConfig resourceConfig;
final WebApplication webApp;
/**
* Creates an instance of {#link GuiceInMemoryTestContainer}
*
* #param Base
* URI of the application
* #param An
* instance of {#link LowLevelAppDescriptor}
*/
private GuiceInMemoryTestContainer( final URI baseUri, final LowLevelAppDescriptor ad ) {
this.baseUri = UriBuilder.fromUri( baseUri ).build();
LOG.info( "Creating low level InMemory test container configured at the base URI " + this.baseUri );
resourceConfig = ad.getResourceConfig();
// Falls man mal in Tests die requests und responses sehen möchte:
// this.resourceConfig.getProperties().put( ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
// LoggingFilter.class.getName() );
// this.resourceConfig.getProperties().put( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
// LoggingFilter.class.getName() );
resourceConfig.getProperties().putAll( StaticConfig.getJerseyParams() );
webApp = WebApplicationFactory.createWebApplication();
}
#Override
public Client getClient() {
ClientConfig clientConfig = null;
final Set providerSingletons = resourceConfig.getProviderSingletons();
if ( providerSingletons.size() > 0 ) {
clientConfig = new DefaultClientConfig();
for ( final Object providerSingleton : providerSingletons ) {
clientConfig.getSingletons().add( providerSingleton );
}
}
final Client client = clientConfig == null
? new Client( new TestResourceClientHandler( baseUri, webApp ) )
: new Client( new TestResourceClientHandler( baseUri, webApp ), clientConfig );
return client;
}
#Override
public URI getBaseUri() {
return baseUri;
}
#Override
public void start() {
if ( !webApp.isInitiated() ) {
LOG.info( "Starting low level InMemory test container" );
webApp.initiate( resourceConfig, new GuiceContainer( null ).new ServletGuiceComponentProviderFactory(
resourceConfig, IntegrationTestBase.getInjector() ) );
}
}
#Override
public void stop() {
if ( webApp.isInitiated() ) {
LOG.info( "Stopping low level InMemory test container" );
webApp.destroy();
}
}
}
}
private final JerseyTest _jerseyTest;
public JerseyIntegrationTestBase() {
// PackagesResourceConfig.getPackages macht genau das, was wir wollen, ist aber private, daher
// auf die harte Tour...
// FORMATTER: OFF
final String[] packages =
staticMethod( "getPackages" ).withReturnType( String[].class ).withParameterTypes( Map.class )
.in( PackagesResourceConfig.class ).invoke( StaticConfig.getJerseyParams() );
// FORMATTER: ON
_jerseyTest = new JerseyTest( new LowLevelAppDescriptor.Builder( packages ).build() ) {
#Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GuiceInMemoryTestContainerFactory();
}
};
}
/**
* #return
* #see JerseyTest#client().
*/
protected Client client() {
return _jerseyTest.client();
}
#BeforeClass( alwaysRun = true )
public void setUp() throws Exception {
_jerseyTest.setUp();
}
#AfterClass( alwaysRun = true )
public void tearDown() throws Exception {
_jerseyTest.tearDown();
}
}
Because JerseyTest is using #Before annotation from Junit for initialising the application, and you have to extend JerseyTest to enable testng support, like this:
public class JerseyTestNG extends JerseyTest {
#Override
protected Application configure() {
ResourceConfig config = new ResourceConfig(YourService.class);
}
#BeforeClass
public void setUp() {
super.setUp();
}
#AfterClass
public void tearDown() {
super.tearDown();
}
}
#BeforeClass also will make sure all tests within are executed after the Jersey container is ready when using surefire plugin. Otherwise those tests will fail quickly.
and if you want to it read applicationContext-test.xml other than the default one, set one more property to ResourceConfig:
config.setProperties(new HashMap<String, String>() {{
put("contextConfigLocation", "applicationContext-test.xml");
}});
also, adding some features to ClientConfig maybe helpful:
#Override
protected void configureClient(ClientConfig config) {
config.register(LoggingFilter.class);
config.register(MOXyJsonProvider.class);
config.register(new EncodingFeature(GZipEncoder.class));
}
All tested on Jersey 2.6.
A simple example using Jersey + Spring + TestNG + Jetty here:
http://ameethpaatil.blogspot.com/2011/09/restful-webservice-jersey-spring-30x.html