Example usage for javax.servlet.http HttpServletRequest getServerPort

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

Introduction

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

Prototype

public int getServerPort();

Source Link

Document

Returns the port number to which the request was sent.

Usage

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser,
        ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpEmailFrom");
    }//from w  w w .ja  v  a2s  .c  o  m

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAsterisk24SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n"
            + "</BODY>\n" + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.google.acre.servlet.ProxyPassServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse An object by which we can send the proxied
 *                             response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *//* w  w w  . j av a2 s.  c o m*/
private void executeProxyRequest(HttpRequestBase httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
    int proxy_port = -1;
    if (!(proxy_host.length() == 0)) {
        proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
        HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
        client.getParams().setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
    }

    // Execute the request
    HttpResponse res = client.execute(httpMethodProxyRequest);
    int rescode = res.getStatusLine().getStatusCode();

    // Pass response headers back to the client
    Header[] headerArrayResponse = res.getAllHeaders();
    for (Header header : headerArrayResponse) {
        httpServletResponse.addHeader(header.getName(), header.getValue());
    }

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (rescode >= 300 && rescode < 304) {
        String stringStatusCode = Integer.toString(rescode);
        String stringLocation = httpMethodProxyRequest.getFirstHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(
                stringLocation.replace(this.metawebAPIHostAndPort + this.metawebAPIPath, stringMyHostName));
        return;
    } else if (rescode == 304) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(304);
        return;
    }

    httpServletResponse.setStatus(rescode);

    InputStream instream = new BufferedInputStream(res.getEntity().getContent());
    OutputStream outstream = httpServletResponse.getOutputStream();
    IOUtils.copy(instream, outstream);
    instream.close();
}

From source file:com.provenance.cloudprovenance.traceabilitystore.ws.controler.TraceabilityStoreController.java

