Example usage for javax.servlet.http HttpServletResponse containsHeader

List of usage examples for javax.servlet.http HttpServletResponse containsHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse containsHeader.

Prototype

public boolean containsHeader(String name);

Source Link

Document

Returns a boolean indicating whether the named response header has already been set.

Usage

From source file:org.opencms.main.OpenCmsCore.java

/**
 * This method performs the error handling for OpenCms.<p>
 *
 * @param cms the current cms context, might be null !
 * @param req the client request/* www .j a  v  a 2 s. c  o  m*/
 * @param res the client response
 * @param t the exception that occurred
 */
private void errorHandling(CmsObject cms, HttpServletRequest req, HttpServletResponse res, Throwable t) {

    // remove the controller attribute from the request
    CmsFlexController.removeController(req);

    boolean canWrite = (!res.isCommitted() && !res.containsHeader("Location"));
    int status = -1;
    boolean isGuest = true;

    if (t instanceof ServletException) {
        ServletException s = (ServletException) t;
        if (s.getRootCause() != null) {
            t = s.getRootCause();
        }
    } else if (t instanceof CmsSecurityException) {
        // access error - display login dialog
        if (canWrite) {
            try {
                m_authorizationHandler.requestAuthorization(req, res, getLoginFormURL(req, res));
            } catch (IOException ioe) {
                // there is nothing we can do about this
            }
            return;
        }
    } else if (t instanceof CmsDbEntryNotFoundException) {
        // user or group does not exist
        status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        isGuest = false;
    } else if (t instanceof CmsVfsResourceNotFoundException) {
        // file not found - display 404 error.
        status = HttpServletResponse.SC_NOT_FOUND;
    } else if (t instanceof CmsException) {
        if (t.getCause() != null) {
            t = t.getCause();
        }
        LOG.error(t.getLocalizedMessage(), t);
    } else {
        LOG.error(t.getLocalizedMessage(), t);
    }

    if (status < 1) {
        // error code not set - set "internal server error" (500)
        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }
    res.setStatus(status);

    try {
        if ((cms != null) && (cms.getRequestContext().getCurrentUser() != null)) {
            isGuest = isGuest && (cms.getRequestContext().getCurrentUser().isGuestUser()
                    || cms.userInGroup(cms.getRequestContext().getCurrentUser().getName(),
                            OpenCms.getDefaultUsers().getGroupGuests()));
        }
    } catch (CmsException e) {
        // result is false
        LOG.error(e.getLocalizedMessage(), e);
    }

    if (canWrite) {
        res.setContentType("text/html");
        CmsRequestUtil.setNoCacheHeaders(res);
        if (!isGuest && (cms != null) && !cms.getRequestContext().getCurrentProject().isOnlineProject()) {
            try {
                res.setStatus(HttpServletResponse.SC_OK);
                res.getWriter().print(createErrorBox(t, req, cms));
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        } else {
            try {
                res.sendError(status, t.toString());
            } catch (IOException e) {
                // can be ignored
                LOG.error(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Handles a YaCy servlet template, reads the template and replaces the template
 * items with actual values. Because of supported server side includes target 
 * might not be the same as request.getPathInfo
 * //from w w  w.  j  av  a 2 s .c  om
 * @param target the path to the template
 * @param request the remote servlet request
 * @param response
 * @throws IOException
 * @throws ServletException
 */
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Switchboard sb = Switchboard.getSwitchboard();

    String localeSelection = sb.getConfig("locale.language", "browser");
    if (localeSelection.endsWith("browser")) {
        String lng = request.getLocale().getLanguage();
        if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer
            localeSelection = "default";
        } else {
            localeSelection = lng;
        }
    }
    File targetFile = getLocalizedFile(target, localeSelection);
    File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile());
    String targetExt = target.substring(target.lastIndexOf('.') + 1);

    long now = System.currentTimeMillis();
    if (target.endsWith(".css")) {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year)
    } else if (target.endsWith(".png")) {
        // expires in 1 minute (reduce heavy image creation load)
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear();
        }
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60));
    } else {
        response.setDateHeader(HeaderFramework.LAST_MODIFIED, now);
        response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now
    }

    if ((targetClass != null)) {
        serverObjects args = new serverObjects();
        Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters
        while (argNames.hasMoreElements()) {
            String argName = argNames.nextElement();
            // standard attributes are just pushed as string
            args.put(argName, request.getParameter(argName));
        }
        RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt);
        // add multipart-form fields to parameter
        if (ServletFileUpload.isMultipartContent(request)) {
            final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING);
            if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) {
                parseMultipart(new GZIPRequestWrapper(request), args);
            } else {
                parseMultipart(request, args);
            }
        }
        // eof modification to read attribute
        Object tmp;
        try {
            if (args.isEmpty()) {
                // yacy servlets typically test for args != null (but not for args .isEmpty())
                tmp = invokeServlet(targetClass, legacyRequestHeader, null);
            } else {
                tmp = invokeServlet(targetClass, legacyRequestHeader, args);
            }
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof InvalidURLLicenceException) {
                /* A non authaurized user is trying to fetch a image with a bad or already released license code */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            if (e.getCause() instanceof TemplateMissingParameterException) {
                /* A template is used but miss some required parameter */
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage());
                return;
            }
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        } catch (IllegalArgumentException | IllegalAccessException e) {
            ConcurrentLog.logException(e);
            throw new ServletException(targetFile.getAbsolutePath());
        }

        if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) {

            net.yacy.cora.util.ByteBuffer result = null;

            if (tmp instanceof RasterPlotter) {
                final RasterPlotter yp = (RasterPlotter) tmp;
                // send an image to client
                result = RasterPlotter.exportImage(yp.getImage(), "png");
            } else if (tmp instanceof EncodedImage) {
                final EncodedImage yp = (EncodedImage) tmp;
                result = yp.getImage();
                /** When encodedImage is empty, return a code 500 rather than only an empty response 
                 * as it is better handled across different browsers */
                if (result == null || result.length() == 0) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    result.close();
                    return;
                }
                if (yp.isStatic()) { // static image never expires
                    response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour
                }
            } else if (tmp instanceof Image) {
                final Image i = (Image) tmp;

                // generate an byte array from the generated image
                int width = i.getWidth(null);
                if (width < 0) {
                    width = 96; // bad hack
                }
                int height = i.getHeight(null);
                if (height < 0) {
                    height = 96; // bad hack
                }
                final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                bi.createGraphics().drawImage(i, 0, 0, width, height, null);
                result = RasterPlotter.exportImage(bi, targetExt);
            }

            updateRespHeadersForImages(target, response);
            final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());
            response.setContentType(mimeType);
            response.setContentLength(result.length());
            response.setStatus(HttpServletResponse.SC_OK);

            result.writeTo(response.getOutputStream());
            result.close();
            return;
        }

        if (tmp instanceof InputStream) {
            /* Images and favicons can also be written directly from an inputStream */
            updateRespHeadersForImages(target, response);

            writeInputStream(response, targetExt, (InputStream) tmp);
            return;
        }

        servletProperties templatePatterns;
        if (tmp == null) {
            // if no args given, then tp will be an empty Hashtable object (not null)
            templatePatterns = new servletProperties();
        } else if (tmp instanceof servletProperties) {
            templatePatterns = (servletProperties) tmp;

            if (templatePatterns.getOutgoingHeader() != null) {
                // handle responseHeader entries set by servlet
                ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader();
                for (String hdrkey : tmpouthdr.keySet()) {
                    if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. )
                        String val = tmpouthdr.get(hdrkey);
                        if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN)
                            response.setHeader(hdrkey, tmpouthdr.get(hdrkey));
                        }
                    }
                }
                // handle login cookie
                if (tmpouthdr.getCookiesEntries() != null) {
                    for (Cookie c : tmpouthdr.getCookiesEntries()) {
                        response.addCookie(c);
                    }
                }
            }
        } else {
            templatePatterns = new servletProperties((serverObjects) tmp);
        }

        // handle YaCy http commands
        // handle action auth: check if the servlets requests authentication
        if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
            if (!request.authenticate(response)) {
                return;
            }
            //handle action forward
        } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
            String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");

            if (location.isEmpty()) {
                location = request.getPathInfo();
            }
            //TODO: handle equivalent of this from httpdfilehandler
            // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo());
            // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?

            response.setHeader(HeaderFramework.LOCATION, location);
            response.setStatus(HttpServletResponse.SC_FOUND);
            return;
        }

        if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {

            sb.setConfig("server.servlets.called",
                    appendPath(sb.getConfig("server.servlets.called", ""), target));
            if (args != null && !args.isEmpty()) {
                sb.setConfig("server.servlets.submitted",
                        appendPath(sb.getConfig("server.servlets.submitted", ""), target));
            }

            // add the application version, the uptime and the client name to every rewrite table
            templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
            templatePatterns.put(servletProperties.PEER_STAT_UPTIME,
                    ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
            templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID());
            templatePatterns.put(servletProperties.PEER_STAT_MYTIME,
                    GenericFormatter.SHORT_SECOND_FORMATTER.format());
            templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target));
            Seed myPeer = sb.peers.mySeed();
            templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
            templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
            boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2;
            templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol)

            templatePatterns.put("simpleheadernavbar",
                    sb.getConfig("decoration.simpleheadernavbar", "navbar-default"));

            // add navigation keys to enable or disable menu items
            templatePatterns.put("navigation-p2p",
                    sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
            templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0);
            String submitted = sb.getConfig("server.servlets.submitted", "");
            boolean crawler_enabled = true; /*
                                            submitted.contains("Crawler_p") ||
                                            submitted.contains("ConfigBasic") ||
                                            submitted.contains("Load_RSS_p");*/
            boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p")
                    || submitted.contains("CrawlStart");
            templatePatterns.put("navigation-crawlmonitor", crawler_enabled);
            templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0);
            templatePatterns.put("navigation-advanced", advanced_enabled);
            templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0);
            templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE,
                    sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, ""));
            templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT,
                    sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, ""));
            templatePatterns.put("clientlanguage", localeSelection);

            String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString());

            InputStream fis;
            long fileSize = targetFile.length();

            if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
                // read file completely into ram, avoid that too many files are open at the same time
                fis = new ByteArrayInputStream(FileUtils.read(targetFile));
            } else {
                fis = new BufferedInputStream(new FileInputStream(targetFile));
            }

            // set response header
            response.setContentType(mimeType);
            response.setStatus(HttpServletResponse.SC_OK);
            ByteArrayOutputStream bas = new ByteArrayOutputStream(4096);
            try {
                // apply templates
                TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns);

                // handle SSI
                parseSSI(bas.toByteArray(), request, response);
            } finally {
                try {
                    fis.close();
                } catch (IOException ignored) {
                    ConcurrentLog.warn("FILEHANDLER",
                            "YaCyDefaultServlet: could not close target file " + targetFile.getName());
                }

                try {
                    bas.close();
                } catch (IOException ignored) {
                    /* Should never happen with a ByteArrayOutputStream */
                }
            }
        }
    }
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

/**
 * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
 *
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 *//*from   w  w  w. j a  v  a2s  .co  m*/
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper,
        FilterChain filterChain) throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    AuthenticationHandler authHandler = getAuthenticationHandler();
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: {}", ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }

                filterChainWrapper.doFilter(httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) { // added this code for atlas error handling and fallback
                if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.apache.ranger.security.web.filter.RangerKrbFilter.java

/**
 * If the request has a valid authentication token it allows the request to continue to the target resource,
 * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
 *
 * @param request the request object./* ww w. j  av  a2s  .co  m*/
 * @param response the response object.
 * @param filterChain the filter chain object.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            ex.printStackTrace();
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isHttps);
                }
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        ex.printStackTrace();
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: " + ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                String agents = PropertiesUtil.getProperty(BROWSER_USER_AGENT_PARAM,
                        RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT);
                if (agents == null) {
                    agents = RangerCSRFPreventionFilter.BROWSER_USER_AGENTS_DEFAULT;
                }
                parseBrowserUserAgents(agents);
                if (isBrowser(httpRequest.getHeader(RangerCSRFPreventionFilter.HEADER_USER_AGENT))) {
                    ((HttpServletResponse) response).setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, "");
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie")
                                && value.startsWith("RANGERADMINSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}

From source file:org.betaconceptframework.astroboa.resourceapi.filter.BinaryChannelLoaderFilter.java

private void loadAndReturnContentOfBinaryChannel(String fileAccessInfo, HttpServletResponse httpServletResponse)
        throws IOException {

    BinaryChannelFileAccessInfoProcessor fileAccessInfoProcessor = new BinaryChannelFileAccessInfoProcessor(
            fileAccessInfo);//from  w w w .  j av  a  2s . c  om

    if (!fileAccessInfoProcessor.processFileAccessInfo()) {
        logger.warn("Invalid file access info " + fileAccessInfo);
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        String repositoryId = fileAccessInfoProcessor.getRepositoryId();

        String fileName = fileAccessInfoProcessor.getFileName();

        String mimeType = fileAccessInfoProcessor.getMimeType();

        String width = fileAccessInfoProcessor.getWidth();

        String height = fileAccessInfoProcessor.getHeight();

        String contentDispositionType = fileAccessInfoProcessor.getContentDispositionType();

        String relativePathToStream = fileAccessInfoProcessor.getRelativePathToStream();

        //Check that repository home directory exists
        if (MapUtils.isEmpty(repositoryHomeDirectoriesPerRepositoryId) || StringUtils.isBlank(repositoryId)
                || !repositoryHomeDirectoriesPerRepositoryId.containsKey(repositoryId)) {
            logger.error("No available home directory exists for repository " + repositoryId);

            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            logger.debug("Ready to serve binary channel : path {}, mime-type: {}, filename :{}",
                    new Object[] { relativePathToStream, mimeType, fileName });

            File resource = null;
            try {
                //Load file
                resource = new File(repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator
                        + relativePathToStream);

                if (!resource.exists()) {
                    logger.warn("Could not locate resource "
                            + repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator
                            + relativePathToStream);
                    httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                } else {

                    //It may well be the case where filename and mime type are not provided
                    //in file access info (especially if binary channel is unmanaged).
                    //In this cases obtain filename and mime type from resource
                    if (StringUtils.isBlank(fileName)) {
                        fileName = resource.getName();
                    }

                    if (StringUtils.isBlank(mimeType)) {
                        mimeType = new MimetypesFileTypeMap().getContentType(resource);
                    }

                    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

                    httpServletResponse.setDateHeader("Last-Modified", resource.lastModified());
                    httpServletResponse.setContentType(mimeType);

                    String processedFilename = org.betaconceptframework.utility.FilenameUtils
                            .convertFilenameGreekCharactersToEnglishAndReplaceInvalidCharacters(fileName);

                    //
                    byte[] resourceByteArray = FileUtils.readFileToByteArray(resource);

                    if (StringUtils.isNotBlank(mimeType) && mimeType.startsWith("image/")) {

                        resourceByteArray = resizeImageResource(resourceByteArray, mimeType, width, height);

                        httpServletResponse.setHeader("Content-Disposition",
                                contentDispositionType + ";filename=" + (width != null ? "W" + width : "")
                                        + (height != null ? "H" + height : "")
                                        + (width != null || height != null ? "-" : "") + processedFilename);

                    } else {
                        //Resource is not an image. Set charset encoding 
                        httpServletResponse.setCharacterEncoding("UTF-8");
                    }

                    if (!httpServletResponse.containsHeader("Content-Disposition")) {
                        httpServletResponse.setHeader("Content-Disposition",
                                contentDispositionType + ";filename=" + processedFilename);
                    }

                    httpServletResponse.setHeader("ETag",
                            ContentApiUtils.createETag(resource.lastModified(), resourceByteArray.length));
                    httpServletResponse.setContentLength(resourceByteArray.length);

                    try {
                        IOUtils.write(resourceByteArray, servletOutputStream);

                        servletOutputStream.flush();
                    } catch (Exception e) {
                        //Something went wrong while writing data to stream.
                        //Just log to debug and not to warn
                        logger.debug("", e);
                        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                    }
                }
            } catch (Exception e) {
                logger.error("", e);
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }
}

From source file:io.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override/*  ww  w. jav  a2 s. c  o  m*/
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(new Random().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity)
                            throws Exception {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request)
                throws IOException, AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), isHttps);
                        }
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug("Authentication exception: " + ex.getMessage(), ex);
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:org.apache.druid.security.kerberos.KerberosAuthenticator.java

