I need to match request along with its corresponding response so i am trying to take session id for matching each request along with its response.
I am using Phase.PRE_STREAM in my constructor.
I am trying to take HttpServletRequest and session id as below in my interceptor
public void handleMessage(Message msg) {
HttpServletRequest req = (HttpServletRequest)msg.get("HTTP.REQUEST");
}
But i am getting null value. Could someone tell me how to take HttpServletRequest in apache cxf?
Do i need to set session id while creating client.I create my client as below
JAXRSClientFactoryBean sf = new JAXRSClientFactoryBean();
sf.setResourceClass(CustomerService.class);
sf.setAddress("http://localhost:9000/");
BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = new JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
CustomerService service = sf.create(CustomerService.class);
WebClient wc = sf.createWebClient();
Implement SOAP Handler like so:
public class SOAPRequestHandler implements SOAPHandler<SOAPMessageContext>
And implement your handlers like so:
public boolean handleMessage(SOAPMessageContext msgContext)
{
HttpServletRequest request = (HttpServletRequest) msgContext.get("HTTP.REQUEST");
...
}
Related
How do I get the header and body of the current request from an application which called my Springboot application? I need to extract this information. Unfortunately this does not work. I tried to get the current request with this code sample (https://stackoverflow.com/a/26323545/5762515):
public static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request;
}
throw new IllegalArgumentException("Request must not be null!");
}
And then I tried to get the body
ContentCachingRequestWrapper requestWrapper = (ContentCachingRequestWrapper) currentRequest;
String requestBody = new String(requestWrapper.getContentAsByteArray());
Can someone tell me what im doing wrong?
Thanks in advance
#RestController
public class SampleController {
#PostMapping("/RestEndpoint")
public ResponseEntity<?> sampleEndpoint(#RequestHeader Map<String, String> headers,#RequestBody Map<String,String> body) {
//Do something with header / body
return null;
}
}
If the application's are communicating through a rest endpoint I believe this would be the simplest solution. In spring you can add RequestHeader and RequestBody annotations to method arguments to have them setup to be used.
Of course you can map RequestBody directly to some POJO instead of using a map but just as an example.
Let me know if this is what you were looking for !
#TryHard, You're using spring boot then following way is more preferable for you,
#RestController
public class SampleController {
#RequestMapping("/get-header-data")
public ResponseEntity<?> sampleEndpoint(HttpServletRequest request) {
// request object comes with various in-built methods use as per your requirement.
request.getHeader("<key>");
}
}
you can get header with your code but need apply some changes.
private String getRequest() throws Exception {
RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
if (attribs != null) {
HttpServletRequest request = ((ServletRequestAttributes) attribs).getRequest();
return request ;
}
throw new IllegalArgumentException("Request must not be null!");
}
after you can extract header info from request. For example if you want get Accept-Encoding
String headerEncoding = getRequest().getHeader("Accept-Encoding");
obliviusly you don't use this approce if not necessary.
If you want exract the body NOT use this solution
I'm working on a POC i need to use zuul as a sever to route 2 routes first will run normally but it has a custom post filter which will send another request to other api using some data of the response of the first requet,
so need to extract the response body of the first request into my custom post filter and get some specific attributes but i can not find the response as it always be null but the status code is 200.
how can i wait and get a value of specific attribute from the response and get the actual status code not just 200 as default value.
i tried to make this implementation using cloud gateway but i reached the same point of disability of extracting the response.
also i tried to make a response decorator but it failed too.
#Component
public class AddResponseHeaderFilter extends ZuulFilter {
#Override
public String filterType() {
return "post";
}
#Override
public int filterOrder() {
return 1;
}
#Override
public boolean shouldFilter() {
return true;
}
#Override
public Object run() {
System.out.println("this is my filter");
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = new HttpServletRequestWrapper(context.getRequest());
System.out.println(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
HttpServletResponse servletResponse = context.getResponse();
// return an address only
System.out.println(context.getResponseBody().toString());
servletResponse.addHeader("X-Foo", UUID.randomUUID().toString());
return null;
}
}
RequestContext.getCurrentContext().getResponseDataStream() works fine for me, I am also able to manipulate the response.
import java.nio.charset.Charset;
import org.springframework.util.StreamUtils;
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String requestLog = StreamUtils.copyToString(request.getInputStream(),
Charset.forName("UTF-8"));
I have an interceptor that implements PreProcessInterceptor.
I need to get the HttpSession object in the preProcess method, so I'm using:
#Context
private HttpServletRequest httpRequest;
and then:
httpRequest.getSession();
to get the HttpSession object.
At first I thought everything was working fine, but then I realized that the httpRequest.getSession() was returning a new HttpSession object on every request.
I need to set some session attributes on the user first request and then use those attributes on futher requests. The attributes are being set all right, I can even access those attributes down along that same request stack. However, as I am getting a new Session on every new request, I am not able to access those attributes.
Do I need to send something from the client side do my REST services, like a token or something?
Here is a more complete view of my Interceptor
#Provider
#ServerInterceptor
#SecurityPrecedence
public class SecurityInterceptor implements PreProcessInterceptor, AcceptedByMethod {
...
#Context
private HttpServletRequest httpRequest;
#Override
public boolean accept(Class classe, Method metodo) {
return metodo.getAnnotation(PermitAll.class) == null;
}
...
#Override
public ServerResponse preProcess(HttpRequest request, ResourceMethod resourceMethod) {
HttpSession httpSession = httpRequest.getSession();
// Set attributes on httpSession
...
return null;
}
}
Session is tried to the concept of HTTP Cookies.
The processing of the First HTTP request would have detected that there is no current Session and created a new one. The Session ID would've then been populated as a Cookie (Http Response Header) whenever the Response was returned to the Client.
If your Second HTTP Request had a Request Header for that same Cookie, then httpSession wouldn't be created new.
So, whenever you are sending requests to the Server, check if there exists a Cookie in the Server and send that cookie with each request.
I need to apply an Authorization header in a request interceptor, but I need to sign the request method, URI, and date.
Inside the request interceptor I get a RequestInterceptor.RequestFacade, which only has "setter methods"
Is there any way I can get request properties inside a request interceptor?
Ah, did some more googling. The way to do this is to use a client wrapper. Observe...
public class SigningClient implements Client {
final Client wrapped;
public SigningClient(Client client) {
wrapped = client;
}
#Override public Response execute(Request request) {
Request newRequest = sign(request);
return wrapped.execute(newRequest);
}
private void sign(Request request) {
// magic
}
}
Found it here: https://github.com/square/retrofit/issues/185#issuecomment-17819547
I am using Jaxb 2 with a Spring WS, and I have an interceptor which is directed to a particular payload and it works fine.
Here my requirement is to read the request parameters from the handleRequest method of my interceptor. I know this should be fairly straight forward. However could not figure out a way to read the request parameters. At the moment my handleRequest method looks as below.
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint)
throws Exception {
boolean proceed = true;
SaajSoapMessage saajSoapMessage =
(SaajSoapMessage) messageContext.getRequest();
SOAPMessage soapMessage = saajSoapMessage.getSaajMessage();
Document doc = saajSoapMessage.getDocument();
Element element = doc.getElementById("request");
}
The relevant part of the my Endpoint class is
#PayloadRoot(namespace = NAMESPACE, localPart = "confirOrderRequest")
public #ResponsePayload ConfirmOrderResponse handleConfirmOrder(
#RequestPayload ConfirmOrderRequest confirmOrderRequest) {
...........
}
Here my requirement is to get the orderId which comes with the ConfirmOrderRequest in the interceptor handleRequest method, is there a way to do this directly, or do I need to do some XML parsing for that?
#VitualTroll, It helped me somewhat, thanks !
But answer on that question is incorrect(at least in my case). Body of my new handleRequest() method would looks as follows. Hope this would save some time for someone else in future. Here jaxb2Marshaller is my spring bean.
#Autowired
private Jaxb2Marshaller jaxb2Marshaller;
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
boolean proceed = true;
SaajSoapMessage saajSoapMessage = (SaajSoapMessage) messageContext.getRequest();
SoapBody requestBody = saajSoapMessage.getSoapBody();
Object obj = jaxb2Marshaller.unmarshal(requestBody.getPayloadSource());
if (obj instanceof ConfirmOrderRequest ) {
ConfirmOrderRequest cor = (ConfirmOrderRequest ) obj;
String orderId = cor.getOrderId();
...........
.......
}
.....
}