Example usage for javax.servlet.http HttpServletRequest getRemoteUser

List of usage examples for javax.servlet.http HttpServletRequest getRemoteUser

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteUser.

Prototype

public String getRemoteUser();

Source Link

Document

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

Usage

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void testHttpContextSetUser() throws ServletException, NamespaceException, IOException {
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();

    HttpContext testContext = new HttpContext() {

        @Override//from ww  w. ja  v a2  s  . co m
        public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            request.setAttribute(HttpContext.REMOTE_USER, "TEST");
            request.setAttribute(HttpContext.AUTHENTICATION_TYPE, "Basic");
            return true;
        }

        @Override
        public URL getResource(String name) {
            return null;
        }

        @Override
        public String getMimeType(String name) {
            return null;
        }
    };
    HttpServlet testServlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            resp.setContentType("text/html");
            PrintWriter out = resp.getWriter();
            out.print("USER: " + req.getRemoteUser() + " AUTH_TYPE: " + req.getAuthType());
        }

    };
    extendedHttpService.registerServlet("/" + getName(), testServlet, null, testContext);

    String expected = "USER: TEST AUTH_TYPE: Basic";
    String actual = requestAdvisor.request(getName());
    Assert.assertEquals(expected, actual);
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;// w  w  w  .j a  v a 2s  . c  o m
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:de.jwi.jfm.servlets.Controller.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String self = null;//w  w w  . j a v  a 2s  .  c o  m
    String contextPath = null;
    String pathInfo = null;
    Folder folder = null;
    String queryString = null;

    try {
        contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String method = request.getMethod();
        boolean formPosted = "POST".equals(method);

        pathInfo = request.getPathInfo();

        if (null == pathInfo) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + servletPath + " is alive.");

            return;
        }

        File f = new File(filebase, pathInfo);

        if (!f.exists()) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + pathInfo + " does not exist.");

            return;
        }

        if (f.isFile()) {
            doDownload(request, response, f);
            return;
        }

        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(request.getRequestURL() + "/");
            return;
        }

        queryString = request.getQueryString();

        String pathTranslated = request.getPathTranslated();
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();

        self = contextPath + servletPath;

        String fileURL = requestURI.replaceFirst(contextPath, "");
        fileURL = fileURL.replaceFirst(servletPath, "");

        folder = new Folder(f, pathInfo, fileURL);

        folder.load();

        String actionresult = "";

        if (FileUpload.isMultipartContent(request)) {
            try {
                actionresult = handleUpload(request, folder);
                folder.load();
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else if (formPosted || null != queryString) {
            try {
                actionresult = handleQuery(request, response, folder);
            } catch (OutOfSyncException e) {
                actionresult = e.getMessage();
            }
            if (null == actionresult) {
                return;
            }
        }

        request.setAttribute("actionresult", actionresult);
    } catch (SecurityException e) {
        request.setAttribute("actionresult", e.getClass().getName() + " " + e.getMessage());
        request.setAttribute("fatalerror", new Boolean(true));

    }

    String s = request.getRemoteUser();

    Principal principal = request.getUserPrincipal();

    if (principal != null) {
        request.setAttribute("principal", principal.getName());
    }

    request.setAttribute("self", self);

    s = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z").format(new Date());

    request.setAttribute("date", s);

    request.setAttribute("version", version);

    request.setAttribute("builddate", builddate);

    request.setAttribute("javaversion", System.getProperty("java.version"));

    request.setAttribute("serverInfo", getServletContext().getServerInfo());

    request.setAttribute("jfmhome", "https://java.net/projects/jfm");

    request.setAttribute("url", contextPath);

    request.setAttribute("path", pathInfo);

    request.setAttribute("folder", folder);

    String forward = "/WEB-INF/fm.jsp";

    if (queryString != null) {
        // hide get query parameters
        //         response.sendRedirect(request.getRequestURL() + "");
        //         return;
    }

    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(forward);

    requestDispatcher.forward(request, response);
}

From source file:ro.raisercostin.web.DebuggingFilter.java

public String debug(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response,
        DebuggingPrinter debuggingPrinter, boolean debugAll, boolean debugRequest) {
    final JspFactory jspFactory = JspFactory.getDefaultFactory();
    HttpSession session = request.getSession();
    debuggingPrinter.addHeader();//from  w  ww  .j  av  a2 s. c  o  m
    debuggingPrinter.addSection("Request Parameters");
    for (Iterator iterator = request.getParameterMap().entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> parameter = (Map.Entry<String, Object>) iterator.next();
        addRow(debuggingPrinter, parameter.getKey(),
                StringUtils.arrayToCommaDelimitedString((Object[]) parameter.getValue()));
    }
    debuggingPrinter.endSection();

    if (debugRequest) {
        debuggingPrinter.addSection("Request Header");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String parameterName = (String) e.nextElement();
            addRow(debuggingPrinter, parameterName,
                    debuggingPrinter.transform(request.getHeader(parameterName)));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Request Attributes");
        java.util.Enumeration en = request.getAttributeNames();
        while (en.hasMoreElements()) {
            String attrName = (String) en.nextElement();
            try {
                addRow(debuggingPrinter, split(attrName, 50), toString2(request.getAttribute(attrName), 120));
            } catch (Exception e) {
                addRow(debuggingPrinter, split(attrName, 50), toString(e, 120));
            }

        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Session Attributes");
        en = session.getAttributeNames();
        while (en.hasMoreElements()) {
            String attrName = (String) en.nextElement();
            try {
                addRow(debuggingPrinter, split(attrName, 50), toString2(session.getAttribute(attrName), 120));
            } catch (Exception e) {
                addRow(debuggingPrinter, split(attrName, 50), toString(e, 120));
            }
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Request Info");
        addRow(debuggingPrinter, "AuthType", request.getAuthType());
        addRow(debuggingPrinter, "ContextPath", request.getContextPath());
        addRow(debuggingPrinter, "Method", request.getMethod());
        addRow(debuggingPrinter, "PathInfo", request.getPathInfo());
        addRow(debuggingPrinter, "PathTranslated", request.getPathTranslated());
        addRow(debuggingPrinter, "Protocol", request.getProtocol());
        addRow(debuggingPrinter, "QueryString", request.getQueryString());
        addRow(debuggingPrinter, "RemoteAddr", request.getRemoteAddr());
        addRow(debuggingPrinter, "RemoteUser", request.getRemoteUser());
        addRow(debuggingPrinter, "RequestedSessionId", request.getRequestedSessionId());
        addRow(debuggingPrinter, "RequestURI", request.getRequestURI());
        addRow(debuggingPrinter, "RequestURL", request.getRequestURL().toString());
        addRow(debuggingPrinter, "ServletPath", request.getServletPath());
        addRow(debuggingPrinter, "Scheme", request.getScheme());
        addRow(debuggingPrinter, "ServletPath", request.getServletPath());
    }
    if (debugAll) {
        debuggingPrinter.addSection("Server");
        addRow(debuggingPrinter, "Server Info", servletContext.getServerInfo());
        addRow(debuggingPrinter, "Servlet Engine Version",
                servletContext.getMajorVersion() + "." + servletContext.getMinorVersion());
        addRow(debuggingPrinter, "JSP Version", jspFactory.getEngineInfo().getSpecificationVersion());
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("JVM Properties");
        for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) {
            String parameterName = (String) e.nextElement();
            addRow(debuggingPrinter, parameterName,
                    debuggingPrinter.transform(System.getProperty(parameterName)));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Environment");
        for (Map.Entry<String, String> property : System.getenv().entrySet()) {
            addRow(debuggingPrinter, property.getKey(), debuggingPrinter.transform(property.getValue()));
        }
        debuggingPrinter.endSection();

        debuggingPrinter.addSection("Debugger Provided by");
        addRow(debuggingPrinter, "provided by", "raisercostin");
        debuggingPrinter.addRow("source",
                "<a target='_blank' href='http://code.google.com/p/raisercostin/wiki/DebuggingFilter'>http://code.google.com/p/raisercostin/wiki/DebuggingFilter</a>");
        addRow(debuggingPrinter, "version", "1.0");
        addRow(debuggingPrinter, "timestamp", "2008.June.14");
        addRow(debuggingPrinter, "license",
                "<a target='_blank' href='http://www.apache.org/licenses/LICENSE-2.0.html'>Apache License 2.0</a>");
        debuggingPrinter.endSection();
    }
    debuggingPrinter.addFooter();
    return debuggingPrinter.getString();
}

From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java

@Override
public List<MenuEntry> getActions(final HttpServletRequest request, final Object object) {
    if (object instanceof ChannelInformation) {
        final ChannelInformation channel = (ChannelInformation) object;

        final Map<String, Object> model = new HashMap<>(1);
        model.put("channelId", channel.getId());

        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            if (!channel.getState().isLocked()) {
                result.add(new MenuEntry("Add Artifact", 100,
                        LinkTarget.createFromController(ChannelController.class, "add").expand(model),
                        Modifier.PRIMARY, null));
                result.add(new MenuEntry("Delete Channel", 400,
                        LinkTarget.createFromController(ChannelController.class, "delete").expand(model),
                        Modifier.DANGER, "trash").makeModalMessage("Delete channel",
                                "Are you sure you want to delete the whole channel?"));
                result.add(new MenuEntry("Clear Channel", 500,
                        LinkTarget.createFromController(ChannelController.class, "clear").expand(model),
                        Modifier.WARNING, null).makeModalMessage("Clear channel",
                                "Are you sure you want to delete all artifacts from this channel?"));

                result.add(new MenuEntry("Lock Channel", 600,
                        LinkTarget.createFromController(ChannelController.class, "lock").expand(model),
                        Modifier.DEFAULT, null));
            } else {
                result.add(new MenuEntry("Unlock Channel", 600,
                        LinkTarget.createFromController(ChannelController.class, "unlock").expand(model),
                        Modifier.DEFAULT, null));
            }//  ww w .  j  a va 2 s. c  o  m

            result.add(new MenuEntry("Edit", 150, "Edit Channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "edit").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Refresh aspects", 100,
                    LinkTarget.createFromController(ChannelController.class, "refreshAllAspects").expand(model),
                    Modifier.SUCCESS, "refresh"));
        }

        if (request.getRemoteUser() != null) {
            result.add(new MenuEntry("Edit", 150, "Configure Aspects", 300,
                    LinkTarget.createFromController(ChannelController.class, "aspects").expand(model),
                    Modifier.DEFAULT, null));
            result.add(new MenuEntry("Maintenance", 160, "Export channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "exportChannel").expand(model),
                    Modifier.DEFAULT, "export"));
        }

        return result;
    } else if (Tags.ACTION_TAG_CHANNELS.equals(object)) {
        final List<MenuEntry> result = new LinkedList<>();

        if (request.isUserInRole("MANAGER")) {
            // result.add ( new MenuEntry ( "Create Channel", 100, LinkTarget.createFromController ( ChannelController.class, "createDetailed" ), Modifier.PRIMARY, null ) );
            result.add(new MenuEntry("Create Channel", 120,
                    LinkTarget.createFromController(ChannelController.class, "createWithRecipe"),
                    Modifier.PRIMARY, null));
            result.add(new MenuEntry("Maintenance", 160, "Import channel", 200,
                    LinkTarget.createFromController(ChannelController.class, "importChannel"), Modifier.DEFAULT,
                    "import"));
            result.add(new MenuEntry("Maintenance", 160, "Export all channels", 300,
                    LinkTarget.createFromController(ChannelController.class, "exportAll"), Modifier.DEFAULT,
                    "export"));
        }

        return result;
    }
    return null;
}

From source file:com.krawler.spring.authHandler.authHandlerController.java

public JSONObject verifyCustomerLogin(HttpServletRequest request, HttpServletResponse response, String user,
        String pass, String login, String subdomain) throws ServletException {
    JSONObject jobj = new JSONObject();
    KwlReturnObject kmsg = null;//from   www .  j  av a2 s  . c om
    String result = "";
    HashMap<String, Object> requestParams2 = null;
    JSONObject obj = null, jret = new JSONObject();
    boolean isvalid = false;
    try {
        boolean isValidUser = false;
        String email = null;
        String companyId = null;
        String contactId = null;
        String customerId = null;
        String contactName = null;
        String userid = null;
        String mainusername = null;
        boolean isActiveCustomer = false;
        if (StringUtil.isNullOrEmpty(login)) {
            Object[] row = authHandlerDAOObj.verifyCaseLogin(user, pass, subdomain);
            if (row != null) {
                isActiveCustomer = (Boolean) row[6];
                if (isActiveCustomer) {
                    email = (String) row[0];
                    companyId = (String) row[1];
                    contactId = (String) row[2];
                    customerId = (String) row[3];
                    contactName = (String) (row[4] != null ? row[4] : "") + " "
                            + (String) (row[5] != null ? row[5] : "");// combining first name and last name for full name
                    sessionHandlerImplObj.createCustomerSession(request, email, companyId, contactId,
                            customerId, contactName.trim());
                    createSessionForCustomPartnerURLAndSysEmailId(companyId);
                    jobj = new JSONObject();
                    jobj.put("email", email);
                    jobj.put("success", true);
                    isvalid = true;
                } else {
                    jobj = new JSONObject();
                    jobj.put("success", false);
                    jobj.put("reason", "noaccess");
                    jobj.put("message", "Login has been deactivated");
                    isvalid = false;
                }
            } else {
                jobj = new JSONObject();
                jobj.put("success", false);
                jobj.put("reason", "noaccess");
                jobj.put("message", "Authentication failed");
                isvalid = false;
            }

        } else {
            String username = request.getRemoteUser();
            if (!StringUtil.isNullOrEmpty(username)) {
                // jbj = DBCon.AuthUser(username, subdomain);
                boolean toContinue = true;
                if (sessionHandlerImplObj.validateSession(request, response)) {
                    result = "alreadyloggedin";
                    toContinue = false;

                }
                if (toContinue) {
                    Object[] row = authHandlerDAOObj.verifyCaseLogin(username, subdomain);
                    if (row != null) {
                        isActiveCustomer = (Boolean) row[6];
                        if (isActiveCustomer) {
                            email = (String) row[0];
                            companyId = (String) row[1];
                            contactId = (String) row[2];
                            customerId = (String) row[3];
                            contactName = (String) row[4] + " " + (String) row[5];// combining first name and last name for full name
                            sessionHandlerImplObj.createCustomerSession(request, email, companyId, contactId,
                                    customerId, contactName);
                            createSessionForCustomPartnerURLAndSysEmailId(companyId);
                            isvalid = true;
                        } else {
                            result = "Login has been deactivated";
                        }
                    } else {
                        result = "noaccess";
                    }

                }
            } else {
                if (sessionHandlerImpl.isValidSession(request, response)) {
                    isValidUser = true;
                } else {
                    result = "timeout";
                }
            }
            if (isValidUser) {
                isvalid = true;

            } else {
                jobj.put("success", false);
                jobj.put("reason", result);
                isvalid = false;
            }
        }
    } catch (Exception e) {
        LOG.info(e.getMessage(), e);
        e.printStackTrace();
    } finally {
        try {
            jret.put("valid", isvalid);
            jret.put("data", jobj);
        } catch (JSONException ex) {
            Logger.getLogger(authHandlerController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return jret;
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

public void logLastDataChangeTime(HttpServletRequest request) throws ObjectNotFoundException {
    // Public user (not logged in) changes don't count
    // TODO: think of something better
    if (request.getRemoteUser() != null) {
        CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
        setLastCompanyDataChangeTime(company);
    }//from  w  w  w .  jav a  2 s  .  c om
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

private BaseValue getCurrentUserValue(HttpServletRequest request)
        throws MissingParametersException, ObjectNotFoundException, DisallowedException {
    BaseValue fieldValue;// ww  w .j ava 2  s . c om
    String userName = request.getRemoteUser();
    AppUserInfo currentUser = null;
    if (userName == null) {
        currentUser = ServletUtilMethods.getPublicUserForRequest(request, this.authManager.getAuthenticator());
    } else {
        currentUser = this.authManager.getUserByUserName(request, userName);
    }
    String fullname = currentUser.getForename() + " " + currentUser.getSurname();
    fullname += " (" + currentUser.getUserName() + ")";
    fieldValue = new TextValueDefn(fullname);
    return fieldValue;
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

public void setDefaultTablePrivileges(HttpServletRequest request, TableInfo newTable)
        throws DisallowedException, CantDoThatException {
    // Set table privileges
    HibernateUtil.activateObject(this.authManager.getAuthenticator());
    // ...give the user who created the table all privileges on it
    try {/*from  w ww.  j av a2s. c o  m*/
        AppUserInfo loggedInUser = this.authManager.getUserByUserName(request, request.getRemoteUser());
        this.authManager.addUserPrivilege(request, loggedInUser, PrivilegeType.MANAGE_TABLE, newTable);
        this.authManager.addUserPrivilege(request, loggedInUser, PrivilegeType.EDIT_TABLE_DATA, newTable);
        this.authManager.addUserPrivilege(request, loggedInUser, PrivilegeType.VIEW_TABLE_DATA, newTable);
    } catch (ObjectNotFoundException onfex) {
        throw new CantDoThatException("The logged in user '" + request.getRemoteUser() + "' can't be found");
    }
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from   ww w .j  a va2 s . com
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        String[] targetHost_port = settings.getHDFSWebUIAddress().split(":");
        File keyStore = new File(baseHadoopClientsService.getSuperKeystorePath());
        File trustStore = new File(baseHadoopClientsService.getSuperTrustStorePath());
        // Assume that KeyStore password and Key password are the same
        Protocol httpsProto = new Protocol("https",
                new CustomSSLProtocolSocketFactory(keyStore,
                        baseHadoopClientsService.getSuperKeystorePassword(),
                        baseHadoopClientsService.getSuperKeystorePassword(), trustStore,
                        baseHadoopClientsService.getSuperTrustStorePassword()),
                Integer.parseInt(targetHost_port[1]));
        Protocol.registerProtocol("https", httpsProto);
        // Execute the request
        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        HttpMethod m = new GetMethod(proxyRequestUri);
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //hdfs does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}