Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

how to get sling servlet response-AEMasCS

Avatar

Level 5

Hi Team,

         I was trying to redirect error response to 500.html,when we gave incorrect url as below.

author url : http://localhost:4502/graphql/execute.json/consumer-bau/bau-popup;fragmentpath=/content/dam/cfm-ecom...

 

please find the json error response.

{
"errors": [
{
"message": "Exception while fetching data (/bauPopupMainSecByPath) : Path: '/content1/dam/cfm-cere/bau-consumer/elife/additional-benefits/popup/benefits-main-sec' did not yield a Content Fragment",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"bauPopupMainSecByPath"
],
"extensions": {
"classification": "DataFetchingException"
}
}
],
"data": null
}

 

Please find the Java code here

rajat168_0-1711102922214.png

Kindly please help how to redirect by getting error response and redirect to 500.html 

Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Level 5

Hi All, This issue has been solved by getting 

slingRequest.getRequestPathInfo().getSuffix() and validated the resource path valid or not.

View solution in original post

10 Replies

Avatar

Community Advisor

HI @rajat168 ,

First you can write a condition in your Java code where you need to check the error status. Then please use below code

      try {
            response.setStatus(404);
            response.sendRedirect("error-page-path");
        } catch (Exception e) {
            logger.error("Error in forwarding request to error page", e);
        }

 

 

Thanks
Tarun

Avatar

Level 5

Hi @TarunKumar , thanks for your response!!.

my clarification was, how to get the error json response from SlingHttpServletResponse servlet, though the graphql response set code were 200 even if was incorrect url. 

Thanks.

Avatar

Level 3

hi @rajat168 

 http://localhost:4502/graphql/execute.json - Is this your graphql custom endpoint. if so could you try to use @component(service = { Filter.class },immediate = true, property = {
"osgi.http.whiteboard.filter.pattern=/graphql/execute.json *" ) to interrupt the request and do a redirect to 500 page if requested resource is not found

Avatar

Level 5

Hi @sateaswa94 ,

 thanks for youre response, as suggested, i modified the code as suggested but the class file itself not got called. :(.

Please find the modified code. appreciate your help!!!

rajat168_0-1711110431162.png

Please find the log details, when we gave incorrect url on the browser.

rajat168_0-1711112078132.png

rajat168_1-1711112139723.png

 

Avatar

Level 3


Hi @rajat168 
Working example
I am redirecting to we retail page if request body is empty. Note we have to overide request wrapper in order to read request body from filter

 

sateaswa94_0-1711124496534.png

sateaswa94_1-1711124571116.png

If body is empty

sateaswa94_2-1711124660482.pngsateaswa94_3-1711124684960.png

sateaswa94_0-1711124812157.png

 

 

 

 

package com.jsonapi.servlets;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.engine.EngineConstants;
import org.codehaus.jettison.json.JSONObject;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;


@Component(service = Filter.class,
        property = {
                EngineConstants.SLING_FILTER_SCOPE + "=" + EngineConstants.FILTER_SCOPE_COMPONENT,
                EngineConstants.SLING_FILTER_RESOURCETYPES+"=graphql/sites/components/endpoint",
        })
public class TestServletFilter implements Filter{
    private static final Logger LOGGER = LoggerFactory.getLogger(TestServletFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest = new RequestWrapper((HttpServletRequest) servletRequest);

        final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) servletResponse;

        String payload = IOUtils.toString(servletRequest.getInputStream(), StandardCharsets.UTF_8);
        LOGGER.info("Servlet called {}" , payload);
        try {
            JSONObject jsonObject = new JSONObject(payload);
            String query = jsonObject.getString("query");
            if(StringUtils.isBlank(query)) {
                slingResponse.reset();
                slingResponse.sendRedirect("http:///localhost:4502/content/we-retail/us.html");
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {

    }
    private static class ResettableStreamHttpServletRequest extends
            HttpServletRequestWrapper {

        private byte[] rawData;
        private HttpServletRequest request;
        private ResettableServletInputStream servletStream;

        public ResettableStreamHttpServletRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
            this.servletStream = new ResettableServletInputStream();
        }


        public void resetInputStream() {
            servletStream.stream = new ByteArrayInputStream(rawData);
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            if (rawData == null) {
                rawData = IOUtils.toByteArray(this.request.getReader());
                servletStream.stream = new ByteArrayInputStream(rawData);
            }
            return servletStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            if (rawData == null) {
                rawData = IOUtils.toByteArray(this.request.getReader());
                servletStream.stream = new ByteArrayInputStream(rawData);
            }
            return new BufferedReader(new InputStreamReader(servletStream));
        }


        private class ResettableServletInputStream extends ServletInputStream {

            private InputStream stream;

            @Override
            public int read() throws IOException {
                return stream.read();
            }
        }
    }
}

 

  

Avatar

Level 5

Hi @sateaswa94 , 

  thanks for your response, i tried from my side, but doesn't work, my requirement was different from your code. as i mentioned above my url, doesnt have body. 

Avatar

Community Advisor

Hi @rajat168 , Please refer this document for more details about the filter chains.
https://medium.com/@toimrank/aem-filter-6f03174c3f2b

I hope this will help!!

Avatar

Level 5

Hi @sravs ,

 thanks for your response, i was able to make simple call using filter, i was expecting how to call com.adobe.aem.graphql.impl.servlet.PersistedQueryServlet and get its response from filter implementation when it throws 500 error?

Avatar

Correct answer by
Level 5

Hi All, This issue has been solved by getting 

slingRequest.getRequestPathInfo().getSuffix() and validated the resource path valid or not.

Avatar

Administrator

@rajat168 Did you find the suggestions from users helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni