Example usage for javax.servlet.http HttpServletResponse getHeaderNames

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

Introduction

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

Prototype

public Collection<String> getHeaderNames();

Source Link

Document

Gets the names of the headers of this response.

Usage

From source file:com.usefullc.platform.common.log.LogHandlerInterceptor.java

@Override
public void afterHandler(ActionHandler actionHandler) {
    if (!this.monitor) { // ?
        return;/*from   w  w  w  . j a v a 2  s  .c om*/
    }
    Long userId = OnlineUserManager.getUserId();
    if (userId == null) { // 
        return;
    }
    // logInfo
    LogInfoDto domain = threadLocal.get();
    if (domain == null) {
        return;
    }
    HttpServletResponse response = actionHandler.getResponse();

    domain.setActionState(actionHandler.getState());

    // ?
    if (!actionHandler.getState()) {
        domain.setErrMsg(actionHandler.getErrMsg());
    }

    // request headers
    JSONObject jsonObj = new JSONObject();

    Collection<String> headerNames = response.getHeaderNames(); //
    for (String headerName : headerNames) {
        Collection<String> headerValues = response.getHeaders(headerName);
        StringBuilder sb = new StringBuilder();
        for (String headerValue : headerValues) {
            sb.append(headerValue);
            sb.append(",");
        }
        if (sb.length() > 0) {
            sb.substring(0, sb.length() - 1);
        }
        jsonObj.put(headerName, sb.toString());
    }
    domain.setResponseHeader(jsonObj.toString());

    domain.setStatus(String.valueOf(response.getStatus()));

    // ??
    logInfoRemoteService.insertLogInfo(domain);

    // ?
    threadLocal.set(null);
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

private void logResponse(HttpServletResponse resp) {

    Collection<String> headerNames = resp.getHeaderNames();
    for (String headerName : headerNames) {
        Collection<String> values = resp.getHeaders(headerName);
        log.info("  Header {}: {}", headerName, values);
    }//from w ww  .  j  av  a  2 s.  c  om
}

From source file:org.smigo.log.LogHandler.java

public String getRequestDump(HttpServletRequest request, HttpServletResponse response, String separator) {
    StringBuilder s = new StringBuilder("####REQUEST ").append(request.getMethod()).append(" ")
            .append(request.getRequestURL()).append(separator);
    s.append("Auth type:").append(request.getAuthType()).append(separator);
    s.append("Principal:").append(request.getUserPrincipal()).append(separator);
    s.append(Log.create(request, response).toString()).append(separator);
    s.append("Headers:").append(separator);
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        s.append(headerName).append("=").append(request.getHeader(headerName)).append(separator);
    }//from  w w w .java  2 s .  com
    s.append(separator);
    s.append("####RESPONSE").append(separator);
    s.append("Status:").append(response.getStatus()).append(separator);
    s.append("Char encoding:").append(response.getCharacterEncoding()).append(separator);
    s.append("Locale:").append(response.getLocale()).append(separator);
    s.append("Content type:").append(response.getContentType()).append(separator);

    s.append("Headers:").append(separator);
    s.append(response.getHeaderNames().stream().map(rh -> rh + "=" + response.getHeader(rh))
            .collect(Collectors.joining(separator)));

    final Long start = (Long) request.getAttribute(RequestLogFilter.REQUEST_TIMER);
    if (start != null) {
        final long elapsedTime = System.nanoTime() - start;
        s.append(separator).append("####Request time elapsed:").append(elapsedTime);
        s.append("ns which is ").append(elapsedTime / 1000000).append("ms").append(separator);
    }
    return s.toString();
}

From source file:com.scooter1556.sms.server.service.AdaptiveStreamingService.java