@Override
public Filter getFilter() {
    return new AuthenticationFilter() {
        private Signer mySigner;

        @Override//  w  w w .j a v  a 2s. com
        public void init(FilterConfig filterConfig) throws ServletException {
            ClassLoader prevLoader = Thread.currentThread().getContextClassLoader();
            try {
                // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader.
                // In case of druid since the class is actually loaded as an extension and filter init is done in main thread.
                // We need to set the classloader explicitly to extension class loader.
                Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader());
                super.init(filterConfig);
                String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
                configPrefix = (configPrefix != null) ? configPrefix + "." : "";
                Properties config = getConfiguration(configPrefix, filterConfig);
                String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET);
                if (signatureSecret == null) {
                    signatureSecret = Long.toString(ThreadLocalRandom.current().nextLong());
                    log.warn("'signature.secret' configuration not set, using a random value as secret");
                }
                final byte[] secretBytes = StringUtils.toUtf8(signatureSecret);
                SignerSecretProvider signerSecretProvider = new SignerSecretProvider() {
                    @Override
                    public void init(Properties config, ServletContext servletContext, long tokenValidity) {

                    }

                    @Override
                    public byte[] getCurrentSecret() {
                        return secretBytes;
                    }

                    @Override
                    public byte[][] getAllSecrets() {
                        return new byte[][] { secretBytes };
                    }
                };
                mySigner = new Signer(signerSecretProvider);
            } finally {
                Thread.currentThread().setContextClassLoader(prevLoader);
            }
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper
        @Override
        protected AuthenticationToken getToken(HttpServletRequest request) throws AuthenticationException {
            AuthenticationToken token = null;
            String tokenStr = null;
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                        tokenStr = cookie.getValue();
                        try {
                            tokenStr = mySigner.verifyAndExtract(tokenStr);
                        } catch (SignerException ex) {
                            throw new AuthenticationException(ex);
                        }
                        break;
                    }
                }
            }
            if (tokenStr != null) {
                token = AuthenticationToken.parse(tokenStr);
                if (!token.getType().equals(getAuthenticationHandler().getType())) {
                    throw new AuthenticationException("Invalid AuthenticationToken type");
                }
                if (token.isExpired()) {
                    throw new AuthenticationException("AuthenticationToken expired");
                }
            }
            return token;
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            HttpServletRequest httpReq = (HttpServletRequest) request;

            // If there's already an auth result, then we have authenticated already, skip this.
            if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) {
                filterChain.doFilter(request, response);
                return;
            }

            if (loginContext == null) {
                initializeKerberosLogin();
            }

            String path = ((HttpServletRequest) request).getRequestURI();
            if (isExcluded(path)) {
                filterChain.doFilter(request, response);
            } else {
                String clientPrincipal = null;
                try {
                    Cookie[] cookies = httpReq.getCookies();
                    if (cookies == null) {
                        clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request);
                    } else {
                        clientPrincipal = null;
                        for (Cookie cookie : cookies) {
                            if ("hadoop.auth".equals(cookie.getName())) {
                                Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue());
                                if (matcher.matches()) {
                                    clientPrincipal = matcher.group(1);
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception ex) {
                    clientPrincipal = null;
                }

                if (clientPrincipal != null) {
                    request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                            new AuthenticationResult(clientPrincipal, authorizerName, name, null));
                }
            }

            doFilterSuper(request, response, filterChain);
        }

        // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling
        private void doFilterSuper(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            boolean unauthorizedResponse = true;
            int errCode = HttpServletResponse.SC_UNAUTHORIZED;
            AuthenticationException authenticationEx = null;
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            boolean isHttps = "https".equals(httpRequest.getScheme());
            try {
                boolean newToken = false;
                AuthenticationToken token;
                try {
                    token = getToken(httpRequest);
                } catch (AuthenticationException ex) {
                    log.warn("AuthenticationToken ignored: " + ex.getMessage());
                    // will be sent back in a 401 unless filter authenticates
                    authenticationEx = ex;
                    token = null;
                }
                if (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) {
                    if (token == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest));
                        }
                        token = getAuthenticationHandler().authenticate(httpRequest, httpResponse);
                        if (token != null && token.getExpires() != 0
                                && token != AuthenticationToken.ANONYMOUS) {
                            token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                        }
                        newToken = true;
                    }
                    if (token != null) {
                        unauthorizedResponse = false;
                        if (log.isDebugEnabled()) {
                            log.debug("Request [{%s}] user [{%s}] authenticated", getRequestURL(httpRequest),
                                    token.getUserName());
                        }
                        final AuthenticationToken authToken = token;
                        httpRequest = new HttpServletRequestWrapper(httpRequest) {

                            @Override
                            public String getAuthType() {
                                return authToken.getType();
                            }

                            @Override
                            public String getRemoteUser() {
                                return authToken.getUserName();
                            }

                            @Override
                            public Principal getUserPrincipal() {
                                return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                            }
                        };
                        if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                            String signedToken = mySigner.sign(token.toString());
                            tokenToAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                                    token.getExpires(), !token.isExpired() && token.getExpires() > 0, isHttps);
                            request.setAttribute(SIGNED_TOKEN_ATTRIBUTE,
                                    tokenToCookieString(signedToken, getCookieDomain(), getCookiePath(),
                                            token.getExpires(), !token.isExpired() && token.getExpires() > 0,
                                            isHttps));
                        }
                        // Since this request is validated also set DRUID_AUTHENTICATION_RESULT
                        request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT,
                                new AuthenticationResult(token.getName(), authorizerName, name, null));
                        doFilter(filterChain, httpRequest, httpResponse);
                    }
                } else {
                    unauthorizedResponse = false;
                }
            } catch (AuthenticationException ex) {
                // exception from the filter itself is fatal
                errCode = HttpServletResponse.SC_FORBIDDEN;
                authenticationEx = ex;
                if (log.isDebugEnabled()) {
                    log.debug(ex, "Authentication exception: " + ex.getMessage());
                } else {
                    log.warn("Authentication exception: " + ex.getMessage());
                }
            }
            if (unauthorizedResponse) {
                if (!httpResponse.isCommitted()) {
                    tokenToAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, false, isHttps);
                    // If response code is 401. Then WWW-Authenticate Header should be
                    // present.. reset to 403 if not found..
                    if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(
                            org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) {
                        errCode = HttpServletResponse.SC_FORBIDDEN;
                    }
                    if (authenticationEx == null) {
                        // Don't send an error response here, unlike the base AuthenticationFilter implementation.
                        // This request did not use Kerberos auth.
                        // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow
                        // other Authenticator implementations to check the request.
                        filterChain.doFilter(request, response);
                    } else {
                        // Do send an error response here, we attempted Kerberos authentication and failed.
                        httpResponse.sendError(errCode, authenticationEx.getMessage());
                    }
                }
            }
        }
    };
}

