How to modify redirector to direct somewhere we need in WSO2 Stratos

 

Here we will discuss how to modify AllPagesFilter.java file to redirect requests.Check the comments shown in the below code.That will show you how to modify this file to add new redirector.

package org.wso2.stratos.redirector.servlet.ui.filters;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.stratos.common.constants.StratosConstants;
import org.wso2.stratos.redirector.servlet.ui.clients.RedirectorServletServiceClient;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class AllPagesFilter implements Filter {
    private static final Log log = LogFactory.getLog(AllPagesFilter.class);
    private static Map<String, Boolean> tenantExistMap = new HashMap<String, Boolean>();
    ServletContext context;
    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
    }

    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse, FilterChain filterChain) throws
            IOException, ServletException {
        if (!(servletRequest instanceof HttpServletRequest)) {
            // no filtering
            return;
        }

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String requestedURI = request.getRequestURI();

        StringTokenizer tokenizer = new StringTokenizer(requestedURI.substring(1), "/");
        String[] firstUriTokens = new String[2];
        int i = 0;
        while (tokenizer.hasMoreElements()) {
            firstUriTokens[i] = tokenizer.nextToken();
            i ++;
            if ( i > 1) {
                break;
            }
        }
        if (i > 1 && firstUriTokens[0].equals("t")) {
            if (requestedURI.startsWith("//")) {
                requestedURI = requestedURI.replaceFirst("//", "/");
            }
            String path = requestedURI.substring(firstUriTokens[0].length() +
                                                 firstUriTokens[1].length() + 2);

            // need to validate the tenant exists
            String tenantDomain = firstUriTokens[1];
            boolean tenantExists = true;
            boolean tenantInactive = false;
            if (tenantExistMap.get(tenantDomain) == null) {
                // we have to call the service :(
                RedirectorServletServiceClient client;
                try {
                    client =
                            new RedirectorServletServiceClient(context, request.getSession());
                } catch (Exception e) {
                    String msg = "Error in constructing RedirectorServletServiceClient.";
                    log.error(msg, e);
                    throw new ServletException(msg, e);
                }

                try {
                    String status = client.validateTenant(tenantDomain);
                    tenantExists = StratosConstants.ACTIVE_TENANT.equals(status);
                    if (!tenantExists &&
                            StratosConstants.INACTIVE_TENANT.equals(status)) {
                        tenantExists = true;
                        tenantInactive = true;
                    }
                } catch (Exception e) {
                    String msg = "Error in checking the existing of the tenant domain: " +
                            tenantDomain + ".";
                    log.error(msg, e);
                    throw new ServletException(msg, e);
                }
                // we have some backup stuff, if the tenant doesn't exists
                if (tenantExists) {
                    // we put this to hash only if the original tenant domain exist
                    tenantExistMap.put(tenantDomain, true);
                }
            }
            if (tenantInactive) {
                String contextPath = request.getContextPath();
                if (contextPath == null || contextPath.equals("/")) {
                    contextPath = "";
                }
                String errorPage = contextPath +
                        "/carbon/admin/error.jsp?The Requested tenant domain: " +
                        tenantDomain + " is inactive.";
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(errorPage);
                requestDispatcher.forward(request, servletResponse);
            } else if (tenantExists) {
                request.setAttribute(MultitenantConstants.TENANT_DOMAIN, tenantDomain);
//===========================================================
//Here wi will identify wether request contains docs/about.html
//Normally this will redirect to carbon about page if we didnt add this code. if we need to  redirect it somewhere else in
//Stratos we can do it here
                if(path.indexOf("docs/about.html")>=0)
                {
//checking and replacing doing here.So we can create "about_stratos.html" file inside
//stratos/services/manager/modules/styles/src/main/resources/web/docs folder. So once we requested docs/about.html
//it will redirect to about_stratos.html located in styles/src/main/resources/web/docs

                    path=path.replace("/docs/about.html","/docs/about_stratos.html");                   
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                    System.out.println("url is"+path);
                }
//=========================================================
                if (path.indexOf("admin/login.jsp") >= 0) {
                    // we are going to apply the login.jsp filter + tenant specif filter both in here
                    path = path.replaceAll("admin/login.jsp",
                            "tenant-login/login_ajaxprocessor.jsp");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if (path.indexOf("/admin/index.jsp") >= 0) {
                    // we are going to apply the login.jsp filter + tenant specif filter both in here
                    path = path.replaceAll("/admin/index.jsp", "/tenant-dashboard/index.jsp");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if (path.indexOf("admin/docs/userguide.html") >= 0) {
                    // we are going to apply the dasbhoard docs.jsp filter +
                    // tenant specif filter both in here
                   path = path.replaceAll("admin/docs/userguide.html","tenant-dashboard/docs/userguide.html");
                    request.setAttribute(StratosConstants.TENANT_SPECIFIC_URL_RESOLVED, "1");
                }
                if ("".equals(path) || "/".equals(path) ||  "/carbon".equals(path) ||
                        "/carbon/".equals(path) || "/carbon/admin".equals(path) ||
                        "/carbon/admin/".equals(path)) {
                    // we have to redirect the root to the login page directly
                    path = "/t/" + tenantDomain + "/carbon/admin/login.jsp";
                    ((HttpServletResponse)servletResponse).sendRedirect(path);
                    return;
                }
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(path);
                requestDispatcher.forward(request, servletResponse);
            } else {
                String contextPath = request.getContextPath();
                if (contextPath == null || contextPath.equals("/")) {
                    contextPath = "";
                }
                String errorPage = contextPath +
                        "/carbon/admin/error.jsp?The Requested tenant domain: " +
                        tenantDomain + " doesn't exist.";
                RequestDispatcher requestDispatcher =
                        request.getRequestDispatcher(errorPage);
                requestDispatcher.forward(request, servletResponse);
            }
        }
    }
    public void destroy() {
        // nothing to destroy
    }
}

No comments:

Post a Comment

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...