public void sendHLSPlaylist(UUID id, String type, Integer extra, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    // Get the request base URL so we can use it in our playlist
    String baseUrl = request.getRequestURL().toString().replaceFirst("/stream(.*)", "");

    List<String> playlist;

    // Get playlist as a string array
    if (type == null) {
        playlist = generateHLSVariantPlaylist(id, baseUrl);
    } else {//from  w  w  w .  j  av a 2  s  .co  m
        playlist = generateHLSPlaylist(id, baseUrl, type, extra);
    }

    if (playlist == null) {
        LogService.getInstance().addLogEntry(LogService.Level.WARN, CLASS_NAME,
                "Unable to generate HLS playlist.", null);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to generate HLS playlist.");
        return;
    }

    // Write playlist to buffer so we can get the content length
    StringWriter playlistWriter = new StringWriter();
    for (String line : playlist) {
        playlistWriter.write(line + "\n");
    }

    // Set Header Parameters
    response.reset();
    response.setContentType("application/x-mpegurl");
    response.setContentLength(playlistWriter.toString().length());

    // Enable CORS
    response.setHeader(("Access-Control-Allow-Origin"), "*");
    response.setHeader("Access-Control-Allow-Methods", "GET");
    response.setIntHeader("Access-Control-Max-Age", 3600);

    // Write playlist out to the client
    response.getWriter().write(playlistWriter.toString());

    /*********************** DEBUG: Response Headers *********************************/
    String requestHeader = "\n***************\nResponse Header:\n***************\n";
    Collection<String> responseHeaderNames = response.getHeaderNames();

    for (int i = 0; i < responseHeaderNames.size(); i++) {
        String header = (String) responseHeaderNames.toArray()[i];
        String value = response.getHeader(header);
        requestHeader += header + ": " + value + "\n";
    }

    // Log Headers
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME, requestHeader, null);

    /********************************************************************************/

    // Log playlist
    LogService.getInstance().addLogEntry(LogService.Level.INSANE, CLASS_NAME,
            "\n************\nHLS Playlist\n************\n" + playlistWriter.toString(), null);
}

From source file:com.indeed.imhotep.web.QueryServlet.java

