Example usage for javax.servlet.http HttpServletRequest getScheme

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

Introduction

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

Prototype

public String getScheme();

Source Link

Document

Returns the name of the scheme used to make this request, for example, <code>http</code>, <code>https</code>, or <code>ftp</code>.

Usage

From source file:be.fedict.eid.idp.sp.protocol.saml2.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}// w ww.j  av a 2  s  . co m
 */
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");

    String idpDestination;
    String relayState;
    KeyStore.PrivateKeyEntry spIdentity = null;
    String language;

    AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
    if (null != service) {
        idpDestination = service.getIdPDestination();
        relayState = service.getRelayState(request.getParameterMap());
        spIdentity = service.getSPIdentity();
        language = service.getLanguage();
    } else {
        idpDestination = this.idpDestination;
        relayState = null;
        language = this.language;
    }

    // sp-destination
    String spDestination = null;
    if (null != service) {
        spDestination = service.getSPDestination();
    }
    if (null == spDestination) {
        // not provided by the service, check web.xml...
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
    }

    // issuer
    String issuer = null;
    if (null != service) {
        issuer = service.getIssuer();
    }
    if (null == issuer) {
        issuer = spDestination;
    }

    // generate and send an authentication request
    AuthnRequest authnRequest = AuthenticationRequestUtil.sendRequest(issuer, idpDestination, spDestination,
            relayState, spIdentity, response, language);

    // save state on session
    setRequestIssuer(authnRequest.getIssuer().getValue(), request.getSession());
    setRequestId(authnRequest.getID(), request.getSession());
    setRecipient(authnRequest.getAssertionConsumerServiceURL(), request.getSession());
    setRelayState(relayState, request.getSession());
}

From source file:de.appsolve.padelcampus.filter.LoginFilter.java

