I need to communicate with a soap webservice (through a VPN tunnel) which requires
a) https (with custom certificates)
b) ntlm authentication
Thanks to pedrofb ( JAX-WS, trusting all ssl certificates not working ) I got SSL (by ignoring certifiactes) "working".
But now I end up not getting through the NTLM authentication...
The credentials I have are correct. I have tested these using cUrl and a minimal HttpClient-only unitTest.
The (ntlm authentication) relevant code looks alike:
public class NtlmAuthenticator extends Authenticator
{
private final String username;
private final char[] password;
public NtlmAuthenticator ( final String username, final String password )
{
super();
this.username = username;
this.password = password.toCharArray();
}
#Override
public PasswordAuthentication getPasswordAuthentication ()
{
return new PasswordAuthentication( username, password );
}
}
...
String ntlmDomain = properties.getProperty( "ntlmDomain" );
String ntlmUser = properties.getProperty( "ntlmUser" );
String ntlmPassword = properties.getProperty( "ntlmPassword" );
String username = ( StringUtils.isNotBlank( ntlmDomain ) ? ntlmDomain + '\\' : "" ) + ntlmUser;
Authenticator.setDefault( new NtlmAuthenticator( username, ntlmPassword ) );
....
Client client = ClientProxy.getClient( tmpSoapService );
// SSL stuff
final HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
TLSClientParameters params = httpConduit.getTlsClientParameters();
if ( params == null )
{
params = new TLSClientParameters();
httpConduit.setTlsClientParameters( params );
}
params.setTrustManagers( new TrustManager[] { new NaiveTrustManager() } );
params.setDisableCNCheck( true );
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout( connectTimeout );
httpClientPolicy.setReceiveTimeout( responseTimeout );
httpClientPolicy.setAllowChunking( false );
httpConduit.setClient( httpClientPolicy );
final BindingProvider bp = (BindingProvider) tmpSoapService;
final Map<String, Object> requestContext = bp.getRequestContext();
requestContext.put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, serviceUrl );
requestContext.put( BindingProvider.USERNAME_PROPERTY, username );
requestContext.put( BindingProvider.PASSWORD_PROPERTY, ntlmPassword );
I get to see the following log output:
org.apache.cxf.interceptor.Fault: Could not send Message.
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:64) ~[cxf-core.jar:3.0.1]
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307) ~[cxf-core.jar:3.0.1]
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:516) [cxf-core.jar:3.0.1]
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:425) [cxf-core.jar:3.0.1]
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:326) [cxf-core.jar:3.0.1]
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:279) [cxf-core.jar:3.0.1]
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96) [cxf-rt-frontend-simple.jar:3.0.1]
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:138) [cxf-rt-frontend-jaxws.jar:3.0.1]
at com.sun.proxy.$Proxy49.nasMgmtRequest(Unknown Source) [na:na]
...
Caused by: org.apache.cxf.transport.http.HTTPException: HTTP response '401: Unauthorized' when communicating with <!! webservice url !!>
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.doProcessResponseCode(HTTPConduit.java:1603) ~[cxf-rt-transports-http.jar:3.0.1]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1610) ~[cxf-rt-transports-http.jar:3.0.1]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1551) ~[cxf-rt-transports-http.jar:3.0.1]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1348) ~[cxf-rt-transports-http.jar:3.0.1]
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56) ~[cxf-core.jar:3.0.1]
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:651) ~[cxf-rt-transports-http.jar:3.0.1]
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62) ~[cxf-core.jar:3.0.1]
... 39 common frames omitted
NtlmAuthenticator is being consulted, stacktrace:
NtlmAuthenticator.getPasswordAuthentication() line: 24
NativeMethodAccessorImpl.invoke0(Method, Object, Object[]) line: not available [native method]
NativeMethodAccessorImpl.invoke(Object, Object[]) line: 62
DelegatingMethodAccessorImpl.invoke(Object, Object[]) line: 43
Method.invoke(Object, Object...) line: 498
ReferencingAuthenticator.tryWith(Authenticator) line: 132
ReferencingAuthenticator.getPasswordAuthentication() line: 46
Authenticator.requestPasswordAuthentication(String, InetAddress, int, String, String, String, URL, Authenticator$RequestorType) line: 317
HttpURLConnection$1.run() line: 420
HttpURLConnection$1.run() line: 415
AccessController.doPrivileged(PrivilegedAction<T>) line: not available [native method]
HttpURLConnection.privilegedRequestPasswordAuthentication(String, InetAddress, int, String, String, String, URL, Authenticator$RequestorType) line: 414
DelegateHttpsURLConnection(HttpURLConnection).getServerAuthentication(AuthenticationHeader) line: 2425
DelegateHttpsURLConnection(HttpURLConnection).getInputStream0() line: 1683
DelegateHttpsURLConnection(HttpURLConnection).getInputStream() line: 1441
DelegateHttpsURLConnection(HttpURLConnection).getHeaderFields() line: 2966
HttpsURLConnectionImpl.getHeaderFields() line: 283
Headers.readFromConnection(HttpURLConnection) line: 258
URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.updateCookiesBeforeRetransmit() line: 297
URLConnectionHTTPConduit$URLConnectionWrappedOutputStream(HTTPConduit$WrappedOutputStream).handleRetransmits() line: 1410
URLConnectionHTTPConduit$URLConnectionWrappedOutputStream(HTTPConduit$WrappedOutputStream).handleResponse() line: 1546
URLConnectionHTTPConduit$URLConnectionWrappedOutputStream(HTTPConduit$WrappedOutputStream).close() line: 1348
URLConnectionHTTPConduit(AbstractConduit).close(Message) line: 56
URLConnectionHTTPConduit(HTTPConduit).close(Message) line: 651
MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(Message) line: 62
PhaseInterceptorChain.doIntercept(Message) line: 307
ClientImpl.doInvoke(ClientCallback, BindingOperationInfo, Object[], Map<String,Object>, Exchange) line: 516
ClientImpl.invoke(BindingOperationInfo, Object[], Map<String,Object>, Exchange) line: 425
ClientImpl.invoke(BindingOperationInfo, Object[], Exchange) line: 326
ClientImpl.invoke(BindingOperationInfo, Object...) line: 279
JaxWsClientProxy(ClientProxy).invokeSync(Method, BindingOperationInfo, Object[]) line: 96
JaxWsClientProxy.invoke(Object, Method, Object[]) line: 138
...
I am not sure this stacktrace reveils/denotes a ntlm authentication attempt, though?
I also tried
httpConduit.getAuthorization().setAuthorizationType( "NTLM" );
httpConduit.getAuthorization().setUserName( username );
httpConduit.getAuthorization().setPassword( ntlmPassword );
which results in
Caused by: java.io.IOException: Authorization loop detected on Conduit "{urn:microsoft-dynamics-schemas/codeunit/RB_Web}RB_Web_Port.http-conduit" on URL "https://10.5.46.136:7057/NAVTEST/WS/RS%20Vertriebs%20AG/Codeunit/RB_Web" with realm "null"
at org.apache.cxf.transport.http.HTTPConduit.detectAuthorizationLoop(HTTPConduit.java:1930) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit.access$600(HTTPConduit.java:147) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.authorizationRetransmit(HTTPConduit.java:1507) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.processRetransmit(HTTPConduit.java:1438) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleRetransmits(HTTPConduit.java:1412) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1546) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1348) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56) ~[cxf-core.jar:3.0.9]
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:651) ~[cxf-rt-transports-http.jar:3.0.9]
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62) ~[cxf-core.jar:3.0.9]
Any advices?
Thx in advance
Clemens
Related
I try to authenticate from my react front end by sending request to my spring boot backend which uses spring security but it fails returning that error in the console:
Uncaught (in promise) AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
knowing that that works fine from postman and returns the access token
Here is my react code:
const handleSubmit = () =>{
var formBody = [];
for (var property in authenticationData) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(authenticationData[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
api.post('/login', formBody).then(res=>{
console.log(res)
localStorage.setItem('jwt-access-token', res.data.access_token)
})
}
And this my spring security authentication filter:
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = request.getParameter("username");
String password = request.getParameter("password");
log.info("Username is : {}", username); log.info("Password is : {}", password);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
return authenticationManager.authenticate(authenticationToken);
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
log.info("Authentication successful congras");
User user = (User) authResult.getPrincipal();
Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
String access_token = JWT.create()
.withSubject(user.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + 10*60*1000))
.withIssuer(request.getRequestURL().toString())
.withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
.sign(algorithm);
String refresh_token = JWT.create()
.withSubject(user.getUsername())
.withExpiresAt(new Date(System.currentTimeMillis() + 30*60*1000))
.withIssuer(request.getRequestURL().toString())
.sign(algorithm);
/*response.setHeader("access_token", access_token);
response.setHeader("refresh_token", refresh_token);*/
Map<String, String> tokens = new HashMap<>();
tokens.put("access_token", access_token);
tokens.put("refresh_token", refresh_token);
response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
Can any one help me please?
I am developing Resteasy. I migrated my application's maven dependencies from 2.2.x to 3.0.x and suddenly I saw most of the API's are deprecated. So this migration has affect to my code and test cases as its simply saying deprecated in my whole code.
I am taking example of my test cases:
Test case with earlier version(in latest version it deprectaed as mentioned in link: ClientRequestFactory RestEasy Deprecated... Any other RestEasy alternative ?):
import org.jboss.resteasy.util.GenericType;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
#Test
public void testGetStudent() throws Exception{
String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
ClientRequest request = new ClientRequest(str);
ClientResponse<List<Student>> response = request.get(new GenericType<List<Student>>(){});
List<Student> students = response.getEntity();
System.out.println("Size : "+students.size());
}
So I refactore my test case to use
#Test
public void testGetStudents(){
final String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
Client client = ClientBuilder.newClient();
// Client client = ClientBuilder.newBuilder().build(); // This also works, OR
Response response = client.target(str).request().get();
// This will gives us whole XML output
String s = response.readEntity(String.class);
System.out.println(s);
**What is the replacement of below two lines in latest version? How I can get List of Student Object ?**
// ClientResponse<List<Student>> response = request.get(new GenericType<List<Student>>(){});
// List<Student> students = response.getEntity();
}
Please guide. What is the replacement of below two lines in latest version? How I can get List of Student Object ?
Edit-1: I tried below, but giving following error:
Students.java
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "students")
public class Students {
#XmlElement(name="student")
private ArrayList<Student> users;
public ArrayList<Student> getUsers() {
return users;
}
public void setUsers(ArrayList<Student> users) {
this.users = users;
}
}
But its giving me errors:
#Test
public void testGetStudents(){
final String str = "http://localhost:8080/RESTfulExample/rest/restwebservice/list";
Client client = ClientBuilder.newClient();
// Client client = ClientBuilder.newBuilder().build(); // This also works, OR
Response response = client.target(str).request().get();
// This will gives us whole XML output
String stringOutput = response.readEntity(String.class);
System.out.println("STATUS : "+response.getStatus());
System.out.println(stringOutput);
Students students = response.readEntity(Students.class);
System.out.println("Size : "+students.getUsers().size());
}
java.lang.IllegalStateException: RESTEASY003765: Response is closed.
at org.jboss.resteasy.specimpl.BuiltResponse.abortIfClosed(BuiltResponse.java:256)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.abortIfClosed(ClientResponse.java:328)
at org.jboss.resteasy.client.jaxrs.internal.ClientResponse.readEntity(ClientResponse.java:152)
at org.jboss.resteasy.specimpl.BuiltResponse.readEntity(BuiltResponse.java:219)
at com.mkyong.rest.test.RestEasySampleTest.testGetStudents(RestEasySampleTest.java:46)
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:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
The Resteasy Client-API has been marked deprecated as JAX-RS standardized a Client-API. You can now use the equivalent javax.ws.rs classes:
javax.ws.rs.client.Client client = javax.ws.rs.client.ClientBuilder.newClient();
javax.ws.rs.client.WebTarget target = client.target("someUrl");
List<Student> students =
target.request().get(new javax.ws.rs.core.GenericType<List<Student>>() {});
Here's an example with query parameters and a check for the HTTP response code, which is handy for failing fast and avoiding stack traces from the JSON mapper, often hiding the real cause:
Response response = null;
try {
response = target.path("apiMethod")
.queryParam("stringParam", "test")
.queryParam("booleanParam", Boolean.FALSE)
.request().accept(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode()) { // HTTP 400
throw new BadRequestException("invalid parameters!");
} else if (response.getStatus() ==
Response.Status.NOT_FOUND.getStatusCode()) { // HTTP 404
throw new NotFoundException("resource was not found on server!");
}
List<MyPojo> result = response.readEntity(new GenericType<List<MyPojo>>(){});
return result;
} finally {
if (response != null) {
response.close();
}
}
I'm trying to get a self-hosted Nancy app running, but I'm having trouble getting it to return valid responses. I'm new at Nancy; I expect my problem is something fairly simple.
Here's some code:
class Program
{
static void Main(string[] args)
{
const String PORT_SETTING = "webServicePortNumber";
const String URI = "http://localhost:{0}/download/";
var portNum = ConfigurationManager.AppSettings[PORT_SETTING];
var uri = new Uri(String.Format(URI, portNum));
var config = new HostConfiguration {
UrlReservations = new UrlReservations { CreateAutomatically = true }
};
using (var nancyHost = new NancyHost(new Bootstrapper(), config, uri)) {
nancyHost.Start();
Console.WriteLine(String.Format("Listening on {0}. Press any key to stop.", uri.AbsoluteUri));
Console.ReadKey();
}
Console.WriteLine("Stopped. Press any key to exit.");
Console.ReadKey();
}
}
internal class Bootstrapper : DefaultNancyBootstrapper
{
protected override Nancy.Diagnostics.DiagnosticsConfiguration DiagnosticsConfiguration
{
get {
return new DiagnosticsConfiguration {
Password = #"[password]"
};
}
}
}
My NancyModule looks like this:
public class DownloadsModule : NancyModule
{
public DownloadsModule() : base("/download")
{
RegisterRoutes();
}
private void RegisterRoutes()
{
Put["/"] = parms => InitiateDownload(parms);
Get["/"] = parms => Summary(parms);
Get["/{id}"] = parms => GetStatus(parms.requestId);
}
private Response GetStatus(Guid requestId)
{
return Response.AsText("TEST: GetStatus requestId " + requestId);
}
private Response Summary(dynamic parms)
{
return Response.AsText("Summary: You loved me before, do you love me now?");
}
private Response InitiateDownload(dynamic parms)
{
return Response.AsText("InitiateDownload.");
}
}
Nancy is running; I can access the diagnostics at http://127.0.0.1:8880/download/_Nancy/. Looking at them, the routes appear ready. Interactive Diagnostics/GetAllRoutes shows:
P U T
name: [nothing] path: /download
G E T
name: [nothing] path: /download
name: [nothing] path: /download/{id}
And yet, I'm getting 404s back when I try http://localhost:8880/download/.
The request trace on the diagnostics page shows:
Method: GET
Request Url:
Scheme: http
Host Name: localhost
Port: 8880
Base Path: /download
Path: /
Query:
Site Base: http://localhost:8880
Is Secure: false
Request Content Type:
Response Content Type: text/html
Request Headers:
<snip>
Accept: text/html;q=1
application/xhtml+xml;q=1
image/webp;q=1
application/xml;q=0.9
*/*;q=0.8
<snip>
Response Headers:
Status Code: 404
Log: New Request Started
[DefaultResponseNegotiator] Processing as real response
So why isn't Nancy routing this request to the proper route?
Problem pointed out to me by jchannon in the Nancy JabbR room:
The URI specifies http://localhost:{0}/download/, while the module also specifies a base path of /download, so currently its looking for an URL of http://localhost:{0}/download/download/
i write a code in apex for setting the chatter photo of a user . i write a function
public PageReference setPhoto() {
Http h = new Http();
HttpRequest req = new HttpRequest();
string firstImageURL = 'https://ap1.salesforce.com/resource/1377118388000/sample_pic';
firstImageURL = firstImageURL.replace(' ', '%20');
req.setEndpoint(firstImageURL);
req.setMethod('GET');
req.setHeader('Content-Type', 'image/jpeg');
req.setCompressed(true);
req.setTimeout(60000);
HttpResponse res = null;
res = h.send(req);
blob image = res.getBodyAsBlob();
ConnectApi.BinaryInput bb = ConnectApi.BinaryInput(image, 'image/png', 'myfile');
System.debug('user is' + ConnectApi.ChatterUsers.setPhoto(null, '00590000001jFln', bb));
return null;
}
when i try to save it it is giving me error
Error: Compile Error: Method does not exist or incorrect signature: ConnectApi.BinaryInput(Blob, String, String) at line 28 column 27
and i am following this http://www.salesforce.com/us/developer/docs/apexcode/Content/connectAPI_inputs.htm#capi_binary_input
can you please guideline whether this documentation is wrong or right ?? and how to get ConnectApi.BinaryInput instance
You'are trying to use the instance method as a static. Create an instance of ConnectApi.BinaryInput
ConnectApi.BinaryInput binaryInput = new ConnectApi.BinaryInput(fileBlob, null, filename);
I am fairly new to EasyMock. I am trying to write a EasyMock test for my Spring WS Endpoint and keep running to a issue. Details are listed below:
Endpoint:
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "UserCreate")<BR>
public void handleUserCreationRequest(#RequestPayload Element userCreate) throws JDOMException {
String userName = userNameExp.valueOf(userCreate);
String loginName = userLoginNameExp.valueOf(userCreate);
String eMail = eMailExp.valueOf(userCreate);
String region = regionExp.valueOf(userCreate);
String department = departmentExp.valueOf(userCreate);
String businessUnit = businessUnitExp.valueOf(userCreate);
userManagementService.userCreate(userName, loginName, eMail,
region, department, businessUnit);
}
Test:
#Before<BR>
public void setUp() throws JDOMException {<BR>
xPath = createNiceMock(XPath.class);<BR>
payload = createNiceMock(Element.class);<BR>
managementService = createStrictMock(UserManagementService.class);<BR>
serviceEndpoint = new UserManagementServiceEndpoint(managementService);
}
#Test
public void testUserCreationHandler() throws JDOMException {
expect(xPath.valueOf(payload)).andReturn("userName");
expect(xPath.valueOf(payload)).andReturn("loginName");
expect(xPath.valueOf(payload)).andReturn("eMail");
expect(xPath.valueOf(payload)).andReturn("region");
expect(xPath.valueOf(payload)).andReturn("department");
expect(xPath.valueOf(payload)).andReturn("businessUnit");
managementService.userCreate("userName", "loginName", "eMail",
"region", "department", "businessUnit");
expectLastCall();
replayAll();
serviceEndpoint.handleUserCreationRequest(payload);
verifyAll();
}
Error Message:
Failed tests:
testUserCreationHandler(com.xxx.usermanagement.endpoint.UserManagementServiceEndpoint
Test):
Expectation failure on verify:
valueOf(EasyMock for class org.jdom.Element): expected: 6, actual: 0
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0<BR><BR>
I would appreciate if anyone can help me on this. Thanks in advance.
The problem you have here is that your XPath mock object is not set to your UserManagementServiceEndpoint object.
You should either modify the constructor to accept an XPath parameter or create a setter for it.