private SelectExecutionStats handleSelectStatement(final SelectRequestArgs args, final HttpServletResponse resp,
        SelectStatement parsedQuery, final ExecutionManager.QueryTracker queryTracker) throws IOException {
    // hashing is done before calling translate so only original JParsec parsing is considered
    final String queryForHashing = parsedQuery.toHashKeyString();

    final IQLQuery iqlQuery = IQLTranslator.translate(parsedQuery,
            args.interactive ? imhotepInteractiveClient : imhotepClient, args.imhotepUserName, metadata,
            imhotepLocalTempFileSizeLimit, imhotepDaemonTempFileSizeLimit);

    // TODO: handle requested format mismatch: e.g. cached CSV but asked for TSV shouldn't have to rerun the query
    final String queryHash = getQueryHash(queryForHashing, iqlQuery.getShardVersionList(), args.csv);
    final String cacheFileName = queryHash + (args.csv ? ".csv" : ".tsv");
    final boolean isCached = queryCache.isFileCached(cacheFileName);

    final QueryMetadata queryMetadata = new QueryMetadata();

    queryMetadata.addItem("IQL-Cached", isCached, true);
    final DateTime newestShard = getLatestShardVersion(iqlQuery.getShardVersionList());
    queryMetadata.addItem("IQL-Newest-Shard", newestShard, args.returnNewestShardVersion);

    final String shardList = shardListToString(iqlQuery.getShardVersionList());
    queryMetadata.addItem("IQL-Shard-List", shardList, args.returnShardlist);

    final List<Interval> timeIntervalsMissingShards = iqlQuery.getTimeIntervalsMissingShards();
    if (timeIntervalsMissingShards.size() > 0) {
        final String missingIntervals = intervalListToString(timeIntervalsMissingShards);
        queryMetadata.addItem("IQL-Missing-Shards", missingIntervals);
    }//w w  w .  j ava  2  s  . c  o m

    queryMetadata.setPendingHeaders(resp);

    if (args.headOnly) {
        return new SelectExecutionStats(true);
    }
    final ServletOutputStream outputStream = resp.getOutputStream();
    if (args.progress) {
        outputStream.print(": This is the start of the IQL Query Stream\n\n");
    }
    if (!args.asynchronous) {
        ResultServlet.setContentType(resp, args.avoidFileSave, args.csv, args.progress);
        if (!args.cacheReadDisabled && isCached) {
            log.trace("Returning cached data in " + cacheFileName);

            // read metadata from cache
            try {
                final InputStream metadataCacheStream = queryCache
                        .getInputStream(cacheFileName + METADATA_FILE_SUFFIX);
                final QueryMetadata cachedMetadata = QueryMetadata.fromStream(metadataCacheStream);
                queryMetadata.mergeIn(cachedMetadata);

                queryMetadata.setPendingHeaders(resp);
                resp.setHeader("Access-Control-Expose-Headers", StringUtils.join(resp.getHeaderNames(), ", "));
                if (args.progress) {
                    outputStream.println("event: header");
                    outputStream.print("data: ");
                    outputStream.print(queryMetadata.toJSON() + "\n\n");
                }
            } catch (Exception e) {
                log.info("Failed to load metadata cache from " + cacheFileName + METADATA_FILE_SUFFIX, e);
            }

            final InputStream cacheInputStream = queryCache.getInputStream(cacheFileName);
            final int rowsWritten = IQLQuery.copyStream(cacheInputStream, outputStream, iqlQuery.getRowLimit(),
                    args.progress);
            outputStream.close();
            return new SelectExecutionStats(isCached, rowsWritten, false, queryHash, 0);
        }
        final IQLQuery.WriteResults writeResults;
        final IQLQuery.ExecutionResult executionResult;
        try {
            // TODO: should we always get totals? opt out http param?
            executionResult = iqlQuery.execute(args.progress, outputStream, true);
            queryMetadata.addItem("IQL-Timings", executionResult.getTimings().replace('\n', '\t'),
                    args.progress);
            queryMetadata.addItem("IQL-Imhotep-Temp-Bytes-Written",
                    executionResult.getImhotepTempFilesBytesWritten(), args.progress);
            queryMetadata.addItem("IQL-Totals", Arrays.toString(executionResult.getTotals()), args.getTotals);

            queryMetadata.setPendingHeaders(resp);
            resp.setHeader("Access-Control-Expose-Headers", StringUtils.join(resp.getHeaderNames(), ", "));

            if (args.progress) {
                outputStream.println("event: header");
                outputStream.print("data: ");
                outputStream.print(queryMetadata.toJSON() + "\n\n");
            }
            final Iterator<GroupStats> groupStats = executionResult.getRows();
            final int groupingColumns = Math.max(1,
                    (parsedQuery.groupBy == null || parsedQuery.groupBy.groupings == null) ? 1
                            : parsedQuery.groupBy.groupings.size());
            final int selectColumns = Math.max(1,
                    (parsedQuery.select == null || parsedQuery.select.getProjections() == null) ? 1
                            : parsedQuery.select.getProjections().size());
            if (!args.asynchronous) {
                writeResults = iqlQuery.outputResults(groupStats, outputStream, args.csv, args.progress,
                        iqlQuery.getRowLimit(), groupingColumns, selectColumns, args.cacheWriteDisabled);
            } else {
                writeResults = new IQLQuery.WriteResults(0, null, groupStats, 0);
            }
            if (!args.cacheWriteDisabled && !isCached) {
                executorService.submit(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        try {
                            try {
                                final OutputStream metadataCacheStream = queryCache
                                        .getOutputStream(cacheFileName + METADATA_FILE_SUFFIX);
                                queryMetadata.toStream(metadataCacheStream);
                                metadataCacheStream.close();
                            } catch (Exception e) {
                                log.warn("Failed to upload metadata cache: " + cacheFileName, e);
                            }
                            try {
                                uploadResultsToCache(writeResults, cacheFileName, args.csv);
                            } catch (Exception e) {
                                log.warn("Failed to upload cache: " + cacheFileName, e);
                            }
                        } finally {
                            Closeables2.closeQuietly(queryTracker, log);
                        }
                        return null;
                    }
                });
                queryTracker.markAsynchronousRelease(); // going to be closed asynchronously after cache is uploaded
            }
        } catch (ImhotepOutOfMemoryException e) {
            throw Throwables.propagate(e);
        } finally {
            Closeables2.closeQuietly(iqlQuery, log);
        }
        outputStream.close();
        return new SelectExecutionStats(isCached, writeResults, queryHash,
                executionResult.getImhotepTempFilesBytesWritten());
    } else {
        // TODO: rework the async case to use the same code path as the sync case above except running under an executor
        if (!isCached && args.cacheWriteDisabled) {
            throw new IllegalStateException("Query cache is disabled so only synchronous calls can be served");
        }

        resp.setContentType("application/json");

        if (!isCached) {
            executorService.submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    try {
                        // TODO: get totals working with the cache
                        final IQLQuery.ExecutionResult executionResult = iqlQuery.execute(false, null, false);
                        final Iterator<GroupStats> groupStats = executionResult.getRows();

                        final OutputStream cacheStream = queryCache.getOutputStream(cacheFileName);
                        IQLQuery.writeRowsToStream(groupStats, cacheStream, args.csv, Integer.MAX_VALUE, false);
                        cacheStream.close(); // has to be closed
                        return null;
                    } finally {
                        Closeables2.closeQuietly(iqlQuery, log);
                        Closeables2.closeQuietly(queryTracker, log);
                    }
                }
            });
            queryTracker.markAsynchronousRelease(); // going to be closed asynchronously after cache is uploaded
        }

        final URL baseURL = new URL(args.requestURL);
        final URL resultsURL = new URL(baseURL, "results/" + cacheFileName);

        final ObjectMapper mapper = new ObjectMapper();
        final ObjectNode ret = mapper.createObjectNode();
        ret.put("filename", resultsURL.toString());
        mapper.writeValue(outputStream, ret);
        outputStream.close();
        // we don't know number of rows as it's handled asynchronously
        return new SelectExecutionStats(isCached, new IQLQuery.WriteResults(0, null, null, 0), queryHash, 0);
    }
}

