Example usage for javax.servlet.http HttpServletResponse getHeader

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

Introduction

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

Prototype

public String getHeader(String name);

Source Link

Document

Gets the value of the response header with the given name.

Usage

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 {//  w w  w. j a v  a2s  .  c  om
        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:photosharing.api.conx.UploadFileDefinition.java

/**
 * uploads a file to the IBM Connections Cloud using the Files Service
 * //  w ww  .j  av a  2  s  .co m
 * @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:com.att.ajsc.csilogging.common.CSILoggingUtils.java

public void finalizeRequest(HttpServletRequest request, HttpServletResponse response) {

    logger.debug("In...:finalizeRequest");
    String servicename = UtilLib.getServiceName(request);

    PerformanceTrackingBean perfTrackerBean = (PerformanceTrackingBean) request
            .getAttribute(PERFORMANCE_TRACKER_BEAN);
    long startTime = (long) request.getAttribute(CommonNames.START_TIME);
    AuditRecord ar = new AuditRecord();
    try {//from   w w w.  j  a v  a 2 s  .c  o m
        logger.debug("Starting application specific handling...:finalizeRequest");
        // request.setAttribute(CommonNames.AUDIT_RECORD, ar);
        // request.setAttribute(CommonNames.ATTR_START_TIME,
        // Long.valueOf(startTime).toString());
        perfTrackerBean.setAuditRecord(ar);
        servicename = LoggerNameConverter.convertNormalizedName(request, servicename);

        perfTrackerBean.setServiceName(servicename);

        perfTrackerBean.setRequestContentLen(request.getContentLength());
        perfTrackerBean.setResponseMsgSize(getResponseLength(request));
        perfTrackerBean.setMethod(request.getMethod());

        ar.setInstanceName(SystemParams.instance().getInstanceName());
        ar.setInitiatedTimestamp(UtilLib.epochToXmlGC(startTime));
        ar.setVtier(SystemParams.instance().getVtier());
        ar.setCluster(SystemParams.instance().getCluster());
        ar.setHostName(SystemParams.instance().getHostName());
        ar.setHostIPAddress(SystemParams.instance().getIpAddress());
        ar.setSubject("CW.pub.spm2." + servicename + ".response");
        ar.setMode("");
        ar.setServiceKeyData1("");
        ar.setServiceKeyData2("");
        ar.setSourceClass(CommonNames.SOURCE_CLASS);
        ar.setSourceMethod(CommonNames.AUDIT_LOGGER_NAME);
        ar.setTransactionName(servicename);
        /*
         * ar.setApplicationId(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setConversationId(request.getAttribute(CommonNames.
         * CSI_CONVERSATION_ID));
         * ar.setUniqueTransactionId(request.getAttribute(CommonNames.
         * CSI_UNIQUE_TXN_ID));
         * ar.setOriginalMessageId(request.getAttribute(CommonNames.
         * CSI_MESSAGE_ID));
         * ar.setOriginatorId(request.getAttribute(CommonNames.
         * CSI_ORIGINATOR_ID));
         * ar.setClientApp(UtilLib.ifNullThenEmpty(request.getAttribute(
         * CommonNames.CSI_CLIENT_APP))); ar.setOriginationSystemId("N/A");
         * ar.setOriginationSystemName(request.getAttribute(CommonNames.
         * CSI_USER_NAME));
         * ar.setOriginationSystemVersion(request.getAttribute(CommonNames.
         * CSI_VERSION));
         */

        ar.setApplicationId(perfTrackerBean.getUserName());
        ar.setConversationId(perfTrackerBean.getConversationId());
        ar.setUniqueTransactionId(perfTrackerBean.getUniqueTransactionId());
        ar.setOriginalMessageId(perfTrackerBean.getOriginalMessageId());
        ar.setOriginatorId(perfTrackerBean.getOriginatorId());
        ar.setClientApp(UtilLib.ifNullThenEmpty(perfTrackerBean.getClientApp()));
        ar.setOriginationSystemId("N/A");
        ar.setOriginationSystemName(perfTrackerBean.getUserName());
        ar.setOriginationSystemVersion(perfTrackerBean.getOriginationSystemVersion());

        // new fields added per new schema
        ar.setClientIP(request.getRemoteAddr());
        ar.setHttpMethod(perfTrackerBean.getMethod());
        ar.setRequestURL(request.getPathInfo());

        // PerformanceTracking.initPerfTrack(request,servicename);
        PerformanceTracking.initPerfTrack(perfTrackerBean, servicename);
        // PerformanceTracking.addPerfTrack(request, "Main", "I",
        // startTime.toString(), servicename);

        int httpCode = response.getStatus();

        if (httpCode == HttpServletResponse.SC_UNAUTHORIZED) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_401_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_401_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_FORBIDDEN) {
            ar.setResponseCode(CommonNames.CSI_AUTH_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_403_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_403_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (httpCode == HttpServletResponse.SC_NOT_IMPLEMENTED) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_501_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_501_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {
            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_503_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_503_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setTransactionStatus("E");
            ar.setFaultEntity("CSI");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);
        } else if (400 <= httpCode && httpCode <= 499) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_4NN_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_4NN_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        } else if (httpCode == 500) {

            ar.setResponseCode(CommonNames.CSI_SERVICE_UNAVAIL_ERROR);
            ar.setResponseDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultCode(CommonErrors.DEF_500_FAULT_CODE);
            ar.setFaultDescription(CommonErrors.DEF_500_FAULT_DESC);
            ar.setFaultLevel("ERROR");
            ar.setFaultEntity("CSI");
            ar.setTransactionStatus("E");
            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));
            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
            ar.setExternalFaultCode(String.valueOf(httpCode));
            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

        else {
            ar.setResponseDescription(CommonNames.CSI_SUCCESS);
            ar.setResponseCode(CommonNames.CSI_SUCCESS_RESPONSE_CODE);
            ar.setTransactionStatus("C");
        }

        // Enhance CSI logging to use the CAET error code

        if (response.getHeader(CommonNames.CAET_RestErrorCode) != null
                || response.getHeader(CommonNames.CAET_CingularErrorCode) != null) {

            // if(request.getHeader("X-CAET-CingularErrorCode") != null){
            if ("Y".equals(request.getAttribute(CommonNames.AJSC_CAET_IS_REST_SERVICE))) {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCategory));
                ar.setResponseDescription(response.getHeader(CommonNames.CAET_RestErrorDescription));

            } else

            {

                ar.setResponseCode(response.getHeader(CommonNames.CAET_CingularErrorCode));

                ar.setResponseDescription(response.getHeader(CommonNames.CAET_CingularErrorDescription));

            }

            ar.setFaultCode(response.getHeader(CommonNames.CAET_FaultCode));

            ar.setFaultDescription(response.getHeader(CommonNames.CAET_FaultDesc));

            ar.setFaultLevel(CommonNames.ERROR);

            ar.setFaultEntity(response.getHeader(CommonNames.CAET_FaultEntity));

            ar.setTransactionStatus("E");

            ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));

            // ar.setFaultTimestamp(UtilLib.epochToXmlGC((new
            // Double(System.nanoTime()/1000000)).longValue()));

            ar.setExternalFaultCode(String.valueOf(httpCode));

            ar.setExternalFaultDescription(CommonErrors.GENERIC_XML_ERROR);

        }

    }

    catch (Exception e) {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        ar.setResponseCode(CommonNames.CSI_GENERIC_UNKNOWN_ERROR);
        ar.setResponseDescription(CommonErrors.DEF_5NN_FAULT_DESC);
        ar.setFaultEntity("CSI");
        ar.setFaultCode(CommonErrors.DEF_5NN_FAULT_CODE);
        ar.setFaultDescription(e.getMessage());
        ar.setFaultLevel("ERROR");
        ar.setFaultSequenceNumber("1");
        ar.setTransactionStatus("E");
        ar.setFaultTimestamp(UtilLib.epochToXmlGC(System.currentTimeMillis()));
        // ar.setFaultTimestamp(UtilLib.epochToXmlGC(((Long)System.nanoTime()/1000000).longValue()));
        logger.error("EXCEPTION - " + e.getMessage());
    }

    finally {
        // AuditRecord ar =
        // (AuditRecord)request.getAttribute(CommonNames.AUDIT_RECORD);
        if (ar != null) {

            if (perfTrackerBean != null && !perfTrackerBean.isAsync()) {
                perfTrackerBean.setAuditRecord(ar);
                logger.debug("Before calling completeLogging");
                completeLogging(request, servicename);
            }

        } else {
            logger.debug("Audit Record is null,abort logging");
        }
    }

}

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   ww  w  .jav  a 2  s.  com
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.// w  ww  . j  a v a  2 s .c  om
 * @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.ejbca.ra.RaAuthenticationHelper.java

