Is there a way to set the CookieDecoder to LAX in MICRONAUT using HttpClient? - httpclient

I'm using Micronaut 2.5.3
When I receive a header like Set-Cookie: cookie_name=cookie value; expires=Mon, 17-May-2021 09:32:59 GMT; path=/; secure; HttpOnly; samesite=none in the response with whitespaces inside the value, the console shows a warning and ends up with a NullPointerException from NettyCookies since it decodes in STRICT mode and fails.
WARN io.netty.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
java.lang.NullPointerException: null
at io.micronaut.http.netty.cookies.NettyCookies.<init>(NettyCookies.java:78)
at io.micronaut.http.client.netty.FullNettyClientHttpResponse.<init>(FullNettyClientHttpResponse.java:99)
at io.micronaut.http.client.netty.DefaultHttpClient$12.channelReadInstrumented(DefaultHttpClient.java:2204)
And finally shows ReadTimeoutException
io.micronaut.http.client.exceptions.ReadTimeoutException: Read Timeout
at io.micronaut.http.client.exceptions.ReadTimeoutException.<clinit>(ReadTimeoutException.java:26)
at io.micronaut.http.client.netty.DefaultHttpClient.lambda$null$36(DefaultHttpClient.java:1178)
at io.reactivex.internal.operators.flowable.FlowableOnErrorNext$OnErrorNextSubscriber.onError(FlowableOnErrorNext.java:103)
at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onError(RxInstrumentedSubscriber.java:66)
at io.reactivex.internal.operators.flowable.FlowableTimeoutTimed$TimeoutSubscriber.onTimeout(FlowableTimeoutTimed.java:139)
at io.reactivex.internal.operators.flowable.FlowableTimeoutTimed$TimeoutTask.run(FlowableTimeoutTimed.java:170)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
If we inspect the NettyCookies code, the STRICT Decoder is used, which returns a null Cookie in io.netty.handler.codec.http.cookie.Cookie nettyCookie = ClientCookieDecoder.STRICT.decode(value);. When this.cookies.put(nettyCookie.name(), new NettyCookie(nettyCookie)); runs, NullPointerException is thrown because nettyCookie is null
public NettyCookies(HttpHeaders nettyHeaders, ConversionService conversionService) {
this.conversionService = conversionService;
if (nettyHeaders != null) {
List<String> values = nettyHeaders.getAll(HttpHeaderNames.SET_COOKIE);
if (values != null && !values.isEmpty()) {
this.cookies = new LinkedHashMap();
Iterator var4 = values.iterator();
while(var4.hasNext()) {
String value = (String)var4.next();
io.netty.handler.codec.http.cookie.Cookie nettyCookie = ClientCookieDecoder.STRICT.decode(value);
this.cookies.put(nettyCookie.name(), new NettyCookie(nettyCookie));
}
} else {
this.cookies = Collections.emptyMap();
}
} else {
this.cookies = Collections.emptyMap();
}
}
If I could use the LAX decoder this would not happen

The decoding method cannot be changed as it is a security vulnerability if it was LAX. The issue with the NPE has been fixed for Micronaut 2.5.4

Related

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

milo:Bad_SessionIdInvalid, The session id is not valid

