Example usage for javax.servlet.http HttpServletRequest getServerName

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

Introduction

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

Prototype

public String getServerName();

Source Link

Document

Returns the host name of the server to which the request was sent.

Usage

From source file:com.cyclopsgroup.waterview.servlet.ServletRuntimeData.java

/**
 * Default constructor of default web runtime
 *
 * @param request Http request object/*from  ww w .  j a  va 2 s  .c o  m*/
 * @param response Http response object
 * @param context Http servlet context
 * @param fileUpload File upload component
 * @param services ServiceManager object
 * @param applicationBase application base url
 * @throws Exception Throw it out
 */
ServletRuntimeData(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        FileUpload fileUpload, ServiceManager services, String applicationBase) throws Exception {
    this.response = response;
    this.context = context;

    setQueryString(request.getQueryString());
    setRefererUrl(request.getHeader("referer"));

    //Session Context
    setSessionContext(new HttpSessionContext(request.getSession()));
    setSessionId(request.getSession().getId());

    setRequestContext(new ServletRequestContext(request));

    //Request path
    String requestPath = request.getPathInfo();
    setRequestPath(requestPath == null ? StringUtils.EMPTY : requestPath);

    //Output
    OutputStream outputStream = response.getOutputStream();
    setOutputStream(outputStream);

    InterpolationFilterWriter filterWriter = new InterpolationFilterWriter(new OutputStreamWriter(outputStream),
            '%') {
        /**
         * Overwrite or implement method interpolate()
         *
         * @see com.cyclopsgroup.waterview.utils.InterpolationFilterWriter#interpolate(java.lang.String)
         */
        protected String interpolate(String name) throws Exception {
            I18NService i18n = (I18NService) getServiceManager().lookup(I18NService.ROLE);
            return i18n.translate(name, getLocale());
        }
    };
    setOutput(new PrintWriter(filterWriter));

    //Request value parser
    if (FileUpload.isMultipartContent(request)) {
        setParams(new MultipartServletRequestParameters(request, fileUpload));
    } else {
        setParams(new ServletRequestParameters(request));
    }

    //Service manager
    setServiceManager(services);

    //Application base url
    if (StringUtils.isEmpty(applicationBase)) {
        StringBuffer sb = new StringBuffer(request.getScheme());
        sb.append("://").append(request.getServerName());
        if (request.getServerPort() != 80) {
            sb.append(':').append(request.getServerPort());
        }
        sb.append(request.getContextPath());
        applicationBase = sb.toString();
    }
    setApplicationBaseUrl(applicationBase);

    //Page base url
    setPageBaseUrl(applicationBase + request.getServletPath());
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj 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/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }//w  w w. ja  v  a 2  s  .c o  m

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

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

    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
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?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
 *///from   w ww. j  a va2  s .  co 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: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");
    }/* ww  w.j  ava2 s . co  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.sun.faban.harness.webclient.XFormServlet.java

/**
 * A get request starts a new form.//from  w w w .j  a v a 2s .  c om
 *
 * @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.provenance.cloudprovenance.traceabilitystore.ws.controler.TraceabilityStoreController.java

@Override
@POST//from  ww w . j  a  v  a  2s . c  o m
@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: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
 * /*  www .  j  a va  2 s .  c o m*/
 * @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:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data./* w w w .j  a  v  a2 s  .c  o  m*/
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

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
 *///  w w w .ja  v a2 s .c o  m
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.janrain.backplane2.server.Backplane2Controller.java

/**
 * Retrieve a single message from the server.
 *
 * @param request//from   w w w .j  a v  a  2 s  . c om
 * @param response
 * @return
 */
@RequestMapping(value = "/message/{msg_id:.*}", method = { RequestMethod.GET })
public @ResponseBody Map<String, Object> message(HttpServletRequest request, HttpServletResponse response,
        @PathVariable final String msg_id,
        @RequestParam(value = OAUTH2_ACCESS_TOKEN_PARAM_NAME, required = false) String access_token,
        @RequestParam(required = false) String callback,
        @RequestHeader(value = "Authorization", required = false) String authorizationHeader)
        throws BackplaneServerException, SimpleDBException {

    ServletUtil.checkSecure(request);

    TimerContext context = v2GetSingleMessageTimer.time();

    try {
        new MessageRequest(callback, null, "0"); // validate callback only, if present
    } catch (InvalidRequestException e) {
        return handleInvalidRequest(e, response);
    }

    try {
        Token token = Token.fromRequest(daoFactory, request, access_token, authorizationHeader);
        if (token.getType().isRefresh()) {
            throw new TokenException("Invalid token type: " + token.getType(),
                    HttpServletResponse.SC_FORBIDDEN);
        }

        BackplaneMessage message = daoFactory.getBackplaneMessageDAO().retrieveBackplaneMessage(msg_id, token);

        if (message != null) {
            Map<String, Object> result = message.asFrame(request.getServerName(),
                    token.getType().isPrivileged());
            aniLogGetMessage(request, message, token);
            return result;
        } else {
            return returnMessage(OAuth2.OAUTH2_TOKEN_INVALID_REQUEST, "Message id '" + msg_id + "' not found",
                    HttpServletResponse.SC_NOT_FOUND, response);
        }
    } catch (TokenException te) {
        return handleTokenException(te, response);
    } finally {
        context.stop();
    }
}