Example usage for javax.servlet.http HttpServletResponse getHeaders

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

Introduction

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

Prototype

public Collection<String> getHeaders(String name);

Source Link

Document

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

Usage

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 ww. ja v a2 s  .c o m*/
 * @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:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * Eventually update response headers for image resources
 * @param target the query target/*from   www. j  a  va  2 s  .co  m*/
 * @param response servlet response to eventually update
 */
private void updateRespHeadersForImages(String target, HttpServletResponse response) {
    if (target.equals("/ViewImage.png") || target.equals("/ViewFavicon.png")) {
        if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) {
            response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work
        }

        // cache-control: allow shared caching (i.e. proxies) and set expires age for cache
        response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(600)); // seconds; ten minutes
    }
}

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

private static String readUserFromCookie(HttpServletResponse response1) {
    String userName = null;/*  w  w w .jav  a  2s. co  m*/
    boolean isCookieSet = response1.containsHeader("Set-Cookie");
    if (isCookieSet) {
        Collection<String> authUserName = response1.getHeaders("Set-Cookie");
        if (authUserName != null) {
            for (String cookie : authUserName) {
                if (!StringUtils.isEmpty(cookie)) {
                    if (cookie.toLowerCase().startsWith(AuthenticatedURL.AUTH_COOKIE.toLowerCase())
                            && cookie.contains("u=")) {
                        String[] split = cookie.split(";");
                        if (split != null) {
                            for (String s : split) {
                                if (!StringUtils.isEmpty(s) && s.toLowerCase()
                                        .startsWith(AuthenticatedURL.AUTH_COOKIE.toLowerCase())) {
                                    int ustr = s.indexOf("u=");
                                    if (ustr != -1) {
                                        int andStr = s.indexOf("&", ustr);
                                        if (andStr != -1) {
                                            try {
                                                userName = s.substring(ustr + 2, andStr);
                                                break;
                                            } catch (Exception e) {
                                                userName = null;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return userName;
}

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

@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String authType = PropertiesUtil.getProperty(RANGER_AUTH_TYPE);
    String userName = null;//from  w  w w.j ava  2s .  com
    boolean checkCookie = response.containsHeader("Set-Cookie");
    if (checkCookie) {
        Collection<String> authUserName = response.getHeaders("Set-Cookie");
        if (authUserName != null) {
            Iterator<String> i = authUserName.iterator();
            while (i.hasNext()) {
                String cookie = i.next();
                if (!StringUtils.isEmpty(cookie)) {
                    if (cookie.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())
                            && cookie.contains("u=")) {
                        String[] split = cookie.split(";");
                        if (split != null) {
                            for (String s : split) {
                                if (!StringUtils.isEmpty(s)
                                        && s.toLowerCase().startsWith(AUTH_COOKIE_NAME.toLowerCase())) {
                                    int ustr = s.indexOf("u=");
                                    if (ustr != -1) {
                                        int andStr = s.indexOf("&", ustr);
                                        if (andStr != -1) {
                                            try {
                                                userName = s.substring(ustr + 2, andStr);
                                            } catch (Exception e) {
                                                userName = null;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    String sessionUserName = request.getParameter(S_USER);
    String pathInfo = request.getPathInfo();
    if (!StringUtils.isEmpty(sessionUserName) && sessionUserName.equalsIgnoreCase("keyadmin")
            && !StringUtils.isEmpty(pathInfo) && pathInfo.contains("public/v2/api/service")) {
        LOG.info("Session will be created by : " + sessionUserName);
        userName = sessionUserName;
    }

    if ((isSpnegoEnable(authType) && (!StringUtils.isEmpty(userName)))) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth == null || !existingAuth.isAuthenticated()) {
            //--------------------------- To Create Ranger Session --------------------------------------
            String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
            //if we get the userName from the token then log into ranger using the same user
            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
            final UserDetails principal = new User(userName, "", grantedAuths);
            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "",
                    grantedAuths);
            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(request);
            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
            Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
            authentication = getGrantedAuthority(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            request.setAttribute("spnegoEnabled", true);
            LOG.info("Logged into Ranger as = " + userName);
            filterChain.doFilter(request, response);
        } else {
            try {
                super.doFilter(filterChain, request, response);
            } catch (Exception e) {
                throw restErrorUtil
                        .createRESTException("RangerKRBAuthenticationFilter Failed : " + e.getMessage());
            }
        }
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:org.kurento.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.debug("  Header {}: {}", headerName, values);
    }//  w  w w  . ja  v a  2s .com
}