Appium parallel test threadlocal - appium

I am trying to run parallel test through selenium grid.
I know I have to use "thread local" for parallel execution,
but I have a problem with my code.
Cannot invoke "io.appium.java_client.android.AndroidDriver.findElementByAccessibilityId(String)" because "driver" is null
can you please solve it
package appiumset;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class _2_Deviceinfo {
public ThreadLocal<AppiumDriver> driver = new ThreadLocal<>();
public void setDriver(AppiumDriver driver) {
this.driver.set(driver);
}
public AppiumDriver getDriver() {
return this.driver.get();
}
#Parameters({"device", "apppackage", "activity","version","appiumServer" , "systemPort", "platformName"})
#BeforeMethod
public synchronized void deviceSetUp(String device, String apppackage, String activity, String version, String appiumServer, String systemPort, String platformName) throws InterruptedException, MalformedURLException {
System.out.println("****************************************");
System.out.println("Setting up device and desired capabilities");
DesiredCapabilities cap = new DesiredCapabilities();
URL url = new URL(appiumServer);
setDriver(new AndroidDriver<>(url, cap));
cap.setCapability(MobileCapabilityType.DEVICE_NAME, device);
cap.setCapability(MobileCapabilityType.UDID, device);
cap.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, systemPort);
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120);
cap.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
//cap.setCapability(MobileCapabilityType., BrowserType.ANDROID);
cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version);
cap.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, apppackage);
cap.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, activity);
cap.setCapability("automationName", "UiAutomator2");
cap.setCapability("noReset","false");
cap.setCapability("FullReset","true");
cap.setCapability("APP_WAIT_ACTIVITY", "*");
cap.setCapability("autowebview","false");
}
#AfterMethod
public void closeDriver() {
getDriver().quit();
}
}
I can't find the driver (AppiumDriver)
package appiumset;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
public class _3_Onboarding extends _1_Appstart {
#Test
public void onboarding() throws MalformedURLException, InterruptedException {
System.out.println("_3_Onboarding Start");
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();
System.out.println("next-done");
}
}

call getdriver() method of your class _2_Deviceinfo to your test class.
Appiumdriver<?> driver = getDriver();
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();

Related

Cannot invoke "io.appium.java_client.android.AndroidDriver.manage()" because "this.driver" is null

I am new to Appium and just getting started, I would like to call methods from other classes by creating an object. but when I call methods it show "this.driver" is null. how to call methods from other class by creating object?? is it possible?? Noted that: I already use 'extends class', so I didn't use it in multiple classes.
//Here, I call methods from other classes......
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
//import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
#Test(priority = 11)
public void IncompleteTask() {
String ser="Update For Testing";
Searching(ser);
AllMethods scr=new AllMethods(driver);
scr.Scroll();
//Scroll();
Point point1=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getCenter();
Point point2=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getLocation();
Swipping(point1,point2);
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_reAssign").click();
//driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/noButton").click();
String mass=driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/tvMessage").getText();
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
String mText="Are you sure you want to undo this Task?";
if(mass.contains(mText))
{
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
}
System.out.println("IncompleteTask Executed!");
driver.quit();
}
//Here is my allMethods class
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.support.PageFactory;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.io.IOException;
import java.lang.NullPointerException;
public class AllMethods {
public AndroidDriver<AndroidElement> driver;
public AllMethods(AndroidDriver driver)
{
PageFactory.initElements(driver, this);
}
public void searching(String ser) {
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_search").click();
driver.findElementById("android:id/search_src_text").sendKeys(ser);
driver.hideKeyboard();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void Scroll() throws NullPointerException
{
for(int i=0; i<3; i++)
{
Dimension dimension=driver.manage().window().getSize();
int start_x=(int) (dimension.width*0.5);
int start_y=(int) (dimension.height*0.2);
int end_x=(int) (dimension.width*0.5);
int end_y=(int) (dimension.height*0.8);
TouchAction tcD=new TouchAction(driver);
tcD.press(PointOption.point(start_x,
start_y)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2)))
.moveTo(PointOption.point(end_x, end_y)).release().perform();
}
}
}
The methods in AllMethods class are referring to the driver which is not yet initialized. i.e they are referring to this driver :
public AndroidDriver<AndroidElement> driver;
You will need to add this.driver=driver inside AllMethods constructor, this will set the driver with the reference of the driver that is passed in the constructor.