I am getting a "The session id is not valid." exception when reading the value of a node ,but just sometimes,I konw the session is not timeout,so why?
the exception :
java.util.concurrent.ExecutionException: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:395)
at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1999)
at com.ggnykj.smartems.cloud.server.autocontrol.client.OpcClientServer.readNode(OpcClientServer.java:230)
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:115)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: UaServiceFaultException: status=Bad_SessionIdInvalid, message=The session id is not valid.
at org.eclipse.milo.opcua.stack.client.UaTcpStackClient.lambda$receiveResponse$16(UaTcpStackClient.java:367)
at org.eclipse.milo.opcua.stack.core.util.ExecutionQueue$PollAndExecute.run(ExecutionQueue.java:107)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
... 3 more
Exception in thread "pool-2-thread-2" java.lang.NullPointerException
at com.ggnykj.smartems.cloud.server.autocontrol.controller.OpcClientServerController.readNode(OpcClientServerController.java:116)
at com.ggnykj.smartems.cloud.server.autocontrol.server.SaveExOpcData.run(SaveExOpcData.java:59)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
there is my code:
MyX509IdentityProvider x509IdentityProvider = new MyX509IdentityProvider(clientOption.opcServer.getCertFilePath(),
clientOption.opcServer.getPrivateKeyPath());
X509Certificate cert = x509IdentityProvider.getCertificate();
KeyPair keyPair = new KeyPair(cert.getPublicKey(), x509IdentityProvider.getPrivateKey());
OpcUaClientConfig config = OpcUaClientConfig.builder()
.setApplicationName(LocalizedText.english(clientOption.opcServer.getOpcServerName()))
//.setApplicationUri("urn:eclipse:milo:examples:client")
.setApplicationUri("")
//.setCertificate(loader.getClientCertificate())
//.setKeyPair(loader.getClientKeyPair())
.setCertificate(cert)
.setKeyPair(keyPair)
.setEndpoint(endpoint)
.setIdentityProvider(clientOption.getIdentityProvider())
.setChannelLifetime(uint(600000000))
.setSessionTimeout(uint(600000000))
//.setRequestTimeout(uint(5000))
.build();
return new OpcUaClient(config);
there is the connect and read code:
private OpcUaClient getOpcClient(OpcServer opcServer){
OpcUaClient client = null;
if(null!=opcClientMap.get(opcServer.getOpcServerId())){
client = opcClientMap.get(opcServer.getOpcServerId());
}else{
try {
ClientOption clientOption = new ClientOption(opcServer);
client = new ClientOptionRunner(clientOption).createClient();
}catch (Throwable t){
logger.error("Error getting client: {}", t.getMessage(), t);
}
opcClientMap.put(opcServer.getOpcServerId(),client);
}
return client;
}
public DataValue readNode(OpcServer opcServer,NodeId nodeId){
OpcUaClient client = getOpcClient(opcServer);
DataValue value = null;
try {
client.connect().get();
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
}catch (Exception e){
e.printStackTrace();
}
return value;
}
when I read the node,there is the problem:
value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
but I don't know why
This StatusCode comes from the server.
Maybe you can capture this behavior on Wireshark to ensure you're really using the same OpcUaClient instance you think you are and not one that has had its session timeout somehow. Or maybe the capture will show the server is at fault and returning this StatusCode when you read on a freshly created Session.

Play-Framework: 2.3.x: play - Cannot invoke the action, eventually got an error: java.lang.IllegalArgumentException:

I am using play-framework 2.3.x with reactivemongo-extension JSON type. following is my code for fetch the data from db as below:
def getStoredAccessToken(authInfo: AuthInfo[User]) = {
println(">>>>>>>>>>>>>>>>>>>>>>: BEFORE"); //$doc("clientId" $eq authInfo.user.email, "userId" $eq authInfo.user._id.get)
var future = accessTokenService.findRandom(Json.obj("clientId" -> authInfo.user.email, "userId" -> authInfo.user._id.get));
println(">>>>>>>>>>>>>>>>>>>>>>: AFTER: "+future);
future.map { option => {
println("*************************** ")
println("***************************: "+option.isEmpty)
if (!option.isEmpty){
var accessToken = option.get;println(">>>>>>>>>>>>>>>>>>>>>>: BEFORE VALUE");
var value = Crypto.validateToken(accessToken.createdAt.value)
println(">>>>>>>>>>>>>>>>>>>>>>: "+value);
Some(scalaoauth2.provider.AccessToken(accessToken.accessToken, accessToken.refreshToken, authInfo.scope,
Some(value), new Date(accessToken.createdAt.value)))
}else{
Option.empty
}
}}
}
When i using BSONDao and BsonDocument for fetching the data, this code successfully run, but after converting to JSONDao i getting the following error:
Note: Some time this code will run but some it thrown an exception after converting to JSON
play - Cannot invoke the action, eventually got an error: java.lang.IllegalArgumentException: bound must be positive
application -
Following are the logs of application full exception strack trace as below:
>>>>>>>>>>>>>>>>>>>>>>: BEFORE
>>>>>>>>>>>>>>>>>>>>>>: AFTER: scala.concurrent.impl.Promise$DefaultPromise#7f4703e3
play - Cannot invoke the action, eventually got an error: java.lang.IllegalArgumentException: bound must be positive
application -
! #6m1520jff - Internal server error, for (POST) [/oauth2/token] ->
play.api.Application$$anon$1: Execution exception[[IllegalArgumentException: bound must be positive]]
at play.api.Application$class.handleError(Application.scala:296) ~[play_2.11-2.3.8.jar:2.3.8]
at play.api.DefaultApplication.handleError(Application.scala:402) [play_2.11-2.3.8.jar:2.3.8]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.8.jar:2.3.8]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [play_2.11-2.3.8.jar:2.3.8]
at scala.Option.map(Option.scala:146) [scala-library-2.11.6.jar:na]
Caused by: java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388) ~[na:1.8.0_40]
at scala.util.Random.nextInt(Random.scala:66) ~[scala-library-2.11.6.jar:na]
The problem is solve, but i am not sure, why this produce, I think there is problem with reactivemongo-extension JSONDao library. because when i use findOne instead of findRandom the code is run successfully, but the findRandom is run good on BSON dao. Still not found what the exact problem is that, but following is the resolved code.
def getStoredAccessToken(authInfo: AuthInfo[User]) = {
println(authInfo.user.email+" ---- "+authInfo.user._id.get)
var future = accessTokenService.findOne($doc("clientId" $eq authInfo.user.email, "userId" $eq authInfo.user._id.get)); //user findOne instead of findRandom in JsonDao
future.map { option => {
if (!option.isEmpty){
var accessToken = option.get;
var value = Crypto.validateToken(accessToken.createdAt.value)
Some(scalaoauth2.provider.AccessToken(accessToken.accessToken, accessToken.refreshToken, authInfo.scope,
Some(value), new Date(accessToken.createdAt.value)))
}else{
Option.empty
}
}}
}

