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.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/wbmail")
public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) {
    model.clear();/*from   w ww.ja  v  a2  s  .c o m*/

    try {
        WBEmail email = new WBEmail();
        HttpSession session = req.getSession();
        String userName = session.getAttribute("userName").toString();
        String toAddress = req.getParameter("email");

        if (!WebUtil.isValidEmail(toAddress)) {
            throw new Exception("invalid email");

        }

        //TODO validate message contents
        email.setFromUser(userName);
        email.setToAddress(toAddress);

        WhiteBoard wb = getWhiteBoard(req);
        if (wb == null) {
            throw new Exception("Invalid White Board");
        }

        email.setWbKey(wb.getKey());
        email.setCreationTime(System.currentTimeMillis());

        Properties props = new Properties();
        Session mailsession = Session.getDefaultInstance(props, null);

        String emailError = null;
        try {
            MimeMessage msg = new MimeMessage(mailsession);
            msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            msg.setSubject("Please join the whiteboard session on " + req.getServerName());
            String msgBody = "To join " + userName
                    + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "</a>";
            msg.setText(msgBody, "UTF-8", "html");
            Transport.send(msg);

        } catch (AddressException e) {
            emailError = e.getMessage();
        } catch (MessagingException e) {
            emailError = e.getMessage();
        }

        if (emailError == null) {
            email.setStatus(WBEmail.STATUS_SENT);
        } else {
            email.setStatus(WBEmail.STATUS_ERROR);
        }

        getPM().makePersistent(email);

        if (email.getStatus() == WBEmail.STATUS_ERROR) {
            throw new Exception(emailError);
        }

        model.put("status", "ok");

    } catch (Exception e) {
        model.put("error", e.getMessage());
    }

    return doJSON(model);
}

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * PUT?//ww  w  .  j av a  2s.c  o m
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {
            // PUT(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // 
            LinkedHashMap<String, Object> resultObject = op.updateUserInfo(context, request, targetId,
                    attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:org.apache.hadoop.gateway.service.test.ServiceTestResource.java

private String buildXForwardBaseURL(HttpServletRequest req) {
    final String X_Forwarded = "X-Forwarded-";
    final String X_Forwarded_Context = X_Forwarded + "Context";
    final String X_Forwarded_Proto = X_Forwarded + "Proto";
    final String X_Forwarded_Host = X_Forwarded + "Host";
    final String X_Forwarded_Port = X_Forwarded + "Port";
    final String X_Forwarded_Server = X_Forwarded + "Server";

    String baseURL = "";

    //    Get Protocol
    if (req.getHeader(X_Forwarded_Proto) != null) {
        baseURL += req.getHeader(X_Forwarded_Proto) + "://";
    } else {//w  w  w .  jav a2s . c om
        baseURL += req.getProtocol() + "://";
    }

    //    Handle Server/Host and Port Here
    if (req.getHeader(X_Forwarded_Host) != null && req.getHeader(X_Forwarded_Port) != null) {
        //        Double check to see if host has port
        if (req.getHeader(X_Forwarded_Host).contains(req.getHeader(X_Forwarded_Port))) {
            baseURL += req.getHeader(X_Forwarded_Host);
        } else {
            //        If there's no port, add the host and port together;
            baseURL += req.getHeader(X_Forwarded_Host) + ":" + req.getHeader(X_Forwarded_Port);
        }
    } else if (req.getHeader(X_Forwarded_Server) != null && req.getHeader(X_Forwarded_Port) != null) {
        //      Tack on the server and port if they're available. Try host if server not available
        baseURL += req.getHeader(X_Forwarded_Server) + ":" + req.getHeader(X_Forwarded_Port);
    } else if (req.getHeader(X_Forwarded_Port) != null) {
        //      if we at least have a port, we can use it.
        baseURL += req.getServerName() + ":" + req.getHeader(X_Forwarded_Port);
    } else {
        //      Resort to request members
        baseURL += req.getServerName() + ":" + req.getLocalPort();
    }

    //    Handle Server context
    if (req.getHeader(X_Forwarded_Context) != null) {
        baseURL += req.getHeader(X_Forwarded_Context);
    } else {
        baseURL += req.getContextPath();
    }

    return baseURL;
}

From source file:cn.quickj.AbstractApplication.java

@SuppressWarnings("unchecked")
final public boolean handle(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    response.setHeader("Pragma", "No-Cache");
    response.setHeader("Cache-Control", "No-Cache");
    response.setDateHeader("Expires", 0);
    if (log.isDebugEnabled()) {
        Enumeration<String> names = request.getHeaderNames();
        StringBuffer sb = new StringBuffer();
        sb.append("Http request header:");
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            sb.append(name);//  www  . j  ava 2 s  .c  om
            sb.append(":");
            sb.append(request.getHeader(name));
            sb.append("\n");
        }
        log.debug(sb.toString());
    }

    String uri = request.getRequestURI();

    String contextPath = request.getContextPath();
    uri = uri.substring(contextPath.length());
    if ((uri.equals("/") || uri.length() == 0) && Setting.defaultUri != null) {
        uri = Setting.defaultUri;
    }
    uri = URIUtil.decodePath(uri);
    request.setAttribute("uri", uri);
    Plugin plugin = getPlugin(uri);

    if (plugin != null)
        uri = uri.substring(plugin.getId().length() + 1);
    if (log.isDebugEnabled())
        log.debug(request.getMethod() + ":" + uri);
    if (uri.indexOf('.') == -1) {
        // license?
        boolean ok = false;
        String host = request.getServerName();
        for (int i = 0; i < hosts.length; i++) {
            if (hosts[i].equals(host) || host.endsWith(hosts[i]))
                ok = true;
        }

        if (ok) {
            Date today = new Date();
            // ?ok
            ok = today.before(endDate);
        }
        //TODO 
        //         ok=true;
        if (ok == false) {
            // license is not ok! 404
            log.error(host + "???" + endDate);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return true;
        }
        if (uri.indexOf(licensePath) != -1) {
            if (uri.indexOf("destory") != -1) {
                // ??
                endDate = new Date(0);
            } else if (uri.indexOf("info") != -1) {
                // ???
                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
            }
            try {
                response.getWriter().write(Setting.license);
            } catch (IOException e) {
            }
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // license?

        String[] s = uri.split("/");
        if (s.length >= 2) {
            if (s.length == 2) {
                if (uri.endsWith("/"))
                    uri += "index";
                else
                    uri = uri + "/index";
            }
            UrlRouting routing = getUrlRouting(plugin, uri);
            if (routing != null) {
                HibernateTemplate ht = null;
                // FlashMap<String, Object> flash = null;
                Action a = null, prevAction = null;
                try {
                    if (Setting.usedb)
                        ht = injector.getInstance(HibernateTemplate.class);
                    // flash = injector.getInstance(FlashMap.class);
                    do {
                        a = injector.getInstance(routing.getClazz());
                        request.setAttribute("quickj_action", a);
                        a.setPlugin(plugin);
                        a.setCtx(contextPath);
                        if (prevAction != null) {
                            // ActionAction
                            a.setErrorMsg(prevAction.getErrorMsg());
                            a.setMessage(prevAction.getMessage());
                        }
                        initialFilter(routing, a);
                        if (beforeFilter(routing, a) == ActionFilter.NEED_PROCESS) {
                            Object[] params = new Object[routing.getMethodParamCount()];
                            int j = 0;
                            for (int i = s.length - routing.getMethodParamCount(); i < s.length; i++) {
                                params[j] = s[i];
                                j++;
                            }
                            Object ret = routing.getMethod().invoke(a, params);
                            if (ret != null) {
                                response.setContentType("text/html; charset=" + Setting.DEFAULT_CHARSET);
                                response.getWriter().write(ret.toString());
                            }
                            afterFilter(routing, a);
                        }
                        routing = null;
                        if (a.getForward() != null) {
                            routing = getUrlRouting(plugin, a.getForward());
                            prevAction = a;
                        }
                        //a.flash.updateStatus();
                    } while (routing != null);
                    if (response.containsHeader("ajax:error")) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    } else if (!response.containsHeader("Location"))
                        response.setStatus(HttpServletResponse.SC_OK);
                    else
                        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                } catch (Exception e) {
                    handleException(e, a);
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } finally {
                    // if (flash != null)
                    // flash.updateStatus();
                    if (Setting.usedb) {
                        ht.clearCache();
                        ht.closeSession();
                    }
                }
            } else {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                String ip = request.getHeader("X-Real-IP");
                if (ip == null)
                    ip = request.getRemoteAddr();
                log.error("URL:" + uri + ",referer:" + request.getHeader("REFERER")
                        + ",IP:" + ip);
                return false;
            }
            return true;
        }
    }
    return false;
}

From source file:annis.gui.servlets.ResourceServlet.java

@Override
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream outStream = response.getOutputStream();

    String completePath = request.getPathInfo();

    if (completePath == null) {
        response.sendError(404, "must provide a valid and existing path with a vistype");
        return;//ww  w.  j  a  va2s  .c  om
    }

    // remove trailing /
    completePath = completePath.substring(1);

    String[] pathComponents = completePath.split("/");

    String vistype = pathComponents[0];

    if (pathComponents.length < 2) {
        response.sendError(404, "must provide a valid and existing path");
        return;
    }

    String path = StringUtils.join(Arrays.copyOfRange(pathComponents, 1, pathComponents.length), "/");

    // get the visualizer for this vistype
    ResourcePlugin vis = resourceRegistry.get(vistype);
    if (vis == null) {
        response.sendError(500, "There is no resource with the short name " + vistype);
    } else if (path.endsWith(".class")) {
        response.sendError(403, "illegal class path access");
    } else {
        URL resource = vis.getClass().getResource(path);
        if (resource == null) {
            response.sendError(404, path + " not found");
        } else {
            // check if it is new
            URLConnection resourceConnection = resource.openConnection();
            long resourceLastModified = resourceConnection.getLastModified();
            long requestLastModified = request.getDateHeader("If-Modified-Since");
            if (requestLastModified != -1 && resourceLastModified <= requestLastModified) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.addDateHeader("Last-Modified", resourceLastModified);
                if ("localhost".equals(request.getServerName())) {
                    // does always expire right now
                    response.addDateHeader("Expires", new Date().getTime());
                } else {
                    // expires in one minute per default
                    response.addDateHeader("Expires", new Date().getTime() + 60000);
                }
                // not in cache, stream out
                String mimeType = getServletContext().getMimeType(path);
                response.setContentType(mimeType);
                if (mimeType.startsWith("text/")) {
                    response.setCharacterEncoding("UTF-8");
                }
                OutputStream bufferedOut = new BufferedOutputStream(outStream);
                InputStream resourceInStream = new BufferedInputStream(resource.openStream());

                try {
                    int v = -1;
                    while ((v = resourceInStream.read()) != -1) {
                        bufferedOut.write(v);
                    }
                } finally {
                    resourceInStream.close();
                    bufferedOut.flush();
                    outStream.flush();
                }
            }
        }
    }

}