@Override
@POST/* w  ww  .  jav  a 2 s  .com*/
@Path(value = "/{serviceId}/{traceabilityType}")
public Response createTraceabilityDocument(@PathParam("serviceId") String serviceId,
        @PathParam("traceabilityType") String traceabilityType, @Context HttpServletRequest request) {

    boolean response = false;
    String bodyText = null;

    // Read the http message body contents
    try {
        bodyText = getBody(request);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Check if the current traceability record Id exists
    if (currentTraceabilityRecordId == null) {
        currentTraceabilityRecordId = "TraceabilityRecord-" + (System.currentTimeMillis());
        String currentTraceabilityRecordIdFileName = constructTraceabilityFileName(currentTraceabilityRecordId);

        // create a blank document first
        response = traceabilityStoreService.createTraceabilityInstance(serviceId, traceabilityType,
                currentTraceabilityRecordIdFileName);
    }

    if (bodyText == null || bodyText.equals("")) {
        // add template content
        String tempelateProvText = this.getTemplateProvFile();
        logger.info("Creating traceability record with template content ");
        response = traceabilityStoreService.createTraceabilityEntry(serviceId, traceabilityType,
                constructTraceabilityFileName(currentTraceabilityRecordId), "", tempelateProvText);
        logger.info("Traceability record created successfully");
    } else {

        // add sent traceability data
        logger.info("Creating traceability record with the content from the request: \n" + bodyText);
        response = traceabilityStoreService.createTraceabilityEntry(serviceId, traceabilityType,
                constructTraceabilityFileName(currentTraceabilityRecordId), "", bodyText);

        logger.info("traceability record created successfully");
    }

    String responseUri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI() + "/" + currentTraceabilityRecordId;

    String responseContent = trResponse.genTraceabilityRecordIdResponse(currentTraceabilityRecordId, serviceId,
            defaultFileExtensionOfrecord, responseUri);

    logger.info("response content: " + responseUri);

    if (response == true) {
        ResponseBuilder rBuilder = Response.status(201);
        rBuilder.entity(responseContent);
        return rBuilder.build();
    } else {
        ResponseBuilder rBuilder = Response.status(400);
        return rBuilder.build();

    }
}

From source file:org.bimserver.servlets.RootServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w  ww .  j  a  va  2s.  c o m
        String requestOrigin = request.getHeader("Origin");
        if (requestOrigin != null && !bimServer.getServerSettingsCache().isHostAllowed(requestOrigin)) {
            response.setStatus(403);
            return;
        }
        if (requestOrigin != null) {
            response.setHeader("Access-Control-Allow-Origin", requestOrigin);
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return;
        }

        String requestUri = request.getRequestURI();
        String servletContextPath = getServletContext().getContextPath();
        if (requestUri.startsWith(servletContextPath)) {
            requestUri = requestUri.substring(servletContextPath.length());
        }
        if (requestUri == null) {
            LOGGER.error("RequestURI is null");
        } else {
            LOGGER.debug(requestUri);
            //            LOGGER.info(requestUri);
        }
        setContentType(response, requestUri);
        if (request.getRequestURI().endsWith(".getbimserveraddress")) {
            response.setContentType("application/json; charset=utf-8");
            String siteAddress = bimServer.getServerSettingsCache().getServerSettings().getSiteAddress();
            if (siteAddress == null || siteAddress.trim().isEmpty()) {
                // Only when in setup-mode
                String forwardedProtocol = request.getHeader("X-Forwarded-Proto");
                if (forwardedProtocol != null) {
                    LOGGER.info("X-Forwarded-Proto " + forwardedProtocol);
                    String port = "" + request.getServerPort();
                    if (request.getHeader("X-Forwarded-Port") != null) {
                        port = request.getHeader("X-Forwarded-Port");
                    }
                    siteAddress = forwardedProtocol + "://" + request.getServerName() + ":" + port
                            + request.getContextPath();
                } else {
                    siteAddress = request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + request.getContextPath();
                }
            }
            response.getWriter().print("{\"address\":\"" + siteAddress + "\"}");
            return;
        } else if (requestUri.startsWith("/stream")) {
            LOGGER.warn("Stream request should not be going to this servlet!");
        } else if (requestUri.startsWith("/soap11/") || requestUri.equals("/soap11")) {
            soap11Servlet.service(request, response);
        } else if (requestUri.startsWith("/soap12/") || requestUri.equals("/soap12")) {
            try {
                soap12Servlet.service(request, response);
            } catch (ClassCastException e) {
                LOGGER.debug("", e);
            }
        } else if (requestUri.startsWith("/syndication/") || requestUri.equals("/syndication")) {
            syndicationServlet.service(request, response);
        } else if (requestUri.startsWith("/json/") || requestUri.equals("/json")) {
            jsonApiServlet.service(request, response);
        } else if (requestUri.startsWith("/oauth/register")) {
            oAuthRegistrationServlet.service(request, response);
        } else if (requestUri.startsWith("/oauth")) {
            oAuthAuthorizationServlet.service(request, response);
        } else if (requestUri.startsWith("/upload/") || requestUri.equals("/upload")) {
            uploadServlet.service(request, response);
        } else if (requestUri.startsWith("/bulkupload/") || requestUri.equals("/bulkupload")) {
            bulkUploadServlet.service(request, response);
        } else if (requestUri.startsWith("/download/") || requestUri.equals("/download")) {
            downloadServlet.service(request, response);
        } else {
            if (requestUri == null || requestUri.equals("") || requestUri.equals("/")) {
                requestUri = "/index.html";
            }
            String modulePath = requestUri;
            if (modulePath.startsWith("/apps/")) {
                modulePath = modulePath.substring(6);
                if (modulePath.indexOf("/", 1) != -1) {
                    modulePath = modulePath.substring(0, modulePath.indexOf("/", 1));
                }
                if (modulePath.startsWith("/")) {
                    modulePath = modulePath.substring(1);
                }
                if (bimServer.getWebModules().containsKey(modulePath)) {
                    String substring = requestUri.substring(6 + modulePath.length());
                    WebModulePlugin webModulePlugin = bimServer.getWebModules().get(modulePath);
                    if (webModulePlugin == null) {
                        response.setStatus(404);
                        response.getWriter().println("No webmodule " + modulePath + " found");
                        return;
                    } else {
                        if (webModulePlugin.service(substring, response)) {
                            return;
                        }
                    }
                }
            }

            if (bimServer.getDefaultWebModule() != null) {
                if (bimServer.getDefaultWebModule().service(requestUri, response)) {
                    return;
                }
            }

            InputStream resourceAsStream = getServletContext().getResourceAsStream(requestUri);
            if (resourceAsStream != null) {
                IOUtils.copy(resourceAsStream, response.getOutputStream());
            } else {
                response.setStatus(404);
                try {
                    response.getWriter().println("404 - Not Found");
                } catch (IllegalStateException e) {
                }
            }
        }
    } catch (Throwable e) {
        if (e instanceof IOException) {
            // Ignore
        } else {
            LOGGER.error("", e);
        }
    }
}

