SignInPage does not see Username and password - wicket

I tried to implement a login using ServletContainerAuthenticatedWebApplication and registering the default SignInPage from Wicket as a sign in page. So far everything works, it redirects me to the login page when I try to access a protected resource, but I cannot login because the username and password fields inside SignInPanel are always null, regardless of what I enter in those inputs in the browser. I tried this with both Wicket 8.0.0-M8 and Wicket 7.9.0. Some help would be appreciated at this time.
public class HelloWorldApplication extends ServletContainerAuthenticatedWebApplication
{
private static String EJB_PROJ_NAME = "rezerva_masa_ejb";
public HelloWorldApplication()
{
}
#Override
public void init()
{
super.init();
getComponentInstantiationListeners().add(new JavaEEComponentInjector(this, new AppJndiNamingStrategy(EJB_PROJ_NAME)));
}
#Override
public Class getHomePage()
{
return HelloWorld.class;
}
#Override
protected Class<? extends ServletContainerAuthenticatedWebSession> getContainerManagedWebSessionClass()
{
return ServletContainerAuthenticatedWebSession.class;
}
#Override
protected Class<? extends WebPage> getSignInPageClass()
{
return SignInPage.class;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>RezervaMasa</display-name>
<filter>
<filter-name>HelloWorldApplication</filter-name>
<filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>ro.rezervamasa.main.HelloWorldApplication</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HelloWorldApplication</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<context-param>
<param-name>configuration</param-name>
<param-value>development<!-- deployment --></param-value>
</context-param>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>ApplicationRealm</realm-name>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/login.html</form-error-page>
</form-login-config>
</login-config>
<security-role>
<role-name>view_users</role-name>
</security-role>
<security-role>
<role-name>create_users</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>All pages</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>view_users</role-name>
<role-name>create_users</role-name>
</auth-constraint>
</security-constraint>
</web-app>

Not sure why I had this problem. The next day I started the server again and everything worked fine. I think there was some publishing problem maybe.

Related

NoClassDefFoundError: Failed to link conditional authenticator keycloak 11

I'm using keycloak 11.0.3 (jboss distribution) with Docker. I'm also writing my custom conditional authenticator for user attribute condition (actually I copied the one from newer keycloak distribution):
Factory class
package org.example;
import org.keycloak.Config;
import org.keycloak.authentication.authenticators.conditional.ConditionalAuthenticator;
import org.keycloak.authentication.authenticators.conditional.ConditionalAuthenticatorFactory;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderConfigProperty;
import java.util.Arrays;
import java.util.List;
public class ConditionalUserAttributeValueFactory implements ConditionalAuthenticatorFactory {
public static final String PROVIDER_ID = "conditional-user-attribute";
public static final String CONF_ATTRIBUTE_NAME = "attribute_name";
public static final String CONF_ATTRIBUTE_EXPECTED_VALUE = "attribute_expected_value";
public static final String CONF_NOT = "not";
private static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
AuthenticationExecutionModel.Requirement.REQUIRED, AuthenticationExecutionModel.Requirement.DISABLED
};
#Override
public void init(Config.Scope config) {
// no-op
}
#Override
public void postInit(KeycloakSessionFactory factory) {
// no-op
}
#Override
public void close() {
// no-op
}
#Override
public String getId() {
return PROVIDER_ID;
}
#Override
public String getDisplayType() {
return "Condition - user attribute";
}
#Override
public String getReferenceCategory() {
return null;
}
#Override
public boolean isConfigurable() {
return true;
}
#Override
public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
return REQUIREMENT_CHOICES;
}
#Override
public boolean isUserSetupAllowed() {
return false;
}
#Override
public String getHelpText() {
return "Flow is executed only if the user attribute exists and has the expected value";
}
#Override
public List<ProviderConfigProperty> getConfigProperties() {
ProviderConfigProperty authNoteName = new ProviderConfigProperty();
authNoteName.setType(ProviderConfigProperty.STRING_TYPE);
authNoteName.setName(CONF_ATTRIBUTE_NAME);
authNoteName.setLabel("Attribute name");
authNoteName.setHelpText("Name of the attribute to check");
ProviderConfigProperty authNoteExpectedValue = new ProviderConfigProperty();
authNoteExpectedValue.setType(ProviderConfigProperty.STRING_TYPE);
authNoteExpectedValue.setName(CONF_ATTRIBUTE_EXPECTED_VALUE);
authNoteExpectedValue.setLabel("Expected attribute value");
authNoteExpectedValue.setHelpText("Expected value in the attribute");
ProviderConfigProperty negateOutput = new ProviderConfigProperty();
negateOutput.setType(ProviderConfigProperty.BOOLEAN_TYPE);
negateOutput.setName(CONF_NOT);
negateOutput.setLabel("Negate output");
negateOutput.setHelpText("Apply a not to the check result");
return Arrays.asList(authNoteName, authNoteExpectedValue, negateOutput);
}
#Override
public ConditionalAuthenticator getSingleton() {
return ConditionalUserAttributeValue.SINGLETON;
}
}
Authenticator class:
package org.example;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.AuthenticationFlowException;
import org.keycloak.authentication.authenticators.conditional.ConditionalAuthenticator;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import java.util.Map;
import java.util.Objects;
public class ConditionalUserAttributeValue implements ConditionalAuthenticator {
static final ConditionalUserAttributeValue SINGLETON = new ConditionalUserAttributeValue();
#Override
public boolean matchCondition(AuthenticationFlowContext context) {
System.out.println("START MATCH CONDITION");
Map<String, String> config = context.getAuthenticatorConfig().getConfig();
System.out.println("Map<String, String> config = " + config);
String attributeName = config.get(ConditionalUserAttributeValueFactory.CONF_ATTRIBUTE_NAME);
String attributeValue = config.get(ConditionalUserAttributeValueFactory.CONF_ATTRIBUTE_EXPECTED_VALUE);
System.out.println("attributeName = " + attributeName);
System.out.println("attributeValue = " + attributeName);
UserModel user = context.getUser();
if (user == null) {
throw new AuthenticationFlowException("Cannot find user for obtaining particular user attributes. Authenticator: " +
ConditionalUserAttributeValueFactory.PROVIDER_ID, AuthenticationFlowError.UNKNOWN_USER);
}
System.out.println("USER ATTRIBUTES :" + user.getAttributes());
return user.getAttribute(attributeName).stream()
.anyMatch(attr -> Objects.equals(attr, attributeValue));
}
#Override
public void action(AuthenticationFlowContext context) {
}
#Override
public boolean requiresUser() {
return true;
}
#Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
}
#Override
public void close() {
}
}
And I added a file named
org.keycloak.authentication.AuthenticatorFactory
to resources/META-INF/services folder with the following content
org.example.ConditionalUserAttributeValueFactory
pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>conditional-authenticator</artifactId>
<version>1.0-SNAPSHOT</version>
<name>conditional-authenticator</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<keycloak.version>11.0.3</keycloak.version>
</properties>
<dependencies>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-services</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi</artifactId>
<version>${keycloak.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi-private</artifactId>
<version>${keycloak.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Dockerfile:
FROM jboss/keycloak:11.0.3
COPY ./deployments /opt/jboss/keycloak/standalone/deployments
ENTRYPOINT [ "/opt/jboss/tools/docker-entrypoint.sh" ]
CMD ["-b", "0.0.0.0"]
But after I run the container I recieve the following error:
16:42:07,288 WARN [org.jboss.modules.define] (ServerService Thread Pool -- 62) Failed to define class org.example.ConditionalUserAttributeValueFactory in Module "deployment.conditional-authenticator-1.0-SNAPSHOT.jar" from Service Module Loader: java.lang.NoClassDefFoundError: Failed to link org/example/ConditionalUserAttributeValueFactory (Module "deployment.conditional-authenticator-1.0-SNAPSHOT.jar" from Service Module Loader): org/keycloak/authentication/authenticators/conditional/ConditionalAuthenticatorFactory
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1096)
at org.jboss.modules.ModuleClassLoader.doDefineOrLoadClass(ModuleClassLoader.java:424)
at org.jboss.modules.ModuleClassLoader.defineClass(ModuleClassLoader.java:555)
at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:339)
at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:126)
at org.jboss.modules.Module.loadModuleClass(Module.java:731)
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:247)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.nextProviderClass(ServiceLoader.java:1209)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNextService(ServiceLoader.java:1220)
at java.base/java.util.ServiceLoader$LazyClassPathLookupIterator.hasNext(ServiceLoader.java:1264)
at java.base/java.util.ServiceLoader$2.hasNext(ServiceLoader.java:1299)
at java.base/java.util.ServiceLoader$3.hasNext(ServiceLoader.java:1384)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.provider.DefaultProviderLoader.load(DefaultProviderLoader.java:60)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.provider.ProviderManager.load(ProviderManager.java:95)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.services.DefaultKeycloakSessionFactory.loadFactories(DefaultKeycloakSessionFactory.java:248)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.services.DefaultKeycloakSessionFactory.init(DefaultKeycloakSessionFactory.java:88)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.services.resources.KeycloakApplication.createSessionFactory(KeycloakApplication.java:260)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.services.resources.KeycloakApplication.startup(KeycloakApplication.java:124)
at org.keycloak.keycloak-wildfly-extensions#11.0.3//org.keycloak.provider.wildfly.WildflyPlatform.onStartup(WildflyPlatform.java:29)
at org.keycloak.keycloak-services#11.0.3//org.keycloak.services.resources.KeycloakApplication.<init>(KeycloakApplication.java:114)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
It worth noting that preciously I managed to successfully deploy custom SMS Authenticator the same way. But I ran intro such troubles with the conditional one.
Any ideas?