/**
 * @param request/*from w  ww .jav a 2s.  c  om*/
 * @param response
 * @param chain
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();
        for (Pattern pattern : NO_FILTER_LIST) {
            if (pattern.matcher(requestURI).matches()) {
                sessionUtil.setCustomer(httpRequest, null);
                chain.doFilter(request, response);
                return;
            }
        }

        CustomerI customer = sessionUtil.getCustomer(httpRequest);
        if (customer == null) {
            String hostHeader = httpRequest.getHeader("host");
            if (!StringUtils.isEmpty(hostHeader)) {
                String[] hostHeaderSplit = hostHeader.split(":");
                customer = customerDAO.findByDomainName(hostHeaderSplit[0]);
            }
            if (customer == null) {
                String url = "";
                String serverName = httpRequest.getServerName();
                if (!StringUtils.isEmpty(serverName)) {
                    String[] domainParts = serverName.split("\\.");
                    if (domainParts.length > 2) {
                        url = httpRequest.getScheme() + "://" + domainParts[domainParts.length - 2] + "."
                                + domainParts[domainParts.length - 1];
                        if (httpRequest.getScheme().equals("http") && httpRequest.getServerPort() != 80) {
                            url += ":" + httpRequest.getServerPort();
                        }
                    }
                }
                url += PATH_START_PAGE;
                httpResponse.setStatus(HttpStatus.PERMANENT_REDIRECT.value());
                httpResponse.sendRedirect(url);
                return;
            }
            sessionUtil.setCustomer(httpRequest, customer);
        }

        //login user in case of valid login cookie
        Player user = sessionUtil.getUser(httpRequest);
        if (user == null) {
            Cookie[] cookies = httpRequest.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName() != null && cookie.getName().equals(COOKIE_LOGIN_TOKEN)) {
                        String cookieValue = cookie.getValue();
                        if (StringUtils.isEmpty(cookieValue)) {
                            loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                        } else {
                            String[] cookieValueSplit = cookieValue.split(":");
                            if (cookieValueSplit.length != 2) {
                                loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                            } else {
                                String uuid = cookieValueSplit[0];
                                String loginCookieRandomValue = cookieValueSplit[1];
                                LoginCookie loginCookie = loginUtil.isValidLoginCookie(uuid,
                                        loginCookieRandomValue);
                                if (loginCookie == null) {
                                    loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                } else {
                                    Player player = playerDAO.findByUUID(loginCookie.getPlayerUUID());
                                    if (player == null) {
                                        loginUtil.deleteLoginCookie(httpRequest, httpResponse);
                                    } else {
                                        //log user in
                                        sessionUtil.setUser(httpRequest, player);

                                        //update loginCookieHash
                                        loginUtil.updateLoginCookie(httpRequest, httpResponse);
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }

        moduleUtil.initModules(httpRequest);
    }
    chain.doFilter(request, response);
}

From source file:org.apache.axis2.transport.http.ListingAgent.java

public void processListService(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {

    String url;/*w w  w . ja v  a 2  s  .  co m*/
    try {
        url = req.getRequestURL().toString();
    } catch (Throwable t) {
        log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t);
        url = req.getRequestURI();
    }
    String serviceName = extractServiceName(url);
    HashMap services = configContext.getAxisConfiguration().getServices();
    String query = req.getQueryString();
    int wsdl2 = query.indexOf("wsdl2");
    int wsdl = query.indexOf("wsdl");
    int xsd = query.indexOf("xsd");
    int policy = query.indexOf("policy");

    if ((services != null) && !services.isEmpty()) {
        Object serviceObj = services.get(serviceName);
        if (serviceObj != null) {
            boolean isHttp = "http".equals(req.getScheme());
            if (wsdl2 >= 0) {
                res.setContentType("text/xml");
                String ip = extractHostAndPort(url, isHttp);
                String wsdlName = req.getParameter("wsdl2");
                if (wsdlName != null && wsdlName.length() > 0) {
                    InputStream in = ((AxisService) serviceObj).getClassLoader()
                            .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName);
                    if (in != null) {
                        OutputStream out = res.getOutputStream();
                        out.write(IOUtils.getStreamAsByteArray(in));
                        out.flush();
                        out.close();
                    } else {
                        res.sendError(HttpServletResponse.SC_NOT_FOUND);
                    }
                } else {
                    OutputStream out = res.getOutputStream();
                    ((AxisService) serviceObj).printWSDL2(out, ip);
                    out.flush();
                    out.close();
                }
                return;
            } else if (wsdl >= 0) {
                OutputStream out = res.getOutputStream();
                res.setContentType("text/xml");
                String ip = extractHostAndPort(url, isHttp);
                String wsdlName = req.getParameter("wsdl");

                if (wsdlName != null && wsdlName.length() > 0) {
                    AxisService axisServce = (AxisService) serviceObj;
                    axisServce.printUserWSDL(out, wsdlName);
                    out.flush();
                    out.close();
                } else {
                    ((AxisService) serviceObj).printWSDL(out, ip);
                    out.flush();
                    out.close();
                }
                return;
            } else if (xsd >= 0) {
                res.setContentType("text/xml");
                int ret = ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd"));
                if (ret == 0) {
                    //multiple schemas are present and the user specified
                    //no name - in this case we cannot possibly pump a schema
                    //so redirect to the service root
                    res.sendRedirect("");
                } else if (ret == -1) {
                    res.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                return;
            } else if (policy >= 0) {

                ExternalPolicySerializer serializer = new ExternalPolicySerializer();
                serializer
                        .setAssertionsToFilter(configContext.getAxisConfiguration().getLocalPolicyAssertions());

                // check whether Id is set
                String idParam = req.getParameter("id");

                if (idParam != null) {
                    // Id is set

                    Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj);

                    if (targetPolicy != null) {
                        XMLStreamWriter writer;

                        try {
                            OutputStream out = res.getOutputStream();
                            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                            res.setContentType("application/wspolicy+xml");
                            targetPolicy.serialize(writer);
                            writer.flush();

                        } catch (XMLStreamException e) {
                            throw new ServletException("Error occured when serializing the Policy", e);

                        } catch (FactoryConfigurationError e) {
                            throw new ServletException("Error occured when serializing the Policy", e);
                        }

                    } else {

                        OutputStream out = res.getOutputStream();
                        res.setContentType("text/html");
                        String outStr = "<b>No policy found for id=" + idParam + "</b>";
                        out.write(outStr.getBytes());
                    }

                } else {

                    PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude();
                    Policy effecPolicy = policyInclude.getEffectivePolicy();

                    if (effecPolicy != null) {
                        XMLStreamWriter writer;

                        try {
                            OutputStream out = res.getOutputStream();
                            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                            res.setContentType("application/wspolicy+xml");
                            effecPolicy.serialize(writer);
                            writer.flush();

                        } catch (XMLStreamException e) {
                            throw new ServletException("Error occured when serializing the Policy", e);

                        } catch (FactoryConfigurationError e) {
                            throw new ServletException("Error occured when serializing the Policy", e);
                        }
                    } else {

                        OutputStream out = res.getOutputStream();
                        res.setContentType("text/html");
                        String outStr = "<b>No effective policy for " + serviceName + " servcie</b>";
                        out.write(outStr.getBytes());
                    }
                }

                return;
            } else {
                try {
                    req.getSession().setAttribute(Constants.SINGLE_SERVICE, serviceObj);
                } catch (Throwable t) {
                    log.info("Old Servlet API :" + t);
                }
            }
        } else {
            try {
                req.getSession().setAttribute(Constants.SINGLE_SERVICE, null);
            } catch (Throwable t) {
                log.info("Old Servlet API :" + t);
            }

            res.sendError(HttpServletResponse.SC_NOT_FOUND, url);
        }
    }

    renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res);
}