From source file:org.infoscoop.web.ProxyServlet.java

public void doProcess(HttpServletRequest request, HttpServletResponse response, int methodType)
        throws ServletException, IOException {
    int statusCode = 0;
    String url = request.getParameter("url");
    ProxyRequest proxyRequest = null;/*ww w. ja v  a2s.  c o m*/

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {

        String filterType = request.getParameter("filter");

        proxyRequest = new ProxyRequest(url, filterType);

        String filterEncoding = request.getParameter("filterEncoding");
        proxyRequest.setFilterEncoding(filterEncoding);

        proxyRequest.setLocales(request.getLocales());
        proxyRequest.setPortalUid((String) request.getSession().getAttribute("Uid"));

        int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
        proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);

        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
        }

        //The certification for iframe
        String authTypeParam = request.getParameter("authType");
        if (authTypeParam != null && !"".equals(authTypeParam)) {
            proxyRequest.putRequestHeader("authType", authTypeParam);
            proxyRequest.putRequestHeader("authuserid", request.getParameter("authuserid"));
            proxyRequest.putRequestHeader("authpassword", request.getParameter("authpassword"));
        }

        for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) {
            String name = (String) names.nextElement();

            proxyRequest.setFilterParameter(name, request.getParameter(name));
        }

        try {
            String otherMethod = request.getHeader("MSDPortal-method");
            if (otherMethod == null)
                otherMethod = request.getParameter("method");

            if (methodType == METHOD_GET) {
                if (otherMethod != null && otherMethod.equalsIgnoreCase("delete")) {
                    statusCode = proxyRequest.executeDelete();
                } else if ("postCredential".equals(authTypeParam)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } else {
                if ("get".equalsIgnoreCase(otherMethod)) {
                    statusCode = proxyRequest.executeGet();
                } else {
                    proxyRequest.setReqeustBody(request.getInputStream());
                    if (otherMethod == null || "post".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePost();
                    } else if ("put".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executePut();
                    } else if ("report".equalsIgnoreCase(otherMethod)) {
                        statusCode = proxyRequest.executeReport();
                        if (statusCode == 207)
                            statusCode = 200;
                    }
                }
            }

        } catch (SocketTimeoutException ex) {
            // When the status code was 408, Firefox did not move well.
            // ABecause the cords such as 10408 are converted into 500 by Apache-GlassFish cooperation, we set it in a header.Apache-GlassFish.
            response.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        } catch (ConnectTimeoutException ex) {
            // In the case of connection-timeout,  we don't try it again.
            //response.setHeader(HttpStatusCode.HEADER_NAME,
            //      HttpStatusCode.MSD_SC_TIMEOUT);
            throw ex;
        }

        Map<String, List<String>> responseHeaders = proxyRequest.getResponseHeaders();
        if (statusCode == 401) {

            String wwwAuthHeader = proxyRequest.getResponseHeader("WWW-Authenticate");
            if (wwwAuthHeader == null) {
                statusCode = 403;
            } else if (wwwAuthHeader.toLowerCase().startsWith("basic")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "basic");
            } else if (wwwAuthHeader.toLowerCase().startsWith("ntlm")
                    || wwwAuthHeader.toLowerCase().startsWith("negotiate")) {
                statusCode = 200;
                response.setHeader("MSDPortal-AuthType", "ntlm");
            }
        }
        response.setStatus(statusCode);

        if (log.isInfoEnabled()) {
            log.info("Response-Status: " + statusCode);
        }

        StringBuffer headersSb = new StringBuffer();
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {

            String name = entry.getKey();
            if (name.equalsIgnoreCase("Transfer-Encoding") || name.equalsIgnoreCase("X-Powered-By")) {
                continue;
            }

            for (String value : entry.getValue()) {
                response.setHeader(entry.getKey(), value);
                headersSb.append(name + "=" + value + ",  ");
            }
        }

        if (!response.containsHeader("Connection")) {
            response.setHeader("Connection", "close");
            headersSb.append("Connection=close,  ");
        }

        if (log.isInfoEnabled())
            log.info("ResponseHeader: " + headersSb);

        String cacheHeader = request.getHeader("MSDPortal-Cache");

        InputStream responseBody = proxyRequest.getResponseBody();

        bos = new BufferedOutputStream(response.getOutputStream());

        if (responseBody != null) {

            //bis = new BufferedInputStream(
            //      new ByteArrayInputStream(bytes));
            bis = new BufferedInputStream(responseBody);

            if (log.isDebugEnabled()) {
                /*
                bis.mark(10240000);
                BufferedReader br =  new BufferedReader(new InputStreamReader(bis,"UTF-8"));
                        
                StringBuffer logStr = new StringBuffer();
                String out = null;
                while((out = br.readLine())!= null){
                   logStr.append(out);
                }
                        
                log.debug(logStr);
                bis.reset();
                */
                bis = printDebug(bis);
            }

            String cacheID = null;
            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse")) {

                //Process to save the cash
                String uid = (String) request.getSession().getAttribute("Uid");
                if (uid == null)
                    uid = request.getHeader("MSDPortal-SessionId");

                Map<String, List<String>> headerMap = proxyRequest.getResponseHeaders();

                try {
                    cacheID = CacheService.getHandle().insertCache(uid, url /*proxyRequest.getTargetURL() + "?"
                                                                            + request.getQueryString()*/, bis,
                            headerMap);
                    if (log.isInfoEnabled())
                        log.info("save cache : id = " + cacheID);
                } catch (Exception e) {
                    log.error(e);
                    //response.sendError(500, e.getMessage());
                }
            }

            if (cacheHeader != null && cacheHeader.equals("Cache-NoResponse") && cacheID != null) {
                response.setHeader("MSDPortal-Cache-ID", cacheID);
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Content-Length", "1");
                //response.setHeader("Content-Length", "0");
                //response.setHeader("Connection", "close");
                bos.write(0);
                bos.flush();
                //response.setStatus(204);
            } else {
                if (cacheHeader != null && cacheHeader.equals("No-Cache")) {
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                }
                if (!response.containsHeader("Content-Length") || statusCode == 500) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    byte[] b = new byte[1024];
                    int c = 0;
                    while ((c = bis.read(b)) != -1) {
                        baos.write(b, 0, c);
                    }

                    byte[] data = baos.toByteArray();
                    response.addHeader("Content-Length", String.valueOf(data.length));

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                }

                byte[] b = new byte[1024];
                int c = 0;
                while ((c = bis.read(b)) != -1) {
                    bos.write(b, 0, c);
                }
                bos.flush();
            }
        } else {
            if (statusCode == HttpStatus.SC_NO_CONTENT) {
                response.setHeader("Content-Length", "0");
            } else {
                response.setHeader("Content-Length", "1");
                bos.write(0);
                bos.flush();
            }
        }

        long elapsedtime = new Date().getTime() - lastDeleteCachesTime;
        if (elapsedtime > 86400000) {
            log.info("Delete old public caches.");
            lastDeleteCachesTime = new Date().getTime();
            CacheService.getHandle().deleteOldPublicCaches();
        }

    } catch (Exception e) {

        log.error("Failed to get the URL. " + buildMessage(statusCode, proxyRequest, url), e);
        response.sendError(500, e.getMessage());
    } finally {
        if (log.isInfoEnabled()) {
            log.info("Succeeded in getting the URL. " + buildMessage(statusCode, proxyRequest, url));
        }

        if (proxyRequest != null)
            proxyRequest.close();
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}