/** Invoke once the session is started to prevent security leak via HTTP headers related. */
private void resetUnwantedHttpHeaders(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) {
    // Ensure that we never send the JSESSIONID over an insecure (HTTP) connection
    // By default JBoss will send the JSESSIONID cookie over HTTP with the "Secure;" option. Since this is sent in clear from the server to the broswer
    // it does not really help security much that it is only sent over HTTPS from client to server.
    if (!httpServletRequest.isSecure()
            && !StringUtils.isEmpty(httpServletResponse.getHeader(HTTP_HEADER_SET_COOKIE))) {
        if (log.isDebugEnabled()) {
            log.debug("Preventing '" + HTTP_HEADER_SET_COOKIE
                    + "' HTTP header on insecure connection with value: "
                    + httpServletResponse.getHeader(HTTP_HEADER_SET_COOKIE));
        }//from   www. j a  v a  2s  .  c  o m
        httpServletResponse.setHeader(HTTP_HEADER_SET_COOKIE, "");
    }
    // Prevent sending the the X-Powered-By header e.g. "JSF/2.0"
    if (!StringUtils.isEmpty(httpServletResponse.getHeader(HTTP_HEADER_X_POWERED_BY))) {
        if (log.isDebugEnabled()) {
            log.debug("Preventing '" + HTTP_HEADER_X_POWERED_BY + "' HTTP header with value: "
                    + httpServletResponse.getHeader(HTTP_HEADER_X_POWERED_BY));
        }
        httpServletResponse.setHeader(HTTP_HEADER_X_POWERED_BY, "");
    }
}

