Mock URL and HttpURLConnection using PowerMockito - url

I am having an issue when mocking URL and HttpURLConnection class.
TestNG is being used as the testing framework because of a limitation that we have.
The test class looks like the following
package com.ericsson.msran.test.stability.environmentmanager.service.batc.restore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.entity.ContentType;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.ericsson.msran.test.stability.environmentmanager.service.Service;
import com.ericsson.msran.test.stability.environmentmanager.service.ServiceException;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCConfig;
import com.ericsson.msran.test.stability.environmentmanager.service.batc.BatCServiceException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
#PowerMockIgnore({ "org.apache.logging.log4j.*" })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ BatCConfig.class, Service.class })
public class RestoreSnapshotServiceTest extends PowerMockTestCase {
HttpURLConnection httpURLConnection;
URL mockedURL;
#BeforeClass
public void setUp() throws MalformedURLException, IOException {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(BatCConfig.class);
}
#Test
public void testRestoreSnapshot() throws Exception {
String jsonResponse = "{\"apiVersion\":\"0.1.0\",\"method\":\"restoreCampaignSnapshot\",\"params\":{\"campaignSnapshotId\":3,\"campaignName\":\"testCampaign3\"},\"data\":{\"newCampaignId\":607}}";
JsonObject response = new JsonParser().parse(jsonResponse).getAsJsonObject();
Mockito.when(BatCConfig.getBatCServiceUrl()).thenReturn(new URL("https://lte-iov.rnd.ki.sw.ericsson.se/batc/"));
mockedURL = PowerMockito.mock(URL.class);
httpURLConnection = PowerMockito.mock(HttpURLConnection.class);
PowerMockito.whenNew(URL.class).withArguments("https://lte-iov.rnd.ki.sw.ericsson.se/batc/restoreCampaignSnapshot").thenReturn(mockedURL);
Mockito.when(mockedURL.openConnection()).thenReturn(httpURLConnection);
Mockito.when(httpURLConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_BAD_GATEWAY);
Mockito.when(httpURLConnection.getContentType()).thenReturn(ContentType.APPLICATION_JSON.getMimeType());
Mockito.doNothing().when(httpURLConnection).connect();
Mockito.when(httpURLConnection.getOutputStream()).thenReturn(null);
Mockito.when(httpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonResponse.getBytes()));
String name = RestoreSnapshotService.restoreSnapshot(3, "testCampaign4");
Assert.assertEquals(name, "testCampaign4");
}
}
When I test the real class (Service) in this case, the mock is not being used but instead the real object. Any help is appreciated!
The sample code under test looks like the following
protected static JsonObject callEndpoint(URL url, ServiceRequestMethod requestMethod, JsonObject requestBody)
throws ServiceException {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty(REQUEST_PROP_KEY, REQUEST_PROP_VAL);
connection.setConnectTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setReadTimeout(REQUEST_TIMEOUT_MILLIS);
connection.setRequestMethod(requestMethod.name());
if (requestMethod == ServiceRequestMethod.POST) {
connection.setDoOutput(true);
}
connection.connect();
if (requestMethod == ServiceRequestMethod.POST) {
final OutputStream os = connection.getOutputStream();
os.write(requestBody.toString().getBytes("UTF-8"));
os.close();
}
final int status = connection.getResponseCode();
final String contentType = connection.getContentType();
log("Recieved response with status={} and ContentType={}", status, contentType);
if (HttpURLConnection.HTTP_OK == status && RESPONSE_TYPE_JSON.equals(contentType)) {
return mapResponse(connection.getInputStream());
} else {
throw new ServiceException("Response from service NOK, status=" + status);
}
} catch (IOException e) {
throw new ServiceException("Could not connect to service", e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}

Related

Appium parallel test threadlocal

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();

Twilio programmable sms

I am getting below exception while using the twilio programmable sms
com.twilio.exception.ApiException: api.twilio.com
at com.twilio.http.NetworkHttpClient.makeRequest(NetworkHttpClient.java:128)
at com.twilio.http.HttpClient.reliableRequest(HttpClient.java:42)
at com.twilio.http.HttpClient.reliableRequest(HttpClient.java:25)
at com.twilio.http.TwilioRestClient.request(TwilioRestClient.java:42)
at com.twilio.rest.api.v2010.account.MessageCreator.create
(MessageCreator.java:391)
at
com.twilio.rest.api.v2010.account.MessageCreator.create
(MessageCreator.java:25)
at com.twilio.base.Creator.create(Creator.java:45)
at Example.main(Example.java:24)
Below is that that i am using
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.rest.api.v2010.account.MessageCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.exception.ApiException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
public class Example
{
private final static String ACCOUNT_SID =
System.getenv("TWILIO_ACCOUNT_SID");
private final static String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");
public static void main(String[] args) {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
Message sms;
try {
sms = Message.creator(new PhoneNumber("+919250057864"), new
PhoneNumber("+16672132498"), "").create();
System.out.println(sms.getSid());
} catch (ApiException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I am using twilio-7.15.6-jar-with-dependencies library.

How can I test HMAC authentication using Dropwizard?

I'm just getting started with Dropwizard 0.4.0, and I would like some help with HMAC authentication. Has anybody got any advice?
Thank you in advance.
At present Dropwizard doesn't support HMAC authentication right out of the box, so you'd have to write your own authenticator. A typical choice for HMAC authentication is to use the HTTP Authorization header. The following code expects this header in the following format:
Authorization: <algorithm> <apiKey> <digest>
An example would be
Authorization: HmacSHA1 abcd-efgh-1234 sdafkljlkansdaflk2354jlkj5345345dflkmsdf
The digest is built from the content of the body (marshalled entity) prior to URL encoding with the HMAC shared secret appended as base64. For a non-body request, such as GET or HEAD, the content is taken as the complete URI path and parameters with the secret key appended.
To implement this in a way that Dropwizard can work with it requires you to copy the BasicAuthenticator code present in the dropwizard-auth module into your own code and modify it with something like this:
import com.google.common.base.Optional;
import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
import com.yammer.dropwizard.auth.AuthenticationException;
import com.yammer.dropwizard.auth.Authenticator;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
class HmacAuthInjectable<T> extends AbstractHttpContextInjectable<T> {
private static final String PREFIX = "HmacSHA1";
private static final String HEADER_VALUE = PREFIX + " realm=\"%s\"";
private final Authenticator<HmacCredentials, T> authenticator;
private final String realm;
private final boolean required;
HmacAuthInjectable(Authenticator<HmacCredentials, T> authenticator, String realm, boolean required) {
this.authenticator = authenticator;
this.realm = realm;
this.required = required;
}
public Authenticator<HmacCredentials, T> getAuthenticator() {
return authenticator;
}
public String getRealm() {
return realm;
}
public boolean isRequired() {
return required;
}
#Override
public T getValue(HttpContext c) {
try {
final String header = c.getRequest().getHeaderValue(HttpHeaders.AUTHORIZATION);
if (header != null) {
final String[] authTokens = header.split(" ");
if (authTokens.length != 3) {
// Malformed
HmacAuthProvider.LOG.debug("Error decoding credentials (length is {})", authTokens.length);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
final String algorithm = authTokens[0];
final String apiKey = authTokens[1];
final String signature = authTokens[2];
final String contents;
// Determine which part of the request will be used for the content
final String method = c.getRequest().getMethod().toUpperCase();
if ("GET".equals(method) ||
"HEAD".equals(method) ||
"DELETE".equals(method)) {
// No entity so use the URI
contents = c.getRequest().getRequestUri().toString();
} else {
// Potentially have an entity (even in OPTIONS) so use that
contents = c.getRequest().getEntity(String.class);
}
final HmacCredentials credentials = new HmacCredentials(algorithm, apiKey, signature, contents);
final Optional<T> result = authenticator.authenticate(credentials);
if (result.isPresent()) {
return result.get();
}
}
} catch (IllegalArgumentException e) {
HmacAuthProvider.LOG.debug(e, "Error decoding credentials");
} catch (AuthenticationException e) {
HmacAuthProvider.LOG.warn(e, "Error authenticating credentials");
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
if (required) {
throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.AUTHORIZATION,
String.format(HEADER_VALUE, realm))
.entity("Credentials are required to access this resource.")
.type(MediaType.TEXT_PLAIN_TYPE)
.build());
}
return null;
}
}
The above is not perfect, but it'll get you started. You may want to refer to the MultiBit Merchant release candidate source code (MIT license) for a more up to date version and the various supporting classes.
The next step is to integrate the authentication process into your ResourceTest subclass. Unfortunately, Dropwizard doesn't provide a good entry point for authentication providers in v0.4.0, so you may want to introduce your own base class, similar to this:
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.LowLevelAppDescriptor;
import com.xeiam.xchange.utils.CryptoUtils;
import com.yammer.dropwizard.bundles.JavaBundle;
import com.yammer.dropwizard.jersey.DropwizardResourceConfig;
import com.yammer.dropwizard.jersey.JacksonMessageBodyProvider;
import com.yammer.dropwizard.json.Json;
import org.codehaus.jackson.map.Module;
import org.junit.After;
import org.junit.Before;
import org.multibit.mbm.auth.hmac.HmacAuthProvider;
import org.multibit.mbm.auth.hmac.HmacAuthenticator;
import org.multibit.mbm.persistence.dao.UserDao;
import org.multibit.mbm.persistence.dto.User;
import org.multibit.mbm.persistence.dto.UserBuilder;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Set;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A base test class for testing Dropwizard resources.
*/
public abstract class BaseResourceTest {
private final Set<Object> singletons = Sets.newHashSet();
private final Set<Object> providers = Sets.newHashSet();
private final List<Module> modules = Lists.newArrayList();
private JerseyTest test;
protected abstract void setUpResources() throws Exception;
protected void addResource(Object resource) {
singletons.add(resource);
}
public void addProvider(Object provider) {
providers.add(provider);
}
protected void addJacksonModule(Module module) {
modules.add(module);
}
protected Json getJson() {
return new Json();
}
protected Client client() {
return test.client();
}
#Before
public void setUpJersey() throws Exception {
setUpResources();
this.test = new JerseyTest() {
#Override
protected AppDescriptor configure() {
final DropwizardResourceConfig config = new DropwizardResourceConfig();
for (Object provider : JavaBundle.DEFAULT_PROVIDERS) { // sorry, Scala folks
config.getSingletons().add(provider);
}
for (Object provider : providers) {
config.getSingletons().add(provider);
}
Json json = getJson();
for (Module module : modules) {
json.registerModule(module);
}
config.getSingletons().add(new JacksonMessageBodyProvider(json));
config.getSingletons().addAll(singletons);
return new LowLevelAppDescriptor.Builder(config).build();
}
};
test.setUp();
}
#After
public void tearDownJersey() throws Exception {
if (test != null) {
test.tearDown();
}
}
/**
* #param contents The content to sign with the default HMAC process (POST body, GET resource path)
* #return
*/
protected String buildHmacAuthorization(String contents, String apiKey, String secretKey) throws UnsupportedEncodingException, GeneralSecurityException {
return String.format("HmacSHA1 %s %s",apiKey, CryptoUtils.computeSignature("HmacSHA1", contents, secretKey));
}
protected void setUpAuthenticator() {
User user = UserBuilder
.getInstance()
.setUUID("abc123")
.setSecretKey("def456")
.build();
//
UserDao userDao = mock(UserDao.class);
when(userDao.getUserByUUID("abc123")).thenReturn(user);
HmacAuthenticator authenticator = new HmacAuthenticator();
authenticator.setUserDao(userDao);
addProvider(new HmacAuthProvider<User>(authenticator, "REST"));
}
}
Again, the above code is not perfect, but the idea is to allow a mocked up UserDao to provide a standard user with a known shared secret key. You'd have to introduce your own UserBuilder implementation for testing purposes.
Finally, with the above code a Dropwizard Resource that had an endpoint like this:
import com.google.common.base.Optional;
import com.yammer.dropwizard.auth.Auth;
import com.yammer.metrics.annotation.Timed;
import org.multibit.mbm.core.Saying;
import org.multibit.mbm.persistence.dto.User;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicLong;
#Path("/")
#Produces(MediaType.APPLICATION_JSON)
public class HelloWorldResource {
private final String template;
private final String defaultName;
private final AtomicLong counter;
public HelloWorldResource(String template, String defaultName) {
this.template = template;
this.defaultName = defaultName;
this.counter = new AtomicLong();
}
#GET
#Timed
#Path("/hello-world")
public Saying sayHello(#QueryParam("name") Optional<String> name) {
return new Saying(counter.incrementAndGet(),
String.format(template, name.or(defaultName)));
}
#GET
#Timed
#Path("/secret")
public Saying saySecuredHello(#Auth User user) {
return new Saying(counter.incrementAndGet(),
"You cracked the code!");
}
}
could be tested with a unit test that was configured like this:
import org.junit.Test;
import org.multibit.mbm.core.Saying;
import org.multibit.mbm.test.BaseResourceTest;
import javax.ws.rs.core.HttpHeaders;
import static org.junit.Assert.assertEquals;
public class HelloWorldResourceTest extends BaseResourceTest {
#Override
protected void setUpResources() {
addResource(new HelloWorldResource("Hello, %s!","Stranger"));
setUpAuthenticator();
}
#Test
public void simpleResourceTest() throws Exception {
Saying expectedSaying = new Saying(1,"Hello, Stranger!");
Saying actualSaying = client()
.resource("/hello-world")
.get(Saying.class);
assertEquals("GET hello-world returns a default",expectedSaying.getContent(),actualSaying.getContent());
}
#Test
public void hmacResourceTest() throws Exception {
String authorization = buildHmacAuthorization("/secret", "abc123", "def456");
Saying actual = client()
.resource("/secret")
.header(HttpHeaders.AUTHORIZATION, authorization)
.get(Saying.class);
assertEquals("GET secret returns unauthorized","You cracked the code!", actual.getContent());
}
}
Hope this helps you get started.

parsing with dom4j

I am successfully retrieve the data of response using xpath expression /abcde/response from the xml ,
<abcde>
<response>000</response>
</abcde>
But couldnt retrieve the data of response from the same xml but with some additional data
<abcde version="8.1" xmlns="http://www.litle.com/schema"
response="0" message="Valid Format">
<response>000</response>
</abcde>
What am i doing wrong ?
package stackoverflow;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.jaxen.VariableContext;
public class MakejdomWork {
public static void main(String[] args) {
new MakejdomWork().run();
}
public void run() {
ByteArrayInputStream bis = new ByteArrayInputStream("<abcde version=\"8.1\" xmlns=\"http://www.litle.com/schema\" response=\"0\" message=\"Valid Format\"> <response>000</response></abcde>".getBytes());
//ByteArrayInputStream bis = new ByteArrayInputStream("<abcde><response>000</response></abcde>".getBytes());
Map nsPrefixes = new HashMap();
nsPrefixes.put( "x", "http://www.litle.com/schema" );
DocumentFactory factory = new DocumentFactory();
factory.setXPathNamespaceURIs( nsPrefixes );
SAXReader reader = new SAXReader();
reader.setDocumentFactory( factory );
Document doc;
try {
doc = reader.read( bis );
Object value = doc.valueOf("/abcde/x:response");
System.out.println(value);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
Short answer: you need to use namespace prefixes if your parser is namespace aware (which dom4j is)

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