From source file:org.commoncrawl.service.listcrawler.ProxyServlet2.java

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if ("CONNECT".equalsIgnoreCase(request.getMethod())) {
        handleConnect(request, response);
    } else {//from  w  w w . j  av  a2 s . c  o m
        final RequestDetails details = new RequestDetails();

        String uri = request.getRequestURI();

        if (request.getQueryString() != null)
            uri += "?" + request.getQueryString();
        final URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), uri);

        if (request.getServerName().equals("proxy")) {
            serviceProxyInternalRequest(req, res);
            return;
        }

        // context.log("URL="+url);
        details.url = url;

        // attempt cache load first ... 
        CacheLoadRequest cacheLoad = new CacheLoadRequest(url);
        details.log.add("Executing Disk Load Request");
        DiskCacheItem cacheItem = cacheLoad.executeRequest();
        details.log.add("Disk Load Request Returned:" + cacheItem);

        // create metadata placeholder
        CrawlURLMetadata metadata = new CrawlURLMetadata();
        NIOHttpHeaders headers = null;

        boolean revalidate = false;
        boolean cacheItemValid = true;

        if (cacheItem != null) {
            // get headers 
            headers = buildHeaderFromHeaderItems(cacheItem.getHeaderItems());
            // set last fetch time in metadata 
            metadata.setLastFetchTimestamp(cacheItem.getFetchTime());
            // parse headers 
            HttpHeaderInfoExtractor.parseHeaders(headers, metadata);
            // ok now validate cache 
            if (HttpCacheUtils.requiresValidation(metadata)) {
                details.log.add("CACHE Item Present But Needs Revalidation");
                revalidate = true;
            }
        }

        // if no cache item or we to revalidate cache item .. 
        if (cacheItem == null || revalidate) {

            NIOHttpConnection connection = new NIOHttpConnection(url,
                    ProxyServer.getSingleton().getEventLoop().getSelector(),
                    ProxyServer.getSingleton().getEventLoop().getResolver(), _cookieStore);

            NIOConnectionWrapper wrapper = new NIOConnectionWrapper(connection);

            // URLConnection connection = url.openConnection();
            // connection.setAllowUserInteraction(false);

            // Set method
            /*
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection)connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }
             */
            connection.setMethod(request.getMethod());

            // check connection header
            String connectionHdr = request.getHeader("Connection");
            if (connectionHdr != null) {
                connectionHdr = connectionHdr.toLowerCase();
                if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
                    connectionHdr = null;
            }

            // copy headers
            boolean xForwardedFor = false;
            boolean hasContent = false;
            Enumeration enm = request.getHeaderNames();
            while (enm.hasMoreElements()) {
                // TODO could be better than this!
                String hdr = (String) enm.nextElement();
                String lhdr = hdr.toLowerCase();

                if (_DontProxyHeaders.contains(lhdr) || lhdr.equals("cookie"))
                    continue;
                if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
                    continue;

                if ("content-type".equals(lhdr))
                    hasContent = true;

                Enumeration vals = request.getHeaders(hdr);
                while (vals.hasMoreElements()) {
                    String val = (String) vals.nextElement();
                    if (val != null) {
                        connection.getRequestHeaders().set(hdr, val);
                        // connection.addRequestProperty(hdr,val);
                        details.log.add("req header: " + hdr + ": " + val);
                        xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
                    }
                }
            }

            String cookies = _cookieStore.GetCookies(url);
            if (cookies.length() != 0) {
                details.log.add("req injected-header: Cookie:" + cookies);
                connection.getRequestHeaders().set("Cookie", cookies);
            }

            // Proxy headers
            connection.getRequestHeaders().set("Via", "1.1 (jetty)");
            // cache headers (if required) 
            if (metadata.isFieldDirty(CrawlURLMetadata.Field_LASTMODIFIEDTIME)) {
                details.log.add("Sending If-Modified-Since");
                connection.getRequestHeaders().set("If-Modified-Since", headers.findValue("Last-Modified"));
            }
            if (metadata.isFieldDirty(CrawlURLMetadata.Field_ETAG)) {
                details.log.add("Sending If-None-Match");
                connection.getRequestHeaders().set("If-None-Match", metadata.getETag());
            }
            if (!xForwardedFor)
                connection.getRequestHeaders().set("X-Forwarded-For", request.getRemoteAddr());
            //connection.addRequestProperty("X-Forwarded-For",request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getHeader("Cache-Control");
            /*
            if (cache_control!=null &&
                (cache_control.indexOf("no-cache")>=0 ||
                 cache_control.indexOf("no-store")>=0))
                connection.setUseCaches(false);
            */

            // customize Connection

            try {
                // connection.setDoInput(true);

                // do input thang!
                InputStream in = request.getInputStream();
                if (hasContent) {
                    //connection.setDoOutput(true);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    IO.copy(in, stream);
                    wrapper.setUploadBuffer(stream.toByteArray());
                }

                // Connect
                connection.open();
            } catch (Exception e) {
                details.log.add(CCStringUtils.stringifyException(e));
            }

            boolean connectionSucceeded = wrapper.waitForCompletion();

            InputStream proxy_in = null;

            // handler status codes etc.
            int code = 500;

            if (connectionSucceeded) {

                // set last fetch time in metadata 
                metadata.setLastFetchTimestamp(System.currentTimeMillis());

                code = connection.getResponseHeaders().getHttpResponseCode();

                if (revalidate && code != 304) {
                    details.log.add("Item ReValidate FAILED");
                    cacheItemValid = false;
                }

                if (code != 304) {

                    HttpHeaderInfoExtractor.parseHeaders(connection.getResponseHeaders(), metadata);

                    response.setStatus(code, "");
                    details.log.add("response code:" + code);

                    // clear response defaults.
                    response.setHeader("Date", null);
                    response.setHeader("Server", null);

                    // set response headers
                    int h = 0;
                    String hdr = connection.getResponseHeaders().getKey(h);
                    String val = connection.getResponseHeaders().getValue(h);
                    while (hdr != null || val != null) {
                        String lhdr = hdr != null ? hdr.toLowerCase() : null;
                        if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr))
                            response.addHeader(hdr, val);

                        details.log.add("response header:" + hdr + ": " + val);

                        h++;
                        hdr = connection.getResponseHeaders().getKey(h);
                        val = connection.getResponseHeaders().getValue(h);
                    }
                    response.addHeader("Via", "1.1 (jetty)");
                    response.addHeader("cache-control", "no-cache,no-store");
                    response.addHeader("Connection", "close");

                    // IF RESULT IS CACHEABLE ...
                    LifeTimeInfo lifeTimeInfo = HttpCacheUtils.getFreshnessLifetimeInMilliseconds(metadata);
                    details.log.add("getFreshnessLifetime returned:" + lifeTimeInfo._lifetime);
                    details.log.add("getFreshnessLifetime source:" + lifeTimeInfo._source);

                    if (lifeTimeInfo._lifetime != 0) {

                        details.log.add("item is cachable - issuing cache request");
                        // construct a disk cache item ... 
                        final DiskCacheItem cacheItemForWrite = new DiskCacheItem();
                        // populate 
                        cacheItemForWrite.setFetchTime(System.currentTimeMillis());
                        cacheItemForWrite.setResponseCode(code);
                        // headers .. 
                        h = 0;
                        hdr = connection.getResponseHeaders().getKey(h);
                        val = connection.getResponseHeaders().getValue(h);
                        while (hdr != null || val != null) {
                            String lhdr = hdr != null ? hdr.toLowerCase() : null;
                            if (hdr != null && val != null) {
                                if (!hdr.toLowerCase().equals("set-cookie")) {
                                    ArcFileHeaderItem item = new ArcFileHeaderItem();
                                    item.setItemKey(hdr);
                                    item.setItemValue(val);
                                    cacheItemForWrite.getHeaderItems().add(item);
                                }
                            }
                            h++;
                            hdr = connection.getResponseHeaders().getKey(h);
                            val = connection.getResponseHeaders().getValue(h);
                        }

                        if (connection.getContentBuffer().available() != 0) {
                            // copy result to byte array
                            //VERY INEFFICIENT ... BUT ONLY FOR TESTING ... 
                            ByteArrayOutputStream tempStream = new ByteArrayOutputStream();
                            IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()), tempStream);
                            // get the underlying buffer 
                            byte[] responseBuffer = tempStream.toByteArray();
                            // set it into the cache item ... 
                            cacheItemForWrite.setContent(new Buffer(responseBuffer));
                            // and now write out buffer 
                            IO.copy(new ByteArrayInputStream(responseBuffer), response.getOutputStream());
                        }

                        // ok schedule a disk cache write ... 
                        _threadPool.execute(new Runnable() {

                            @Override
                            public void run() {
                                LOG.info("Writing Cache Item for URL:" + url);
                                File cacheFileName;
                                try {
                                    cacheFileName = cachePathFromURL(url);

                                    try {
                                        FileOutputStream fileStream = new FileOutputStream(cacheFileName);
                                        try {
                                            DataOutputStream dataOutputStream = new DataOutputStream(
                                                    fileStream);
                                            cacheItemForWrite.serialize(dataOutputStream, new BinaryProtocol());
                                        } finally {
                                            fileStream.close();
                                        }
                                    } catch (IOException e) {
                                        LOG.error(CCStringUtils.stringifyException(e));
                                    }

                                } catch (MalformedURLException e) {
                                    LOG.error(CCStringUtils.stringifyException(e));
                                }

                            }

                        });
                    } else {
                        details.log.add("FRESHNESS LIFETIME == 0 - SKIPPING CACHE!");
                        // no cache direct copy case 
                        if (connection.getContentBuffer().available() != 0) {
                            IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()),
                                    response.getOutputStream());
                        }
                    }
                }
            } else {
                response.setStatus(500, "Proxy Request Failed");
                details.log.add("Proxy Request Failed");
            }
        }
        // ok now, if cache item != null and cache-item is still valid 
        if (cacheItem != null && cacheItemValid) {
            // service request from cache
            details.log.add("Servicing Request From Disk Cache");

            // clear response defaults.
            response.setHeader("Date", null);
            response.setHeader("Server", null);

            // set response code 
            response.setStatus(cacheItem.getResponseCode());

            // set response headers
            for (ArcFileHeaderItem headerItem : cacheItem.getHeaderItems()) {
                String key = headerItem.getItemKey().toLowerCase();
                // if not in don't proxy headers ... 
                if (key.length() != 0) {
                    if (!_DontProxyHeaders.contains(key) && !key.equals("set-cookie")) {
                        response.addHeader(headerItem.getItemKey(), headerItem.getItemValue());
                        details.log.add("cache response: " + headerItem.getItemKey() + ": "
                                + headerItem.getItemValue());
                    } else {
                        details.log.add("cache hidden-hdr: " + headerItem.getItemKey() + ": "
                                + headerItem.getItemValue());
                    }
                }
            }

            response.addHeader("Via", "1.1 (jetty)");
            response.addHeader("cache-control", "no-cache,no-store");
            response.addHeader("Connection", "close");

            if (cacheItem.getContent().getCount() != 0) {
                response.setHeader("Content-Length", null);
                response.addHeader("Content-Length", Integer.toString(cacheItem.getContent().getCount()));
                IO.copy(new ByteArrayInputStream(cacheItem.getContent().getReadOnlyBytes()),
                        response.getOutputStream());
            }
        }

        LOG.info(details.toString());
    }
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = rqst.getAttributeNames();
        for (; e.hasMoreElements();) {
            String attribute = e.nextElement();
            b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
        }/* ww  w .j  a  v  a2s .c o  m*/

        X509Certificate[] userCerts = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");
        if (userCerts != null)
            for (X509Certificate cert : userCerts)
                b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

        b.append("\n The Scheme is " + rqst.getScheme());
        b.append("\n The Auth Type is " + rqst.getAuthType());
        b.append("\n The Path Info is " + rqst.getPathInfo());
        b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
        b.append("\n The Context Path is " + rqst.getContextPath());
        b.append("\n The Query String is " + rqst.getQueryString());
        b.append("\n The Remote User is " + rqst.getRemoteUser());
        b.append("\n The User Principal is " + rqst.getUserPrincipal());
        b.append("\n The Request URI is " + rqst.getRequestURI());
        b.append("\n The Request URL is " + rqst.getRequestURL());
        b.append("\n The Servlet Path is " + rqst.getServletPath());

        LOG.debug(b.toString());
    }

    boolean unitTest = false;
    if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null)
        unitTest = true;

    if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) {
        boolean isAuthorized = false;
        X509Certificate[] certs = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");

        if (unitTest) {
            try {
                LOG.debug("==> Entering https unit test");
                String SslPath = rqst.getParameter("SslPath");
                InputStream inStream = new FileInputStream(SslPath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                certs = new X509Certificate[] { cert };
            } catch (Exception e) {
                // do nothing here
            }
        }

        if (certs == null || certs.length == 0) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
            LOG.info("No Client SSL certificate received");
            return;
        }
        for (X509Certificate cert : certs) {
            try {
                cert.checkValidity();
            } catch (CertificateExpiredException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
                return;
            } catch (CertificateNotYetValidException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
                return;
            }
        }

        String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
        String userID = null;
        for (String s : tokens) {
            if (s.startsWith("CN=")) {
                userID = s;
                break;
            }
        }
        if (userID == null || userID.length() < 4) {
            LOG.info("Can't retrieve user ID from SSL certificate");
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
            return;
        }
        userID = userID.substring(3);

        String servletPath = rqst.getServletPath();
        if (unitTest) {
            servletPath = rqst.getParameter("TestSevletPathInfo");
            LOG.info("this is for unit test purpose only");
        }

        if (HFTP_PATTERN.matcher(servletPath).matches()) {
            // request is an HSFTP request
            if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
                // file path as part of the URL
                isAuthorized = checkPath(userID, certs[0],
                        rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
            } else {
                // file path is stored in "filename" parameter
                isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
            }
        } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
            Configuration conf = new Configuration(false);
            conf.addResource("hdfsproxy-default.xml");
            Map<String, Set<Path>> permsMap = getPermMap(conf);
            Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
            if (permsMap == null || certsMap == null) {
                LOG.warn("Permission files reloading failed");
                rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Permission files reloading failed");
                return;
            }
            ProxyFilter.permsMap = permsMap;
            ProxyFilter.certsMap = certsMap;
            LOG.info("User permissions and user certs files reloaded");
            rsp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (!isAuthorized) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
            return;
        }

        // request is authorized, set ugi for servlets
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID);
        rqst.setAttribute("authorized.ugi", ugi);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID);
    } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes
        String ugi = rqst.getParameter("ugi");
        if (ugi != null) {
            rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi));
            rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