cucumber.runtime.CucumberException: java.lang.NullPointerException

I am using to execute my selenium test with Cucumber, Maven and TestNG and Appium. When i started this automation by using TestNG via TestNG.xml. App launched but There is an error on running feature files selenium cucumber. I am getting the below error. Please help to resolve this error.
cucumber.runtime.CucumberException: java.lang.NullPointerException
at cucumber.api.testng.TestNGCucumberRunner.runCucumber(TestNGCucumberRunner.java:69)
at runner.RunnerTest.feature(RunnerTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:584)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:172)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:804)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:145)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.testng.TestRunner.privateRun(TestRunner.java:770)
at org.testng.TestRunner.run(TestRunner.java:591)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:402)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:396)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:355)
at org.testng.SuiteRunner.run(SuiteRunner.java:304)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1180)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1102)
at org.testng.TestNG.runSuites(TestNG.java:1032)
at org.testng.TestNG.run(TestNG.java:1000)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.NullPointerException
at com.odealMobile.Login.ClickLogin(Login.java:41)
at ✽.When click on login button(src/main/java/features/Android/Login.feature:6)
Details of Plugins Versions:
TestNG - 6.7
Cucumber - 1.2.6
Maven - 3.6.3
Appium - 1.15.1
My Test Class;
package com.odealMobile;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import runner.RunnerTest;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends RunnerTest {
String loginButtonId = "login";
String registerButtonId = "register";
String TCKNId = "tckn";
String passwordId = "password";
String profileImageId = "profile_image_view";
#Given("^odeal app is opened$")
public void CheckOpenedPage() {
System.out.print(By.id(loginButtonId));
wait.until(ExpectedConditions.elementToBeClickable(By.id(loginButtonId)));
//loginButtonId bekleniyor.
wait.until(ExpectedConditions.elementToBeClickable(By.id(registerButtonId)));
}
#When("^click on login button$")
public void ClickLogin() {
// loginButtonId ye tıklanıyor.
driver.findElement(By.id(loginButtonId)).click();
}
#Then("^login page will be opened$")
public void CheckLoginPage() {
wait.until(ExpectedConditions.elementToBeClickable(By.id(loginButtonId)));
}
#When("^user enters valid TCKN$")
public void EnterTCKN() {
driver.findElement(By.id(TCKNId)).click();
driver.findElement(By.id(TCKNId)).setValue("23231487730");
}
#And("^user enters valid password$")
public void EnterPassword() {
driver.findElement(By.id(passwordId)).click();
driver.findElement(By.id(passwordId)).setValue("135246");
}
#And("^clicks on login button$")
public void ClickLoginonLoginPage() {
driver.findElement(By.id(loginButtonId)).click();
}
#Then("^home page will be opened$")
public void CheckHomePage() {
wait.until(ExpectedConditions.elementToBeClickable(By.id(profileImageId)));
if (driver.findElement(By.id(profileImageId)).isDisplayed()) {
System.out.println("Login Success");
} else {
System.out.println("Login Failed");
}
}
}
My Runner Class;
package runner;
import cucumber.api.CucumberOptions;
import cucumber.api.testng.CucumberFeatureWrapper;
import cucumber.api.testng.TestNGCucumberRunner;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
#CucumberOptions(
plugin = {
"pretty",
"json:target/report/cucumber2.json"
},
features = {
"src/main/java/features/Android/Login.feature"
},
glue = {
"com/odealMobile"
}
)
public class RunnerTest {
public AppiumDriver < MobileElement > driver;
public WebDriverWait wait;
private TestNGCucumberRunner testNGCucumberRunner;
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("deviceName", "TestDevice-1");
cap.setCapability("automationName", "UiAutomator2");
cap.setCapability("udid", "emulator-5554");
cap.setCapability("platformName", "Android");
cap.setCapability("platformVersion", "10.0");
//cap.setCapability("autoGrantPermissions", "true");
cap.setCapability("noReset", "false");
cap.setCapability("clearSystemFiles", "true");
cap.setCapability("appPackage", "com.telera.merchant.stage.debug");
cap.setCapability("appActivity", "com.telera.merchant.splash.SplashActivity");
driver = new AndroidDriver < MobileElement > (new URL("http://127.0.0.1:4723/wd/hub"), cap);
wait = new WebDriverWait(driver, 10);
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(groups = "Cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
#DataProvider
public Object[][] features() {
return testNGCucumberRunner.provideFeatures();
}
#AfterClass(alwaysRun = true)
public void tearDownClass() throws Exception {
Thread.sleep(50000);
driver.quit();
//testNGCucumberRunner.finish();
}
}
My Pom.xml;
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>appium.mobile.test</groupId>
<artifactId>odealMobile</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Odeal Mobile</name>
<description>Appium Testing for Mobile </description>
<properties>
<testng.version>6.7</testng.version>
<cucumber.version>1.2.6</cucumber.version>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-guice</artifactId>
<version>1.2.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-html</artifactId>
<version>0.2.3</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>${cucumber.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-jvm -->
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-jvm</artifactId>
<version>${cucumber.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>7.3.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.cucumber/tag-expressions -->
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>tag-expressions</artifactId>
<version>2.0.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
My testng.xml;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="runner.RunnerTest"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
The important part of the error is right here:
Caused by: java.lang.NullPointerException
at com.odealMobile.Login.ClickLogin(Login.java:41)
at ✽.When click on login button(src/main/java/features/Android/Login.feature:6)
When you get a null pointer exception this means that a variable or field doesn't have a value. Either because it has been set to null or because it has never been set.
So what happens? In a very simplified way this:
RunnerTest runner = new RunnerTest();
runner.setUpClass() // This sets runner.driver
Login login = new Login();
login.ClickLogin() // This tries to use login.driver
First an instance of the RunnerTest class is created and driver is set when setupClass is called. Then a new instance of Login is created. Because this is a different instance, even though it extends the RunnerTest class, the driver variable is never set. So when call ClickLogin is used a null pointer happens.
You can fix this in a few ways. The easiest is probably making driver static, not having Login extend RunnerTest and referencing driver as RunnerTest.driver.
public class RunnerTest{
public static AppiumDriver<MobileElement> driver;
}
public class Login {
#When("^click on login button$")
public void ClickLogin() {
// loginButtonId ye tıklanıyor.
RunnerTest.driver.findElement(By.id(loginButtonId)).click();
}
}

Tomcat does not recognize my controller (MVC) - Error instantiating servlet class MyController

I have four files that I want to interact together: Three views (index.jsp, error.jsp and success.jsp) and a controller (MyController.java)
ProjectName
|__
| Java Reosurces
| |__src/main/resources
| |__controller
| |__MyController.java
|_src
|__main
|__webapp
|__WEB-INF
| |__web.xml
|
|__index.jsp
|__error.jsp
|__success.jsp
For my index.jsp, I simply put a textbox, ask for a name and wait for the submit
<html>
<body>
<form action="MyController" method="post">
Name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
When the form gets a submission, I expect it to go handle it at MyController, which has
public class MyController extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyController() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fname = request.getParameter("fname");
RequestDispatcher rd = null;
if (fname.equals("luis")) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("fname", "luis");
} else {
rd = request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}
}
And from there determine whether to show error.jsp or success.jsp, but right now I'm getting an "HTTP Status 500 - Error instantiating servlet class MyController". What could I be doing wrong? I'm thinking it may be a matter of paths/organizing directories rather than the code.
My web.xml has
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>MyController</servlet-name>
<display-name>MyController</display-name>
<description></description>
<servlet-class>MyController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyController</servlet-name>
<url-pattern>/MyController</url-pattern>
</servlet-mapping>
</web-app>
Thanks in advance for any help!

GWT + RPC Service - Error 404 NOT_FOUND

I'm building a gwt app with gmaps. When I call a service in a button click, the console in eclipse shows me the following:
PS: The service is only for testing purposes. I've not implemented the real service!
[WARN] 404 - POST /findmeagasstationweb/inserirpostorpc (127.0.0.1) 1422 bytes
Request headers
Host: 127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pt-pt,pt;q=0.8,en;q=0.5,en-us;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://127.0.0.1:8888/FindMeAGasStationWeb.html?gwt.codesvr=127.0.0.1:9997
X-GWT-Permutation: HostedMode
X-GWT-Module-Base: http://127.0.0.1:8888/findmeagasstationweb/
Content-Type: text/x-gwt-rpc; charset=utf-8
Content-Length: 225
Pragma: no-cache
Cache-Control: no-cache
Response headers
Content-Type: text/html; charset=iso-8859-1
Content-Length: 1422
The following code of my app:
Defined Servlets
<!-- Servlets -->
<servlet>
<servlet-name>insereServlet</servlet-name>
<servlet-class>com.pz.findmeagasstationweb.server.InsereNovoPostoImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>insereServlet</servlet-name>
<url-pattern>/inserirpostorpc/</url-pattern>
</servlet-mapping>
Class FindMeAGasStationWeb
package com.pz.findmeagasstationweb.client;
//imports are omitted
public class FindMeAGasStationWeb implements EntryPoint {
Label latLabel = new Label("Latitude");
TextBox latBox = new TextBox();
Label longLabel = new Label("Longitude");
TextBox longBox = new TextBox();
Label nameLabel = new Label("Nome do Posto");
TextBox nameBox = new TextBox();
Label descLabel = new Label("Descricao");
TextBox descBox = new TextBox();
Label sc95Label = new Label("Preco Gasolina 95");
TextBox sc95Box = new TextBox();
Label sc98Label = new Label("Preco Gasolina 98");
TextBox sc98Box = new TextBox();
Label gasoleoLabel = new Label("Preco Gasoleo");
TextBox gasoleoBox = new TextBox();
Button inserir = new Button("Inserir Posto");
Grid grid = new Grid(2, 8);
public int controlo;
public void onModuleLoad() {
final AsyncCallback<String> callback = new AsyncCallback<String>(){
public void onFailure(Throwable caught){
Window.alert("Falha a inserir os dados."+caught);
}
public void onSuccess(String result){
Window.alert(""+result);
}
};
grid.setWidget(0, 0, latLabel);
grid.setWidget(0, 1, latBox);
grid.setWidget(1, 0, longLabel);
grid.setWidget(1, 1, longBox);
grid.setWidget(0, 2, nameLabel);
grid.setWidget(0, 3, nameBox);
grid.setWidget(1, 2, descLabel);
grid.setWidget(1, 3, descBox);
grid.setWidget(0, 4, sc95Label);
grid.setWidget(0, 5, sc95Box);
grid.setWidget(1, 4, sc98Label);
grid.setWidget(1, 5, sc98Box);
grid.setWidget(0, 6, gasoleoLabel);
grid.setWidget(0, 7, gasoleoBox);
grid.setWidget(1, 7, inserir);
latBox.setEnabled(false);
longBox.setEnabled(false);
RootPanel.get().add(grid);
inserir.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
//.inserirPosto(latBox.getText(), longBox.getText(), nameBox.getText(), descBox.getText(),
try{
InsereNovoPostoAsync getServico = (InsereNovoPostoAsync) GWT.create(InsereNovoPosto.class);
ServiceDefTarget serviceDef = (ServiceDefTarget) getServico;
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL()
+ "inserirpostorpc");
getServico.inserirPosto("1","2", "a", "b", "1", "2", "3", callback);
}
catch(Exception ex){
Window.alert(""+ex);
}
//getServico().inserirPosto(latBox.getText(), longBox.getText(), nameBox.getText(), descBox.getText(), sc95Box.getText(), sc98Box.getText(), gasoleoBox.getText(), callback);
/*
(latBox.getText(), longBox.getText(), nameBox.getText(),
descBox.getText(), sc95Box.getText(), sc98Box.getText(),
gasoleoBox.getText(), callback);
/*RootPanel.get().add(
new Label("Thanks for your submission."));
Window.alert("Submit name=" + nameBox.getText()
+ "\naddress=" + addrBox.getText() + "\nphone="
+ phoneBox.getText());*/
}
});
MapWidget mapWiget = new MapWidget(LatLng.newInstance(48.136559, 11.576318), 13);
mapWiget.setSize("1024px", "500px");
mapWiget.addControl(new SmallMapControl());
mapWiget.addControl(new MapTypeControl());
mapWiget.addMapClickHandler(new MapClickHandler() {
public void onClick(MapClickEvent e) {
MapWidget sender = e.getSender();
Overlay overlay = e.getOverlay();
LatLng point = e.getLatLng();
if (overlay != null && overlay instanceof Marker) {
sender.removeOverlay(overlay);
latBox.setText("");
longBox.setText("");
controlo = 0;
} else {
if(controlo==0){
String a[] = point.toString().split(",");
String b = a[0].toString();
b = b.substring(1);
String c = a[1].toString();
c = c.substring(0, c.length()-1);
latBox.setText(""+b);
longBox.setText(""+c);
sender.addOverlay(new Marker(point));
controlo=1;
}
}
}
});
RootPanel.get().add(mapWiget);
}
}
Service:
InsereNovoPosto
package com.pz.findmeagasstationweb.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("inserirpostorpc")
public interface InsereNovoPosto extends RemoteService {
public String inserirPosto(String lat, String longi, String nome,
String descricao, String sc95, String sc98, String gasoleo);
}
InsereNovoPostoAsync
package com.pz.findmeagasstationweb.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface InsereNovoPostoAsync {
public void inserirPosto(String lat, String longi, String nome,
String descricao, String sc95, String sc98, String gasoleo, AsyncCallback<String> callback);
}
InsereNovoPostoImpl
package com.pz.findmeagasstationweb.server;
import com.pz.findmeagasstationweb.client.InsereNovoPosto;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
#SuppressWarnings("serial")
public class InsereNovoPostoImpl extends RemoteServiceServlet implements InsereNovoPosto {
#Override
public String inserirPosto(String lat, String longi, String nome,
String descricao, String sc95, String sc98, String gasoleo) {
Window.alert(""+lat+"-"+longi+"-"+nome+"-"+descricao+"-"+sc95+"-"+sc98+"-"+gasoleo);
return nome;
}
}
findmeagasstationweb.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
When updating your version of GWT, you should also update this DTD reference,
so that your app can take advantage of the latest GWT module capabilities.
-->
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.0//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.5.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='findmeagasstationweb'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
<!-- Other module inherits -->
<inherits name='com.google.gwt.maps.GoogleMaps'/>
<script src='http://maps.google.com/maps?gwt=1&file=api&v=2' />
<!-- Specify the app entry point class. -->
<entry-point class='com.pz.findmeagasstationweb.client.FindMeAGasStationWeb'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>
Any idea what's going wrong? Any help would be great... Thanks in advanced, and sorry for my bad english !
It is url pattern problem in web.xml, Please change it.
<url-pattern>/findmeagasstationweb/inserirpostorpc/</url-pattern>
To call RPC, you have written code like
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL()
+ "inserirpostorpc");
Here GWT.getModuleBaseURL() is "project module name" + inserirpostorpc.
You have mismatch w.r.t to url to which you are making the RPC request.
1) Your URL pattern in your rpc creation
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL()
+ "inserirpostorpc");
OR
2) Your URL pattern in web.xml
<url-pattern>/inserirpostorpc/</url-pattern>
You can change either of them to avoid the 404 error. Drop the GWT.getModuleBaseURL() or change URL pattern in web.xml to have /findmeagasstationweb/inserirpostorpc/
Just maintain uniformity across all rpc creation and web.xml mapping.
Here the complete login rpc :
onModuleLoad:
private final String loginRpc="loginrpc";
private final LoginServiceAsync loginService = GWT.create(LoginService.class);
((ServiceDefTarget) loginService).setServiceEntryPoint(loginRpc);
loginService.LoginRPC(
new AsyncCallback<obj>() {
#Override
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
#Override
public void onSuccess(Object obj) {
//TODO
}}
});
Web.xml
<servlet>
<servlet-name>loginrpc</servlet-name>
<servlet-class>com.my.test.LoginServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginrpc</servlet-name>
<url-pattern>/loginrpc</url-pattern>
</servlet-mapping>

jersey rest web services multiple format

how to return the correct representation based on URI
example
/text.json should return json
/text.xml should return xml
/text should return plain text
All these are mapped to the same method
#GET
public Contact getContacts()
{
}
The answer can be found in this post: http://jersey.576304.n2.nabble.com/extension-custom-negotiation-td3078866.html
Essentially you configure a ResourceConfig https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceConfig.html
You need to extend an implementation of ResourceConfig [1] and override the media type mappings method.
For example you can do the following:
package foo;
public class MyResourceConfig extends PackagesResourceConfig {
public PackagesResourceConfig(Map<String, Object> props) {
super(props);
}
public Map<String, MediaType> getMediaTypeMappings() {
Map<String, MediaType> m = new HashMap<String, MediaType> ();
m.put("json", MediaType.APPLICATION_JSON_TYPE);
m.put("xml", MediaType.APPLICATION_XML_TYPE);
return m;
}
}
and you can register your "MyResourceConfig" as described here:
https://jersey.dev.java.net/documentation/1.1.0-ea/user-guide.html#d4e115
In the above example your web.xml would need to container:
<web-app>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>foo.MyResourceConfig</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.foo.rest;org.bar.rest</param-value>
</init-param>
</servlet>
....