Why do I get an MSPL exception "ProxyRequest only valid for sipRequest"

I'm writing a Lync MSPL application using a manifest and a windows service. In my manifest.am I have the following code:
<?xml version="1.0"?>
<r:applicationManifest
r:appUri="http://www.company.no/LyncServerFilter"
xmlns:r="http://schemas.microsoft.com/lcs/2006/05">
<r:requestFilter methodNames="ALL"
strictRoute="true"
domainSupported="false"/>
<r:responseFilter reasonCodes="ALL"/>
<r:proxyByDefault action="true" />
<r:allowRegistrationBeforeUserServices action="true" />
<r:splScript>
<![CDATA[
callId = GetHeaderValues("Call-ID");
cseq = GetHeaderValues("CSeq");
content = "";
sstate = GetHeaderValues("subscription-state");
xevent = GetHeaderValues("Event");
xdir = GetHeaderValues("Direction");
xexp = GetHeaderValues("Session-Expires");
referto = GetHeaderValues("Refer-To");
if (sipRequest)
{
if (sipRequest.Method == "INVITE") {
if (ContainsString(sipRequest.Content, "m=audio", true)) {
content = "audio";
}
else if (ContainsString(sipRequest.Content, "m=video", true)) {
content = "video";
}
else if (ContainsString(sipRequest.Content, "m=message", true)) {
content = "message";
}
else if (ContainsString(sipRequest.Content, "m=application", true)) {
content = "application";
}
else {
content = "unknown";
}
}
else if (sipRequest.Method == "NOTIFY" || sipRequest.Method == "BENOTIFY") {
content = sipRequest.Content;
}
DispatchNotification("OnRequest", sipRequest.Method, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
if (sipRequest) {
ProxyRequest();
}
}
else if(sipResponse) {
DispatchNotification("OnResponse", sipResponse.StatusCode, sipResponse.StatusReasonPhrase, sipMessage.From, sipMessage.To, callId, cseq, content, xdir, xevent, sstate, xexp, referto);
ProxyResponse();
}
]]></r:splScript>
</r:applicationManifest>
I'm getting the following errormessage in Eventlog on Lync Front End server:
Lync Server application MSPL script execution aborted because of an error
Application Uri at 'http://www.company.no/LyncServerFilter', at line 60
Error: 0x80070057 - The parameter is incorrect
Additional information: ProxyRequest only valid for sipRequest
Line 60 is where I call ProxyRequest:
if (sipRequest) {
ProxyRequest();
}
Questions:
Why does the errormessage say that ProxyRequest is only valid for a sipRequest? I'm checking that it is a sipMessage right?
Can I remove my call to ProxyRequest() since I have set proxyByDefault=true? Does the DistpathNotification-method "handle" the method (swallow it), or will the message be proxied by default? The code "works" when I remove the call to ProxyRequest(), but I'm not sure what the consequences are...
The ProxyRequest method takes a argument of the uri, which is why you are getting the compile error message.
So you should be calling it like:
ProxyRequest(""); // send to the URI specified in the request itself
Removing it effectivity does the same thing as per your proxyByDefault setting being set to true:
If true, the server automatically proxies any messages that are not handled by the application. If false, the message is dropped and applications that follow this application in the application execution order will not receive it. The default value is true.
As a side-note, you can use compilespl.exe, which comes as part of the Lync Server SDK to verify that your MSPL script is correct before trying to start it on the lync server.
Check out this link in the 'Compile the MSPL application separately' section.

SEVERE: SAAJ0120: Can't add a header when one is already present

I'm trying to deploy my jsp site on Oracle web server, but when I call my web service using a port I get the following error :
SEVERE: SAAJ0120: Can't add a header when one is already present
This is the code for my HeaderHandler
public boolean handleMessage(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
SOAPMessage message = smc.getMessage();
SOAPEnvelope envelope = null;
SOAPHeader header = null;
try {
envelope = smc.getMessage().getSOAPPart().getEnvelope();
header = envelope.addHeader();
SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
//http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd
SOAPElement BinarySecurityToken =
security.addChildElement("BinarySecurityToken", "wsse");
BinarySecurityToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
//EncodingType="SSHA" ValueType="AccessManagerSSOSecurityToken" wsu:Id="OAMToken"
BinarySecurityToken.addAttribute(new QName("EncodingType"), "SSHA");
BinarySecurityToken.addAttribute(new QName("ValueType"), "AccessManagerSSOSecurityToken");
BinarySecurityToken.addAttribute(new QName("wsu:Id"), "OAMToken");
BinarySecurityToken.addTextNode(token);
//message.writeTo(System.out);
//System.out.println("");
} catch (Exception e) {
try {
header = envelope.addHeader();
} catch (SOAPException e1) {
e1.printStackTrace();
}
//e.printStackTrace();
}
} else {
try {
//This handler does nothing with the response from the Web Service so
//we just print out the SOAP message.
SOAPMessage message = smc.getMessage();
//message.writeTo(System.out);
//System.out.println("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
return outboundProperty;
}
EDIT:
The error is
com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl addHeader
SEVERE: SAAJ0120: Can't add a header when one is already present
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present.
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:114)
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:94)
at com.standardandpoors.wso.HeaderHandler.handleMessage(HeaderHandler.java:33)
at com.standardandpoors.wso.HeaderHandler.handleMessage(HeaderHandler.java:1)
at com.sun.xml.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:297)
at com.sun.xml.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:138)
at com.sun.xml.ws.handler.ClientSOAPHandlerTube.callHandlersOnRequest(ClientSOAPHandlerTube.java:144)
at com.sun.xml.ws.handler.HandlerTube.processRequest(HandlerTube.java:115)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:892)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:841)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:804)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:706)
at com.sun.xml.ws.client.Stub.process(Stub.java:385)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:189)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:102)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:172)
at $Proxy125.findUserById(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at weblogic.wsee.jaxws.spi.ClientInstanceInvocationHandler.invoke(ClientInstanceInvocationHandler.java:84)
at $Proxy120.findUserById(Unknown Source)
at com.standardandpoors.wso.IdmWSUtil.findUserById(IdmWSUtil.java:44)
at com.standardandpoors.idm.controller.JspRedirectionController.forgotPassword(JspRedirectionController.java:123)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:774)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:216)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:132)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:338)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:221)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3284)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2089)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1513)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
EDIT:
The issue is present using JDK 1.8, not in 1.7
You can replace the header by detaching the old one first.
if (envelope.getHeader() != null) {
envelope.getHeader().detachNode();
}
SOAPHeader header = envelope.addHeader();
http://docs.oracle.com/javaee/5/api/javax/xml/soap/SOAPEnvelope.html
I was finally able to resolve the issue. I just added an if condition to check whether the header was NULL or not, if it was NULL only then I added the header else continued with the program.
This worked for me !
if(header == null){
header = envelope.addHeader();
}
Wouldn't it be easier to just use?
SOAPHeader header = envelope.getHeader();
SOAPHeader header = envelope.getHeader();
if (header == null) {
header = add.addHeader();
}
header.addChildElement(wsSecurityElement);
Is my personal choice: detaching the previous SOAPHeader can break the code, for instance in case of handlers chaining, where other upstream handlers might add their elements to the header.
null testing makes the code backward compatible with previous JREs; otherwise switching from addHeader to getHeader is enough.