@SuppressWarnings("deprecation")
private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    try {//from  w  w w. j a  v  a2  s .  c om
        this.targetUri = new URI(remoteUrl);
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //Need to handle https, but think about "restricted" layers for now.  Some institutions don't really have good protection for restricted layers.  Does this open up potential for security
    //problems for those folks?
    if (servletRequest.getScheme().equals("https")) {
        //actually, what matters the most is if the remote url is https
    }

    BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest(
            servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest));

    //HttpGet httpget = new HttpGet(rewriteUrlFromRequest(servletRequest));
    copyRequestHeaders(servletRequest, proxyRequest);

    // Add the input entity (streamed) then execute the request.
    HttpResponse proxyResponse = null;
    InputStream servletRequestInputStream = servletRequest.getInputStream();
    CloseableHttpClient proxyClient = ogpHttpClient.getCloseableHttpClient();

    try {
        try {
            //proxyRequest.setEntity(new InputStreamEntity(servletRequestInputStream));
            proxyRequest.setEntity(
                    new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength()));

            // Execute the request
            logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI()
                    + " -- " + proxyRequest.getRequestLine().getUri());

            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest);
        } finally {
            IOUtils.closeQuietly(servletRequestInputStream);
        }

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();
        logger.info("Status from remote server: " + Integer.toString(statusCode));
        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            EntityUtils.consume(proxyResponse.getEntity());
            return;
        }

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

        copyResponseHeaders(proxyResponse, servletResponse);

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

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        throw new RuntimeException(e);
    }
}