From source file:cn.quickj.AbstractApplication.java

@SuppressWarnings("unchecked")
final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    response.setHeader("Pragma", "No-Cache");
    response.setHeader("Cache-Control", "No-Cache");
    response.setDateHeader("Expires", 0);
    if (log.isDebugEnabled()) {
        Enumeration<String> names = request.getHeaderNames();
        StringBuffer sb = new StringBuffer();
        sb.append("Http request header:");
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            sb.append(name);/*from   www. j av  a2s . c o m*/
            sb.append(":");
            sb.append(request.getHeader(name));
            sb.append("\n");
        }
        log.debug(sb.toString());
    }

    String uri = request.getRequestURI();

    String contextPath = request.getContextPath();
    uri = uri.substring(contextPath.length());
    if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) {
        uri = Setting.defaultUri;
    }
    uri = URIUtil.decodePath(uri);
    request.setAttribute("uri", uri);
    Plugin plugin = getPlugin(uri);

    if (plugin != null)
        uri = uri.substring(plugin.getId().length() + 1);
    if (log.isDebugEnabled())
        log.debug(request.getMethod() + ":" + uri);
    if (uri.indexOf('.') == -1) {
        // license?
        boolean ok = false;
        String host = request.getServerName();
        for (int i = 0; i < hosts.length; i++) {
            if (hosts[i].equals(host) || host.endsWith(hosts[i]))
                ok = true;
        }

        if (ok) {
            Date today = new Date();
            // ?ok
            ok = today.before(endDate);
        }
        //TODO 
        //         ok=true;
        if (ok == false) {
            // license is not ok! 404
            log.error(host + "???" + endDate);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return true;
        }
        if (uri.indexOf(licensePath) != -1) {
            if (uri.indexOf("destory") != -1) {
                // ??
                endDate = new Date(0);
            } else if (uri.indexOf("info") != -1) {
                // ???
                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
            }
            try {
                response.getWriter().write(Setting.license);
            } catch (IOException e) {
            }
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // license?

        String[] s = uri.split("/");
        if (s.length >= 2) {
            if (s.length == 2) {
                if (uri.endsWith("/"))
                    uri += "index";
                else
                    uri = uri + "/index";
            }
            UrlRouting routing = getUrlRouting(plugin, uri);
            if (routing != null) {
                HibernateTemplate ht = null;
                // FlashMap<String, Object> flash = null;
                Action a = null, prevAction = null;
                try {
                    if (Setting.usedb)
                        ht = injector.getInstance(HibernateTemplate.class);
                    // flash = injector.getInstance(FlashMap.class);
                    do {
                        a = injector.getInstance(routing.getClazz());
                        request.setAttribute("quickj_action", a);
                        a.setPlugin(plugin);
                        a.setCtx(contextPath);
                        if (prevAction != null) {
                            // ActionAction
                            a.setErrorMsg(prevAction.getErrorMsg());
                            a.setMessage(prevAction.getMessage());
                        }
                        initialFilter(routing, a);
                        if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) {
                            Object[] params = new Object[routing.getMethodParamCount()];
                            int j = 0;
                            for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) {
                                params[j] = s[i];
                                j++;
                            }
                            Object ret = routing.getMethod().invoke(a, params);
                            if (ret != null) {
                                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
                                response.getWriter().write(ret.toString());
                            }
                            afterFilter(routing, a);
                        }
                        routing = null;
                        if (a.getForward() != null) {
                            routing = getUrlRouting(plugin, a.getForward());
                            prevAction = a;
                        }
                        //a.flash.updateStatus();
                    } while (routing != null);
                    if (response.containsHeader("ajax:error")) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    } else if (!response.containsHeader("Location"))
                        response.setStatus(HttpServletResponse.SC_OK);
                    else
                        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                } catch (Exception e) {
                    handleException(e, a);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } finally {
                    // if (flash != null)
                    // flash.updateStatus();
                    if (Setting.usedb) {
                        ht.clearCache();
                        ht.closeSession();
                    }
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                String ip = request.getHeader("X-Real-IP");
                if (ip == null)
                    ip = request.getRemoteAddr();
                log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER")
                        + ",IP:" + ip);
                return false;
            }
            return true;
        }
    }
    return false;
}