From source file:com.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form./* w w  w.  j  a  v a  2 s. c  o m*/
 *
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException Error in request handling
 * @throws IOException Error doing other IO
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession(true);
    Adapter adapter = null;

    String templateFile = (String) session.getAttribute("faban.submit.template");
    String styleSheet = (String) session.getAttribute("faban.submit.stylesheet");

    String srcURL = new File(templateFile).toURI().toString();

    logger.finer("benchmark.template: " + srcURL);
    session.removeAttribute("faban.submit.template");
    session.removeAttribute("faban.submit.stylesheet");

    try {
        String requestURI = request.getRequestURI();
        String formURI = null;
        String contextPath = request.getContextPath();
        String benchPath = contextPath + "/bm_submit/";
        if (requestURI.startsWith(benchPath)) {
            int idx = requestURI.indexOf('/', benchPath.length());
            String benchName = requestURI.substring(benchPath.length(), idx);
            String formName = requestURI.substring(idx + 1);
            formURI = com.sun.faban.harness.common.Config.FABAN_HOME + "benchmarks/" + benchName + "/META-INF/"
                    + formName;
        } else {
            StringBuffer buffer = new StringBuffer(request.getScheme());
            buffer.append("://");
            buffer.append(request.getServerName());
            buffer.append(":");
            buffer.append(request.getServerPort());
            buffer.append(request.getContextPath());
            buffer.append(request.getParameter("form"));
            formURI = buffer.toString();
        }

        if (formURI == null) {
            throw new IOException("Resource not found: " + formURI);
        }
        logger.finer("Form URI: " + formURI);

        String css = request.getParameter("css");
        String actionURL = response.encodeURL(request.getRequestURI());
        logger.finer("actionURL: " + actionURL);

        // Find the base URL used by Faban. We do not use Config.FABAN_URL
        // because this base URL can vary by the interface name the Faban
        // master is accessed in this session. Otherwise it is identical.
        StringBuffer baseURL = request.getRequestURL();
        int uriLength = baseURL.length() - requestURI.length() + contextPath.length();
        baseURL.setLength(++uriLength); // Add the ending slash

        adapter = new Adapter();
        if (configFile != null && configFile.length() > 0)
            adapter.setConfigPath(configFile);

        File xsl = null;
        if (styleSheet != null)
            xsl = new File(styleSheet);

        if (xsl != null && xsl.exists()) {
            adapter.xslPath = xsl.getParent();
            adapter.stylesheet = xsl.getName();
        } else {
            adapter.xslPath = xsltDir;
            adapter.stylesheet = "faban.xsl";
        }

        adapter.baseURI = baseURL.toString();
        adapter.formURI = formURI;
        adapter.actionURL = actionURL;
        adapter.beanCtx.put("chiba.web.uploadDir", uploadDir);
        adapter.beanCtx.put("chiba.useragent", request.getHeader("User-Agent"));
        adapter.beanCtx.put("chiba.web.request", request);
        adapter.beanCtx.put("chiba.web.session", session);
        adapter.beanCtx.put("benchmark.template", srcURL);

        if (css != null) {
            adapter.CSSFile = css;
            logger.fine("using css stylesheet: " + css);
        }

        Map servletMap = new HashMap();
        servletMap.put(ChibaAdapter.SESSION_ID, session.getId());
        adapter.beanCtx.put(ChibaAdapter.SUBMISSION_RESPONSE, servletMap);

        Enumeration params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String s = (String) params.nextElement();
            //store all request-params we don't use in the beanCtx map
            if (!(s.equals("form") || s.equals("xslt") || s.equals("css") || s.equals("action_url"))) {
                String value = request.getParameter(s);
                adapter.beanCtx.put(s, value);
                logger.finer("added request param '" + s + "' to beanCtx");
            }
        }
        adapter.init();
        adapter.execute();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        adapter.generator.setOutput(out);
        adapter.buildUI();
        session.setAttribute("chiba.adapter", adapter);
        out.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception processing XForms", e);
        shutdown(adapter, session, e, request, response);
    }
}

From source file:com.konakart.actions.BaseAction.java

/**
 * Determines whether we are using SSL or not. If we are logged in, then we should be using SSL.
 * SSL can also be forced by setting the forceSSL boolean. If we should be using SSL but aren't
 * (or vice versa) we do a redirect by returning an action forward with the correct URL to
 * redirect to. Otherwise we return null
 * //from   ww w  .  j  a va 2s .  com
 * @param request
 * @param custId
 *            The customer id
 * @param forceSSL
 *            Set to true if we should force SSL.
 * @return ActionForward
 * @throws KKException
 */