How to test AuthenticationPrincipal and getting an ID Token in Spring Security?

I have the following LogoutResource class that returns an ID Token.
package com.mycompany.myapp.web.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* REST controller for managing global OIDC logout.
*/
#RestController
public class LogoutResource {
private ClientRegistration registration;
public LogoutResource(ClientRegistrationRepository registrations) {
this.registration = registrations.findByRegistrationId("oidc");
}
/**
* {#code POST /api/logout} : logout the current user.
*
* #param request the {#link HttpServletRequest}.
* #param idToken the ID token.
* #return the {#link ResponseEntity} with status {#code 200 (OK)} and a body with a global logout URL and ID token.
*/
#PostMapping("/api/logout")
public ResponseEntity<?> logout(HttpServletRequest request,
#AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
String logoutUrl = this.registration.getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
Map<String, String> logoutDetails = new HashMap<>();
logoutDetails.put("logoutUrl", logoutUrl);
logoutDetails.put("idToken", idToken.getTokenValue());
request.getSession().invalidate();
return ResponseEntity.ok().body(logoutDetails);
}
}
This works, but I'd like to test it. I tried the following:
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.config.Constants;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() {
LogoutResource logoutResource = new LogoutResource(registrations);
this.restLogoutMockMvc = MockMvcBuilders.standaloneSetup(logoutResource)
.setMessageConverters(jacksonMessageConverter).build();
}
#Test
public void getLogoutInformation() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout")
.with(authentication(createMockOAuth2AuthenticationToken(idToken))))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl));
}
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}
However, this results in the following error:
Caused by: java.lang.IllegalArgumentException: tokenValue cannot be empty
at org.springframework.util.Assert.hasText(Assert.java:284)
at org.springframework.security.oauth2.core.AbstractOAuth2Token.<init>(AbstractOAuth2Token.java:55)
at org.springframework.security.oauth2.core.oidc.OidcIdToken.<init>(OidcIdToken.java:53)
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)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
Does anyone know of a way to mock AuthenticationPrincipal and have it return a preset ID token?
Answer provided by Joe Grandja from the Spring Security Team:
The AuthenticationPrincipalArgumentResolver is not getting registered in your test.
NOTE: It automatically gets registered when the "full" spring-web-mvc is enabled, e.g #EnableWebMvc
However, in your #Before, you have:
MockMvcBuilders.standaloneSetup() - this does not initialize the full web-mvc infrastructure - only a subset
Try this instead:
MockMvcBuilders.webAppContextSetup(this.context) - this will register AuthenticationPrincipalArgumentResolver and your test should resolve the OidcIdToken.
I changed my test to the following and now everything passes. Thanks Joe!
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private WebApplicationContext context;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
SecurityContextHolder.getContext().setAuthentication(authenticationToken(idToken));
SecurityContextHolderAwareRequestFilter authInjector = new SecurityContextHolderAwareRequestFilter();
authInjector.afterPropertiesSet();
this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
#Test
public void getLogoutInformation() throws Exception {
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl))
.andExpect(jsonPath("$.idToken").value(ID_TOKEN));
}
private OAuth2AuthenticationToken authenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}

Error:(73, 5) error: illegal start of expression