From source file:org.apache.zeppelin.realm.kerberos.KerberosRealm.java

/**
 * If the request has a valid authentication token it allows the request to continue to
 * the target resource,//w w  w .ja  va 2  s .c om
 * otherwise it triggers a GSS-API sequence for authentication
 *
 * @param request     the request object.
 * @param response    the response object.
 * @param filterChain the filter chain object.
 * @throws IOException      thrown if an IO error occurred.
 * @throws ServletException thrown if a processing error occurred.
 */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got token {} from httpRequest {}", token, getRequestURL(httpRequest));
                if (null != token) {
                    LOG.debug("token.isExpired() = " + token.isExpired());
                }
            }
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            if (!ex.getMessage().equals("Empty token")) {
                // will be sent back in a 401 unless filter authenticates
                authenticationEx = ex;
            }
            token = null;
        }
        if (managementOperation(token, httpRequest, httpResponse)) {
            if (token == null || token.isExpired()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication. handler: {}", getRequestURL(httpRequest),
                            this.getClass());
                }
                token = authenticate(httpRequest, httpResponse);
                if (token != null && token != AuthenticationToken.ANONYMOUS) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            if (token.getMaxInactives() > 0) {
                    //              token.setMaxInactives(System.currentTimeMillis()
                    //                  + getTokenMaxInactiveInterval() * 1000);
                    //            }
                    if (token.getExpires() != 0) {
                        token.setExpires(System.currentTimeMillis() + getTokenValidity() * 1000);
                    }
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest),
                            token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };

                // If cookie persistence is configured to false,
                // it means the cookie will be a session cookie.
                // If the token is an old one, renew the its tokenMaxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getTokenMaxInactiveInterval() > 0) {
                    //            TODO(vr): uncomment when we move to Hadoop 2.8+
                    //            token.setMaxInactives(System.currentTimeMillis()
                    //                + getTokenMaxInactiveInterval() * 1000);
                    token.setExpires(token.getExpires());
                    newToken = true;
                }
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(),
                            token.getExpires(), isCookiePersistent(), isHttps);
                }
                KerberosToken kerberosToken = new KerberosToken(token.getUserName(), token.toString());
                SecurityUtils.getSubject().login(kerberosToken);
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("managementOperation returned false for request {}." + " token: {}",
                        getRequestURL(httpRequest), token);
            }
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(),
                    isHttps);
            // If response code is 401. Then WWW-Authenticate Header should be
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                    && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                httpResponse.sendError(errCode, "Authentication required");
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}