protected String checkSSL(KKAppEng eng, HttpServletRequest request, int custId, boolean forceSSL)
        throws KKException {
    try {
        if (eng == null) {
            throw new KKException("checkSSL called with KKAppEng set to null");
        }
        String sslPort = eng.getSslPort();
        String standardPort = eng.getStandardPort();
        boolean activateCheck = eng.isEnableSSL();
        String sslBaseUrl = eng.getSslBaseUrl();

        if (activateCheck && request != null) {
            boolean isSSL = false;
            StringBuffer redirectUrl;

            if (request.getRequestURL() == null) {
                throw new KKException(
                        "Cannot determine whether SSL is being used because the method request.getRequestURL() returns null");
            }

            if (request.getRequestURL().substring(0, 5).equalsIgnoreCase("https")) {
                isSSL = true;
            }

            if (log.isDebugEnabled()) {
                log.debug("getServerName = " + request.getServerName());
                log.debug("getServerPort = " + request.getServerPort());
                log.debug("getServletPath = " + request.getServletPath());
                log.debug("getRequestURI = " + request.getRequestURI());
                log.debug("getRequestURL = " + request.getRequestURL());
                log.debug("isSSL = " + isSSL);
                log.debug("custId = " + custId);
            }

            if (!isSSL && (custId > -1 || forceSSL)) {
                // We aren't using SSL but should be
                redirectUrl = new StringBuffer();
                if (sslBaseUrl != null) {
                    redirectUrl.append(sslBaseUrl);
                    redirectUrl.append(request.getRequestURI());
                } else {
                    redirectUrl.append("https://");
                    redirectUrl.append(request.getServerName());
                    // Insert the port if it is non standard
                    if (sslPort != null && !sslPort.equals("443")) {
                        redirectUrl.append(":");
                        redirectUrl.append(sslPort);
                    }
                    redirectUrl.append(request.getRequestURI());
                }

                /*
                 * The following is called for security reasons. In some cases (such as when
                 * using Tomcat) the session id is appended to the URL in the browser (i.e.
                 * jsessionid=E2D1B0B2B8C5478B7F6F3C3C5D9BB0FB). If a hacker managed to get this
                 * session id while the customer wasn't logged in, he could use it to access
                 * sensitive information once the customer has logged in since the session id
                 * doesn't change. The following method creates a new session and substitutes
                 * it.
                 */
                changeSession(request);
            } else if (isSSL && (custId < 0) && !forceSSL) {
                // We are using SSL but shouldn't be
                redirectUrl = new StringBuffer();
                redirectUrl.append("http://");
                redirectUrl.append(request.getServerName());
                // Insert the port if it is non standard
                if (standardPort != null && !standardPort.equals("80")) {
                    redirectUrl.append(":");
                    redirectUrl.append(standardPort);
                }
                redirectUrl.append(request.getRequestURI());
            } else {
                // Don't need to do anything
                return null;
            }

            // Get the parameters
            StringBuffer parms = new StringBuffer();
            Enumeration<String> en = request.getParameterNames();
            while (en.hasMoreElements()) {
                String paramName = en.nextElement();
                String paramValue = request.getParameter(paramName);
                if (parms.length() > 0) {
                    parms.append("&");
                } else {
                    parms.append("?");
                }
                parms.append(paramName);
                parms.append("=");
                parms.append(paramValue);
            }

            // Append the parameters to the redirect url
            redirectUrl.append(parms);
            if (log.isDebugEnabled()) {
                log.debug("redirectUrl = " + redirectUrl);
            }
            return redirectUrl.toString();
        }

        return null;
    } catch (Exception e) {
        log.error(e);
        return null;
    }
}

From source file:org.jahia.params.ParamBean.java