From source file:photosharing.api.conx.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * //from  w  w w  .j  ava  2s.  c  om
 * @param bearer token
 * @param nonce 
 * @param request
 * @param response
 */
public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) {

    // Extracts from the Request Parameters
    String visibility = request.getParameter("visibility");
    String title = request.getParameter("title");
    String share = request.getParameter("share");
    String tagsUnsplit = request.getParameter("q");

    // Check for the Required Parameters
    if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) {
        response.setStatus(HttpStatus.SC_PRECONDITION_FAILED);

    } else {

        /*
         * Builds the URL Parameters 
         */
        StringBuilder builder = new StringBuilder();
        builder.append("visibility=" + visibility + "&");
        builder.append("title=" + title + "&");

        // The Share parameters for the URL
        if (share != null && !share.isEmpty()) {
            builder.append("shared=true&");
            builder.append("shareWith=" + share + "&");
        }

        if (visibility.compareTo("private") == 0 && share == null) {
            builder.append("shared=false&");
        }

        // Splits the TagString into Indvidual Tags
        // - Technically this API is limited to 3 tags at most. 
        String[] tags = tagsUnsplit.split(",");
        for (String tag : tags) {
            logger.info("Tag-> " + tag);
            builder.append("tag=" + tag + "&");
        }

        // Build the apiURL
        String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString();

        //API Url
        logger.info(apiUrl);

        // Add the Headers
        String length = request.getHeader("X-Content-Length");
        String contentType = request.getHeader("Content-Type");
        String fileext = contentType.split("/")[1].split(";")[0];
        String slug = title + "." + fileext;

        Request post = Request.Post(apiUrl);
        post.addHeader("Authorization", "Bearer " + bearer);
        post.addHeader("X-Update-Nonce", nonce);
        post.addHeader("Slug", slug);
        post.addHeader("Content-Type", contentType);

        logger.info("Authorization: Bearer " + bearer);
        logger.info("X-Update-Nonce: " + nonce);
        logger.info("Slug: " + slug);
        logger.info("Content-Type: " + contentType);

        try {
            //
            InputStream in = request.getInputStream();
            Base64InputStream bis = new Base64InputStream(in);

            long len = Long.parseLong(length);
            InputStreamEntity entity = new InputStreamEntity(bis, len);

            post.body(entity);

            post.removeHeaders("Cookie");

            Executor exec = ExecutorUtil.getExecutor();

            Response apiResponse = exec.execute(post);
            HttpResponse hr = apiResponse.returnResponse();

            /**
             * Check the status codes
             */
            int code = hr.getStatusLine().getStatusCode();

            logger.info("code is " + code);

            // Session is no longer valid or access token is expired
            if (code == HttpStatus.SC_FORBIDDEN) {
                response.sendRedirect("./api/logout");
            }

            // User is not authorized
            else if (code == HttpStatus.SC_UNAUTHORIZED) {
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            }

            // Duplicate Item
            else if (code == HttpStatus.SC_CONFLICT) {
                response.setStatus(HttpStatus.SC_CONFLICT);
            }

            // Checks if Created
            else if (code == HttpStatus.SC_CREATED) {
                response.setStatus(HttpStatus.SC_OK);
                /**
                 * Do Extra Processing Here to process the body
                 */
                InputStream inRes = hr.getEntity().getContent();

                // Converts XML to JSON String
                String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes);
                JSONObject obj = new JSONObject(jsonString);

                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                writer.append(obj.toString());
                writer.close();

            } else {
                // Catch All
                response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                InputStream inRes = hr.getEntity().getContent();
                String out = IOUtils.toString(inRes);
                logger.info("Content: " + out);
                logger.info("Content Type of Response: " + response.getContentType());

                Collection<String> coll = response.getHeaderNames();
                Iterator<String> iter = coll.iterator();

                while (iter.hasNext()) {
                    String header = iter.next();
                    logger.info(header + " " + response.getHeader(header));
                }

            }

        } catch (IOException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("IOException " + e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            logger.severe("SAXException " + e.toString());
        } catch (JSONException e) {
            response.setHeader("X-Application-Error", e.getClass().getName());
            response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);

            logger.severe("JSONException " + e.toString());
        }
    }
}

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.
 *//*  w  ww.j  a va 2s .  c  o  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./*from   w  ww  .ja  va2  s.com*/
 * @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());
            }
        }
    }
}