From source file:org.mobile.mpos.interceptor.LoggerInterceptor.java

/**
 * ???/*from w  ww .  j a v  a2s . c o  m*/
 * @param response
 */
private void printHeaders(HttpServletResponse response) {
    if (response != null) {
        StringBuilder head = new StringBuilder();
        head.append(SystemUtils.LINE_SEPARATOR);
        head.append("heads:");
        head.append(SystemUtils.LINE_SEPARATOR);
        JSONObject h = new JSONObject();
        for (String headerName : response.getHeaderNames()) {
            h.put(headerName, response.getHeader(headerName));
        }
        head.append(h.toString(4));
        logger.info(head.toString());
    }
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.krb5.Krb5Authenticator.java

@Override
public Boolean handleLoginPrompt(HttpServletRequest req, HttpServletResponse res, String baseURL) {

    logger.debug("Sending login prompt...");
    if (res.getHeader(WWW_AUTHENTICATE) == null) {
        res.setHeader(WWW_AUTHENTICATE, NEGOTIATE);
    }/*from  w w w.jav  a 2  s.co m*/
    // hack to support fallback to form auth in case the
    // client does not answer the SPNEGO challenge.
    // This will obviously break if form auth is disabled; but this isn't
    // much of an issue since other sso filters will not work nicely after
    // this one (as this one takes over the response and flushes it to start
    // negotiation).
    String refresh = String.format("1;url=/%s/login.jsp", VirtualHostHelper.getWebAppName(req));
    res.setHeader("Refresh", refresh);
    res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    res.setContentLength(0);
    try {
        res.flushBuffer();

    } catch (IOException e) {
        logger.warn("Cannot flush response", e);
    }
    return true;
}

From source file:org.opennms.web.rest.NodeRestServiceTest.java

@Override
protected void createNode() throws Exception {
    String node = "<node type=\"A\" label=\"TestMachine" + m_nodeCounter + "\">"
            + "<labelSource>H</labelSource>" + "<sysContact>The Owner</sysContact>" + "<sysDescription>"
            + "Darwin TestMachine 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun  9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386"
            + "</sysDescription>" + "<sysLocation>DevJam</sysLocation>" + "<sysName>TestMachine" + m_nodeCounter
            + "</sysName>" + "<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" +
            // Add some constant values for these timestamps
            "<createTime>2011-09-24T07:12:46.421-04:00</createTime>"
            + "<lastCapsdPoll>2011-09-24T07:12:46.421-04:00</lastCapsdPoll>" + "</node>";

    HttpServletResponse response = sendPost("/nodes", node, 303, null);

    // Set the asset record's lastModifiedDate to a constant value as well
    String newNodeLocation = response.getHeader("Location");
    String nodeId = newNodeLocation.substring(newNodeLocation.lastIndexOf("/"));
    sendPut("/nodes" + nodeId + "/assetRecord", "lastModifiedDate=2011-09-24T07:12:46.421-04:00", 303, null);
}

From source file:org.opennms.web.rest.v1.NodeRestServiceIT.java

@Override
protected void createNode() throws Exception {
    String node = "<node type=\"A\" label=\"TestMachine" + m_nodeCounter + "\">"
            + "<labelSource>H</labelSource>" + "<sysContact>The Owner</sysContact>" + "<sysDescription>"
            + "Darwin TestMachine 9.4.0 Darwin Kernel Version 9.4.0: Mon Jun  9 19:30:53 PDT 2008; root:xnu-1228.5.20~1/RELEASE_I386 i386"
            + "</sysDescription>" + "<sysLocation>DevJam</sysLocation>" + "<sysName>TestMachine" + m_nodeCounter
            + "</sysName>" + "<sysObjectId>.1.3.6.1.4.1.8072.3.2.255</sysObjectId>" +
            // Add some constant values for these timestamps
            "<createTime>2011-09-24T07:12:46.421-04:00</createTime>"
            + "<lastCapsdPoll>2011-09-24T07:12:46.421-04:00</lastCapsdPoll>" + "</node>";

    HttpServletResponse response = sendPost("/nodes", node, 201, null);

    // Set the asset record's lastModifiedDate to a constant value as well
    String newNodeLocation = response.getHeader("Location");
    String nodeId = newNodeLocation.substring(newNodeLocation.lastIndexOf("/"));
    sendPut("/nodes" + nodeId + "/assetRecord", "lastModifiedDate=2011-09-24T07:12:46.421-04:00", 204);
}