From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java

public String getXMLDependencyGraphURL(HttpServletRequest request, String unitName, String unitVersion,
        String selectedEnv, String containerGraphList) throws Exception {
    String file = request.getRequestURI();
    file = file.substring(0, file.indexOf("/", file.indexOf("/") + 1));

    if (request.getQueryString() != null) {
        // file += '?' +
        // request.getQueryString()+"&_eventId_getXMLGraph=true&name="+
        // unitName+"&version="+unitVersion+"&environment="+selectedEnv;
        file += "/unitInverseDependencies.htm" + '?' + "name=" + unitName + "&version=" + unitVersion
                + "&environment=" + selectedEnv.replace(' ', '+') + "&justGraph=true" + "&containerGraphList="
                + containerGraphList;/*from   w  ww.j ava2s .c o  m*/
    }
    URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file);
    return (reconstructedURL.toString()).substring(request.getScheme().length(),
            (reconstructedURL.toString().length()));
}

From source file:org.hoteia.qalingo.core.service.AbstractUrlService.java

public String buildDomainePathUrl(final RequestData requestData) throws Exception {
    final HttpServletRequest request = requestData.getRequest();
    final MarketPlace marketPlace = requestData.getMarketPlace();
    final Market market = requestData.getMarket();
    final MarketArea marketArea = requestData.getMarketArea();
    final String contextNameValue = requestData.getContextNameValue();

    // CHOSE DOMAIN PATH FROM MARKET PLACE AND MARKET AND MARKET AREA
    String domainePathUrl = "";
    if (marketPlace != null) {
        String domainName = marketPlace.getDomainName(contextNameValue);
        if (StringUtils.isNotEmpty(domainName)) {
            domainePathUrl = domainName;
        }/*from  w ww .jav  a  2s . co  m*/
    }
    if (market != null) {
        String domainName = market.getDomainName(contextNameValue);
        if (StringUtils.isNotEmpty(domainName)) {
            domainePathUrl = domainName;
        }
    }
    if (marketArea != null) {
        String domainName = marketArea.getDomainName(contextNameValue);
        if (StringUtils.isNotEmpty(domainName)) {
            domainePathUrl = domainName;
        }
    }
    if (request != null && StringUtils.isEmpty(domainePathUrl)) {
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.replace(request.getScheme() + "://", "");
        String[] urlBlock = requestUrl.split("/");
        domainePathUrl = urlBlock[0];
    }
    if (request != null && !domainePathUrl.startsWith(request.getScheme())) {
        domainePathUrl = request.getScheme() + "://" + domainePathUrl;
    }
    if (!domainePathUrl.contains("http")) {
        // Default value
        domainePathUrl = "http://" + domainePathUrl;
    }
    return domainePathUrl;
}