@SuppressWarnings("unchecked")
private void copyRequestData(final HttpServletRequest request) {

    if (request == null) {
        return;// w  w  w  .j a  v  a2s  .  c  o m
    }

    if (isMultipartRequest(request)) {
        // multipart is processed only if it's not a portlet request.
        // otherwise it's the task the portlet
        if (!isPortletRequest(request)) {
            final String savePath = settings().getTmpContentDiskPath();
            final File tmp = new File(savePath);
            if (!tmp.exists()) {
                tmp.mkdirs();
            }
            try {
                fupload = new FileUpload(request, savePath, Integer.MAX_VALUE);
                Set<String> names = fupload.getParameterNames();
                for (String name : names) {
                    getCustomParameters().put(name, fupload.getParameterValues(name));
                }
            } catch (IOException e) {
                logger.error("Cannot parse multipart data !", e);
            }
        } else {
            logger.debug("Mulipart request is not processed. It's the task of the portlet");
        }
    }

    // first let's copy all the parameters from the request object
    getCustomParameters().putAll(request.getParameterMap());

    setScheme(request.getScheme());
    setRequestURI(request.getRequestURI());
    setContextPath(request.getContextPath());
    setServletPath(request.getServletPath());
    setPathInfo(request.getPathInfo());
    setQueryString(request.getQueryString());
    setServerName(request.getServerName());
    setServerPort(request.getServerPort());

    setRemoteAddr(request.getRemoteAddr());

    setSessionState(new HttpSessionState(request.getSession()));
}

From source file:org.dspace.authenticate.ShibAuthentication.java

/**
 * Get login page to which to redirect. Returns URL (as string) to which to
 * redirect to obtain credentials (either password prompt or e.g. HTTPS port
 * for client cert.); null means no redirect.
 * //from   ww  w. j  a  va2  s .  com
 * @param context
 *            DSpace context, will be modified (ePerson set) upon success.
 * 
 * @param request
 *            The HTTP request that started this operation, or null if not
 *            applicable.
 * 
 * @param response
 *            The HTTP response from the servlet method.
 * 
 * @return fully-qualified URL or null
 */
@Override
public String loginPageURL(Context context, HttpServletRequest request, HttpServletResponse response) {
    // If this server is configured for lazy sessions then use this to
    // login, otherwise default to the protected shibboleth url.

    boolean lazySession = configurationService.getBooleanProperty("authentication-shibboleth.lazysession",
            false);

    if (lazySession) {
        String shibURL = configurationService.getProperty("authentication-shibboleth.lazysession.loginurl");
        boolean forceHTTPS = configurationService
                .getBooleanProperty("authentication-shibboleth.lazysession.secure", true);

        // Shibboleth authentication initiator 
        if (shibURL == null || shibURL.length() == 0)
            shibURL = "/Shibboleth.sso/Login";
        shibURL = shibURL.trim();

        // Determine the return URL, where shib will send the user after authenticating. We need it to go back
        // to DSpace's shibboleth-login url so the we will extract the user's information and locally
        // authenticate them.
        String host = request.getServerName();
        int port = request.getServerPort();
        String contextPath = request.getContextPath();

        String returnURL;
        if (request.isSecure() || forceHTTPS)
            returnURL = "https://";
        else
            returnURL = "http://";

        returnURL += host;
        if (!(port == 443 || port == 80))
            returnURL += ":" + port;
        returnURL += "/" + contextPath + "/shibboleth-login";

        try {
            shibURL += "?target=" + URLEncoder.encode(returnURL, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            log.error("Unable to generate lazysession authentication", uee);
        }

        log.debug("Redirecting user to Shibboleth initiator: " + shibURL);

        return response.encodeRedirectURL(shibURL);
    } else {
        // If we are not using lazy sessions rely on the protected URL.
        return response.encodeRedirectURL(request.getContextPath() + "/shibboleth-login");
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Executes the {@link org.apache.commons.httpclient.HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException      Can be thrown by the {@link org.apache.commons.httpclient.HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 *///  ww  w  . j a  va  2 s. c  om
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @param httpServletRequest Request object pertaining to the proxied HTTP request
 * @throws IOException      Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 *///w ww . jav  a 2  s .c o  m
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    getCredential(httpServletRequest.getParameter("servername"));
    if (credentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    }
    httpMethodProxyRequest.setFollowRedirects(true);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    String response = httpMethodProxyRequest.getResponseBodyAsString();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                cookie.setPath("/");
                //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                httpServletResponse.addCookie(cookie);
            }
            httpServletResponse.sendRedirect(stringLocation
                    .replace(getProxyHostAndPort(httpServletRequest) + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            response = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, response);
        } else {
            response = new String(ungzip(httpMethodProxyRequest.getResponseBody()));
        }
        httpServletResponse.setContentLength(response.length());
    }

    // Send the content to the client
    if (intProxyResponseCode == 200)
        httpServletResponse.getWriter().write(response);
    else
        httpServletResponse.getWriter().write(intProxyResponseCode);
}