anyone can help me?
I'm amateur in android programming.
that's my code:
package com.example.aleta.dbapp;
/**
* Created by aleta on 24/07/2017.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class ForSpinner{
Connection connect;
PreparedStatement stmt;
ResultSet rs;
string srvr,dbn;
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.spinners);
srvr="DESKTOP-F27TAGV\\ALETAYEB_DB";
db="shop_db";
spinnerstate=(Spinner)
findViewById(R.id.spinnerstate);
connect=CONN;
String query="select Title from ostan";
connect=CONN;
stmt=connect.prepareStatement(query);
rs=stmt.executeQuery();
ArrayList<String> data=new ArrayList<String>();
while (rs.next()){
String id=rs.getString("ostan");
data.add(id);
}
String[] array=data.toArray(new String[0]);
ArrayAdapter NoCoreAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,data);
spinnerstate.setAdapter(NoCoreAdapter);
spinnerstate.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id){
String name=spinnerstate.getSelectedItem().toString();
Toast.makeText(ForSpinner.this,name,Toast.LENGTH_SHORT()).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
#SuppressLint("NewApi")
private Connection CONN(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy((policy));
Connection conn=null;
String ConnURL=null;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL="jdbc:jtds:sqlserver://" + srvr + ";"
+ "databaseName=" + dbn + ";Integrated security=true;";
conn=DriverManager.getConnection(ConnURL);
return conn;
}
}
}
but an error occurred :
Error:(73, 28) error: ';' expected
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 2.572 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console
how i can solve that?

How to start appium test on iOS simulator?

I have the following setup and trying to start the test on iOS Simulator. I am a beginner and don't know how to start the test. I have already imported and installed appium from tutorials.
The questions are:
Is this setup correct?
How to run the tests?
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class AppiumDriver {
private static final String JavascriptExecutor = null;
public WebDriver driver = null;
#BeforeMethod
public void setUp() throws Exception {
// set up appium
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "8.1");
capabilities.setCapability(CapabilityType.PLATFORM, "Mac");
capabilities.setCapability("device", "iPhone");
capabilities.setCapability("app", "path here, i have started it with appium inspector and it works");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4725/wd/hub"), capabilities);
System.out.println("App launched");
}
#Test
public void test01() throws InterruptedException {
driver.findElement(By.name("Guest")).click();
Thread.sleep(5000);
}
#AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}
Yes, your setup is correct. Looks like you are using testng framework so just run it as "testng" and you should be good to go.

Is there any easy way to perform Junit test for WSDL WS-I compliance

I am trying to validate generated WSDL to be correct. I have tried WS-i test tool downloaded from http://www.ws-i.org/ but it's test tool require all input to go through a config xml and the output is again an output xml file. Is there other easier way of validating a WSDL?
The Woden library/jar provides adequate functionality to be able to do this. If your wsdl isn't valid, the last statement, reader.readWSDL(...), will throw an exception.
import static junit.framework.Assert.fail;
import java.net.URISyntaxException;
import org.apache.woden.WSDLException;
import org.apache.woden.WSDLFactory;
import org.apache.woden.WSDLReader;
import org.apache.woden.wsdl20.Description;
import org.junit.Test;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
#Test
public void validateWSDL2() throws WSDLException {
String wsdlUri = null;
try {
wsdlUri = this.getClass().getResource(wsdlFileName).toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
WSDLFactory factory = WSDLFactory.newInstance("org.apache.woden.internal.OMWSDLFactory");
WSDLReader reader = factory.newWSDLReader();
reader.setFeature(WSDLReader.FEATURE_VALIDATION, true);
reader.readWSDL(wsdlUri);
}
}
And should you need a unit test for WSDL 1.1, see the following:
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.fail;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.stream.XMLStreamException;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import com.sun.xml.ws.api.model.wsdl.WSDLModel;
import com.sun.xml.ws.api.server.SDDocumentSource;
import com.sun.xml.ws.api.wsdl.parser.WSDLParserExtension;
import com.sun.xml.ws.api.wsdl.parser.XMLEntityResolver;
public class WSDLValidationTest {
String wsdlFileName = "/MyService.wsdl";
String wsdlUri = null;
URL wsdlUrl = null;
#Before
public void before()
{
try {
wsdlUrl = this.getClass().getResource(wsdlFileName);
wsdlUri = wsdlUrl.toURI().toString();
}
catch( URISyntaxException urise) {
urise.printStackTrace();
fail( "Unable to retrieve wsdl: " + urise.getMessage());
}
}
#Test
public void parseAndValidateWSDL1_1WithWSDL4J() throws WSDLException
{
WSDLReader wsdlReader = null;
try {
WSDLFactory factory = WSDLFactory.newInstance();
wsdlReader = factory.newWSDLReader();
}
catch( WSDLException wsdle) {
wsdle.printStackTrace();
fail( "Unable to instantiate wsdl reader: " + wsdle.getMessage());
}
// Read WSDL service interface document
Definition def = wsdlReader.readWSDL(null, wsdlUri);
assertNotNull(def);
}
#Test
public void parseAndValidateWSDL1_1WithJaxWS() throws IOException, XMLStreamException, SAXException
{
final SDDocumentSource doc = SDDocumentSource.create(wsdlUrl);
final XMLEntityResolver.Parser parser = new XMLEntityResolver.Parser(doc);
WSDLModel model = WSDLModel.WSDLParser.parse( parser, null, false, new WSDLParserExtension[] {} );
assertNotNull(model);
}
}

Resources