From source file:com.viewer.controller.ViewerController.java

@RequestMapping(value = "/GetImageUrls", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody/*from   www. j a  v a  2 s  .com*/

public GetImageUrlsResponse GetImageUrls(@RequestBody GetImageUrlsParameters parameters,
        HttpServletRequest request) throws Exception {

    try {

        if (com.viewer.model.helper.DotNetToJavaStringHelper.isNullOrEmpty(parameters.getPath())) {
            GetImageUrlsResponse empty = new GetImageUrlsResponse();
            empty.imageUrls = new String[0];
            return empty;
        }

        DocumentInfoOptions documentInfoOptions = new DocumentInfoOptions(parameters.getPath());
        DocumentInfoContainer documentInfoContainer = _imageHandler.getDocumentInfo(documentInfoOptions);

        int[] pageNumbers = new int[documentInfoContainer.getPages().size()];
        int count = 0;
        for (PageData page : documentInfoContainer.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }

        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, parameters);

        GetImageUrlsResponse result = new GetImageUrlsResponse();
        result.imageUrls = imageUrls;
        return result;

    } catch (Exception e) {
        e.printStackTrace();
    }
    GetImageUrlsResponse test = null;
    return test;
}

From source file:grails.plugin.springsecurity.web.access.AjaxAwareAccessDeniedHandler.java

public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Spring Security won't save the original request
        requestCache.saveRequest(request, response);
    }/*from   w w  w.  j  a v a 2 s  . co  m*/

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    if (useForward && (errorPage != null || ajaxError)) {
        // Put exception into request scope (perhaps of use to a view)
        request.setAttribute(WebAttributes.ACCESS_DENIED_403, e);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.getRequestDispatcher(ajaxError ? ajaxErrorPage : errorPage).forward(request, response);
        return;
    }

    String redirectUrl;
    String serverURL = ReflectionUtils.getGrailsServerURL();
    if (serverURL == null) {
        boolean includePort = true;
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = portResolver.getServerPort(request);
        String contextPath = request.getContextPath();
        boolean inHttp = "http".equals(scheme.toLowerCase());
        boolean inHttps = "https".equals(scheme.toLowerCase());

        if (inHttp && (serverPort == 80)) {
            includePort = false;
        } else if (inHttps && (serverPort == 443)) {
            includePort = false;
        }
        redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    } else {
        redirectUrl = serverURL;
    }

    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}