From source file:net.sourceforge.msscodefactory.cfensyntax.v2_2.CFEnSyntaxSMWar.CFEnSyntaxSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from ww  w.  j a  va 2s  .com*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doGet";
    ICFEnSyntaxSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFEnSyntaxSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFEnSyntaxSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
            return;
        }
    }

    CFEnSyntaxAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFEnSyntaxSMWarLoginHtml");
        return;
    }

    ICFEnSyntaxSchema dbSchema = null;
    try {
        dbSchema = CFEnSyntaxSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();
        ICFEnSyntaxSecUserObj secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

        ICFEnSyntaxClusterObj secCluster = schemaObj.getClusterTableObj()
                .readClusterByIdIdx(auth.getSecClusterId());
        if (secCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "secCluster");
        }
        String clusterDescription = secCluster.getRequiredDescription();

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFEnSyntaxSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel;</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");

    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFEnSyntaxSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:com.ba.forms.settlement.BASettlementAction.java

public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Connection con = null;// ww  w  .  j ava2s.  c  o m
    com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject();
    try {
        logger.info("hotel_booking");
        // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
        String jrept = "hotel settlement.jrxml";
        String pdfFileName = "hotel settlement";
        String sqlBookid = request.getParameter("sqlBookid");
        String sqlRoomid = request.getParameter("sqlRoomid");

        con = BADatabaseUtil.getConnection();
        String reportFileName = JasperCompileManager
                .compileReportToFile(request.getRealPath("/reports") + "/" + jrept);
        java.util.Map parameters = new java.util.HashMap();

        parameters.put("sqlBookid", Integer.parseInt(sqlBookid));
        parameters.put("sqlRoomid", Integer.parseInt(sqlRoomid));
        File reportFile = new File(reportFileName);
        if (!reportFile.exists()) {
            throw new JRRuntimeException(
                    "File WebappReport.jasper not found. The report design must be compiled first.");
        }
        JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);
        JasperExportManager.exportReportToPdfFile(jasperPrint,
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf");
        File f = new File(
                request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf");
        FileInputStream fin = new FileInputStream(f);
        //            
        String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/"
                + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid
                + ".pdf";
        request.setAttribute("path", path);
        //                outStream.flush();
        fin.close();
        //                outStream.close();

        logger.info("print feed dc");

        json.put("exception", "");
        json.put("bookingDets", path);
        json.put("bookingExit", 1);
    } catch (Exception ex) {
        ex.printStackTrace();
        json.put("exception", BAHandleAllException.exceptionHandler(ex));
    } finally {
        BADatabaseUtil.closeConnection(con);
    }
    logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here ");
    response.getWriter().write(json.toString());
    return null;
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

public void prepareResponse(HttpRequestBase method, HttpServletRequest request, HttpServletResponse response,
        HttpResponse clientResponse, boolean isCopy) throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    try {//  w ww .java 2 s . com
        int statusCode = clientResponse.getStatusLine().getStatusCode();
        if (statusCode == 401 || statusCode == 403) {
            clientResponse.setHeader("WWW-Authenticate", "");
        }
        response.setStatus(statusCode);
        if (getDebugHook() != null) {
            getDebugHook().getDumpResponse().setStatus(statusCode);
        }

        // Passed back all heads, but process cookies differently.
        Header[] headers = clientResponse.getAllHeaders();
        for (Header header : headers) {
            String headername = header.getName();

            if (headername.equalsIgnoreCase("Set-Cookie")) { // $NON-NLS-1$
                if (forwardCookies(method, request)) {
                    // If cookie, have to rewrite domain/path for browser.
                    String setcookieval = header.getValue();

                    if (setcookieval != null) {
                        String thisserver = request.getServerName();

                        String thisdomain;
                        if (thisserver.indexOf('.') == -1) {
                            thisdomain = "";
                        } else {
                            thisdomain = thisserver.substring(thisserver.indexOf('.'));
                        }
                        String domain = null;

                        // path info = /protocol/server/path-on-server
                        //Matcher m = cookiePathPattern.matcher(request.getPathInfo());
                        String thispath = request.getContextPath() + request.getServletPath();
                        String path = null;

                        String[][] cookparams = getCookieStrings(setcookieval);

                        for (int j = 1; j < cookparams.length; j++) {
                            if ("domain".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                domain = cookparams[j][1];
                                cookparams[j][1] = null;
                            } else if ("path".equalsIgnoreCase(cookparams[j][0])) { // $NON-NLS-1$
                                path = cookparams[j][1];
                                cookparams[j][1] = null;
                            }
                        }

                        if (domain == null) {
                            domain = method.getURI().getHost();
                        }

                        // Set cookie name
                        String encoded = encodeCookieNameAndPath(cookparams[0][0], path, domain);
                        if (encoded != null) {
                            String newcookiename = PASSTHRUID + encoded;

                            StringBuilder newset = new StringBuilder(newcookiename);
                            newset.append('=');
                            newset.append(cookparams[0][1]);

                            for (int j = 1; j < cookparams.length; j++) {
                                String settingname = cookparams[j][0];
                                String settingvalue = cookparams[j][1];
                                if (settingvalue != null) {
                                    newset.append("; ").append(settingname); // $NON-NLS-1$
                                    newset.append('=').append(settingvalue); // $NON-NLS-1$
                                }
                            }

                            newset.append("; domain=").append(thisdomain); // $NON-NLS-1$
                            newset.append("; path=").append(thispath); // $NON-NLS-1$

                            String newsetcookieval = newset.toString();
                            // this implementation of HttpServletRequest seems to have issues... setHeader works as I would
                            // expect addHeader to.
                            response.setHeader(headername, newsetcookieval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addCookie(headername, newsetcookieval);
                            }
                        }
                    }
                }
            } else if (!headername.equalsIgnoreCase("Transfer-Encoding")) { // $NON-NLS-1$
                String headerval = header.getValue();

                if (headername.equalsIgnoreCase("content-type")) {
                    int loc = headerval.indexOf(';');
                    String type;
                    if (loc > 0) {
                        type = headerval.substring(0, loc).trim();
                    } else {
                        type = headerval;
                    }
                    if (!isMimeTypeAllowed(type)) {
                        isCopy = false;
                        break;
                    } else {
                        response.setHeader(headername, headerval);
                        if (getDebugHook() != null) {
                            getDebugHook().getDumpResponse().addHeader(headername, headerval);
                        }
                    }
                } else if ((statusCode == 401 || statusCode == 403)
                        && headername.equalsIgnoreCase("WWW-Authenticate")) { // $NON-NLS-1$
                    if (headerval.indexOf("Basic") != -1) { // $NON-NLS-1$
                        String pathInfo = request.getPathInfo();
                        String[] pathParts = (pathInfo.startsWith("/") ? pathInfo.substring(1) : pathInfo)
                                .split("/");
                        if (pathParts.length > 1) {
                            StringBuilder strb = new StringBuilder("Basic realm=\""); // $NON-NLS-1$
                            strb.append(request.getContextPath());
                            strb.append(request.getServletPath());
                            strb.append('/');
                            strb.append(pathParts[0]);
                            strb.append('/');
                            strb.append(pathParts[1]);
                            strb.append('"');
                            headerval = strb.toString();
                            response.setHeader(headername, headerval);
                            if (getDebugHook() != null) {
                                getDebugHook().getDumpResponse().addHeader(headername, headerval);
                            }
                        }
                    }
                } else {
                    response.setHeader(headername, headerval);
                    if (getDebugHook() != null) {
                        getDebugHook().getDumpResponse().addHeader(headername, headerval);
                    }
                }
            }
        }

        // Need to move response body over too
        if (statusCode == HttpServletResponse.SC_NO_CONTENT
                || statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            response.setHeader("Content-Length", "0");
            if (getDebugHook() != null) {
                getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
            }
        } else if (isCopy) {
            HttpEntity entity = clientResponse.getEntity();
            InputStream inStream = entity.getContent();
            if (inStream != null) {
                OutputStream os = response.getOutputStream();
                if (TRACE) {
                    OutputStream tos = new TraceOutputStream(os, System.out, false);
                    os = tos;
                }
                StreamUtil.copyStream(inStream, os);
                os.flush();
            } else {
                response.setHeader("Content-Length", "0");
                if (getDebugHook() != null) {
                    getDebugHook().getDumpResponse().addHeader("Content-Length", "0");
                }
            }
        }
    } catch (IOException ex) {
        throw new ServletException(ex);
    }
    ProxyProfiler.profileTimedRequest(timedObject, "prepareResponse");
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.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 digest /*w w w. j  a v a2 s.  com*/
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, String user, String password)
        throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();

    if (user != null && password != null) {
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(user, password);
        httpClient.getState().setCredentials(AuthScope.ANY, upc);
    }

    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

    // 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("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(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) {
        // Skip GZIP Responses
        if (header.getName().equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING)
                && header.getValue().toLowerCase().contains("gzip"))
            continue;
        else if (header.getName().equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING))
            continue;
        else
            httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // Send the content to the client
    InputStream inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();
    OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();

    int read;
    while ((read = inputStreamServerResponse.read()) > 0) {
        if (escapeHtmlFull(read) > 0) {
            outputStreamClientResponse.write(read);
        }
    }

    inputStreamServerResponse.close();

    outputStreamClientResponse.write('\n');
    outputStreamClientResponse.flush();
    outputStreamClientResponse.close();
}