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:org.apache.sling.resourceresolver.impl.ResourceResolverImpl.java

private Resource resolveInternal(final HttpServletRequest request, String absPath) {
    // make sure abspath is not null and is absolute
    if (absPath == null) {
        absPath = "/";
    } else if (!absPath.startsWith("/")) {
        absPath = "/" + absPath;
    }/*from ww w .  ja v  a  2 s  .  co  m*/

    // check for special namespace prefix treatment
    absPath = unmangleNamespaces(absPath);

    // Assume http://localhost:80 if request is null
    String[] realPathList = { absPath };
    String requestPath;
    if (request != null) {
        requestPath = getMapPath(request.getScheme(), request.getServerName(), request.getServerPort(),
                absPath);
    } else {
        requestPath = getMapPath("http", "localhost", 80, absPath);
    }

    logger.debug("resolve: Resolving request path {}", requestPath);

    // loop while finding internal or external redirect into the
    // content out of the virtual host mapping tree
    // the counter is to ensure we are not caught in an endless loop here
    // TODO: might do better to be able to log the loop and help the user
    for (int i = 0; i < 100; i++) {

        String[] mappedPath = null;

        final Iterator<MapEntry> mapEntriesIterator = this.factory.getMapEntries()
                .getResolveMapsIterator(requestPath);
        while (mapEntriesIterator.hasNext()) {
            final MapEntry mapEntry = mapEntriesIterator.next();
            mappedPath = mapEntry.replace(requestPath);
            if (mappedPath != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("resolve: MapEntry {} matches, mapped path is {}", mapEntry,
                            Arrays.toString(mappedPath));
                }
                if (mapEntry.isInternal()) {
                    // internal redirect
                    logger.debug("resolve: Redirecting internally");
                    break;
                }

                // external redirect
                logger.debug("resolve: Returning external redirect");
                return this.factory.getResourceDecoratorTracker()
                        .decorate(new RedirectResource(this, absPath, mappedPath[0], mapEntry.getStatus()));
            }
        }

        // if there is no virtual host based path mapping, abort
        // and use the original realPath
        if (mappedPath == null) {
            logger.debug("resolve: Request path {} does not match any MapEntry", requestPath);
            break;
        }

        // if the mapped path is not an URL, use this path to continue
        if (!mappedPath[0].contains("://")) {
            logger.debug("resolve: Mapped path is for resource tree");
            realPathList = mappedPath;
            break;
        }

        // otherwise the mapped path is an URI and we have to try to
        // resolve that URI now, using the URI's path as the real path
        try {
            final URI uri = new URI(mappedPath[0], false);
            requestPath = getMapPath(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath());
            realPathList = new String[] { uri.getPath() };

            logger.debug("resolve: Mapped path is an URL, using new request path {}", requestPath);
        } catch (final URIException use) {
            // TODO: log and fail
            throw new ResourceNotFoundException(absPath);
        }
    }

    // now we have the real path resolved from virtual host mapping
    // this path may be absolute or relative, in which case we try
    // to resolve it against the search path

    Resource res = null;
    for (int i = 0; res == null && i < realPathList.length; i++) {
        final ParsedParameters parsedPath = new ParsedParameters(realPathList[i]);
        final String realPath = parsedPath.getRawPath();

        // first check whether the requested resource is a StarResource
        if (StarResource.appliesTo(realPath)) {
            logger.debug("resolve: Mapped path {} is a Star Resource", realPath);
            res = new StarResource(this, ensureAbsPath(realPath));

        } else {

            if (realPath.startsWith("/")) {

                // let's check it with a direct access first
                logger.debug("resolve: Try absolute mapped path {}", realPath);
                res = resolveInternal(realPath, parsedPath.getParameters());

            } else {

                final String[] searchPath = getSearchPath();
                for (int spi = 0; res == null && spi < searchPath.length; spi++) {
                    logger.debug("resolve: Try relative mapped path with search path entry {}",
                            searchPath[spi]);
                    res = resolveInternal(searchPath[spi] + realPath, parsedPath.getParameters());
                }

            }
        }
    }

    // if no resource has been found, use a NonExistingResource
    if (res == null) {
        final ParsedParameters parsedPath = new ParsedParameters(realPathList[0]);
        final String resourcePath = ensureAbsPath(parsedPath.getRawPath());
        logger.debug("resolve: Path {} does not resolve, returning NonExistingResource at {}", absPath,
                resourcePath);

        res = new NonExistingResource(this, resourcePath);
        // SLING-864: if the path contains a dot we assume this to be
        // the start for any selectors, extension, suffix, which may be
        // used for further request processing.
        // the resolution path must be the full path and is already set within
        // the non existing resource
        final int index = resourcePath.indexOf('.');
        if (index != -1) {
            res.getResourceMetadata().setResolutionPathInfo(resourcePath.substring(index));
        }
        res.getResourceMetadata().setParameterMap(parsedPath.getParameters());
    } else {
        logger.debug("resolve: Path {} resolves to Resource {}", absPath, res);
    }

    return this.factory.getResourceDecoratorTracker().decorate(res);
}

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

/**
 * PUT?//  w w w .j a va2s . 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:PrintCGI.java

/**
     * Prints CGI Environment Variables in a table
     * //from  w  ww  .java2 s . c  o m
     * @param request
     * @param response
     * @throws IOException
     */

    public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String headers = null;
        String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>";
        String htmlFooter = "</BODY></HTML>";

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println(htmlHeader);
        out.println("<TABLE ALIGN=CENTER BORDER=1>");
        out.println("<tr><th> CGI Variable </th><th> Value </th>");

        out.println("<tr><td align=center>Authentication Type</td>");
        out.println("<td align=center>" + request.getAuthType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type</td>");
        out.println("<td align=center>" + request.getContentType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type Length</td>");
        out.println("<td align=center>" + request.getContentLength() + "</td></tr>");

        out.println("<tr><td align=center>Query String</td>");
        out.println("<td align=center>" + request.getMethod() + "</td></tr>");

        out.println("<tr><td align=center>IP Address</td>");
        out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>");

        out.println("<tr><td align=center>Host Name</td>");
        out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>");

        out.println("<tr><td align=center>Request URL</td>");
        out.println("<td align=center>" + request.getRequestURI() + "</td></tr>");

        out.println("<tr><td align=center>Servlet Path</td>");
        out.println("<td align=center>" + request.getServletPath() + "</td></tr>");

        out.println("<tr><td align=center>Server's Name</td>");
        out.println("<td align=center>" + request.getServerName() + "</td></tr>");

        out.println("<tr><td align=center>Server's Port</td>");
        out.println("<td align=center>" + request.getServerPort() + "</td></tr>");

        out.println("</TABLE><BR>");
        out.println(htmlFooter);

    }

From source file:org.apache.struts2.views.util.DefaultUrlHelper.java

public String buildUrl(String action, HttpServletRequest request, HttpServletResponse response,
        Map<String, Object> params, String scheme, boolean includeContext, boolean encodeResult,
        boolean forceAddSchemeHostAndPort, boolean escapeAmp) {
    StringBuilder link = new StringBuilder();

    boolean changedScheme = false;

    // FIXME: temporary hack until class is made a properly injected bean
    Container cont = ActionContext.getContext().getContainer();
    int httpPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTP_PORT));
    int httpsPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTPS_PORT));

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
        String reqScheme = request.getScheme();
        changedScheme = true;/*  w  w w . j  av  a  2s  .  c om*/
        link.append(scheme != null ? scheme : reqScheme);
        link.append("://");
        link.append(request.getServerName());

        if (scheme != null) {
            // If switching schemes, use the configured port for the particular scheme.
            if (!scheme.equals(reqScheme)) {
                if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(scheme.equals("http") ? httpPort : httpsPort);
                }
                // Else use the port from the current request.
            } else {
                int reqPort = request.getServerPort();

                if ((scheme.equals("http") && (reqPort != DEFAULT_HTTP_PORT))
                        || (scheme.equals("https") && reqPort != DEFAULT_HTTPS_PORT)) {
                    link.append(":");
                    link.append(reqPort);
                }
            }
        }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
        changedScheme = true;
        link.append(scheme);
        link.append("://");
        link.append(request.getServerName());

        if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT))
                || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(scheme.equals("http") ? httpPort : httpsPort);
        }
    }

    if (action != null) {
        // Check if context path needs to be added
        // Add path to absolute links
        if (action.startsWith("/") && includeContext) {
            String contextPath = request.getContextPath();
            if (!contextPath.equals("/")) {
                link.append(contextPath);
            }
        } else if (changedScheme) {

            // (Applicable to Servlet 2.4 containers)
            // If the request was forwarded, the attribute below will be set with the original URL
            String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

            // If the attribute wasn't found, default to the value in the request object
            if (uri == null) {
                uri = request.getRequestURI();
            }

            link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
        }

        // Add page
        link.append(action);
    } else {
        // Go to "same page"
        String requestURI = (String) request.getAttribute("struts.request_uri");

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        if (requestURI == null) {
            requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
        }

        // If neither request attributes were found, default to the value in the request object
        if (requestURI == null) {
            requestURI = request.getRequestURI();
        }

        link.append(requestURI);
    }

    //if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
        buildParametersString(params, link, AMP);
    } else {
        buildParametersString(params, link, "&");
    }

    String result = link.toString();

    if (StringUtils.containsIgnoreCase(result, "<script")) {
        result = StringEscapeUtils.escapeEcmaScript(result);
    }
    try {
        result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not encode the URL for some reason, use it unchanged", ex);
        }
        result = link.toString();
    }

    return result;
}

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//* www. j a  va 2s. c o  m*/
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:org.codeartisans.proxilet.Proxilet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given
 * {@link HttpServletResponse}./*from w  ww. ja v a 2 s . c  o m*/
 *
 * @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
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    // Create a default HttpClient
    HttpClient httpClient;
    httpClient = createClientWithLogin();
    httpMethodProxyRequest.setFollowRedirects(false);

    // 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(HEADER_LOCATION).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + HEADER_LOCATION + " 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) {
            httpServletResponse
                    .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, 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(HEADER_CONTENT_LENGTH, 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")) {
            // proxy servlet does not support chunked encoding
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

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

    // FIXME We should handle both String and bytes response in the same way:
    String response = null;
    byte[] bodyBytes = null;

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

    if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) {
        LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response);
    } else {
        LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode);
    }

    // Send the content to the client
    if (response != null) {
        httpServletResponse.getWriter().write(response);
    } else if (bodyBytes != null) {
        httpServletResponse.getOutputStream().write(bodyBytes);
    } else {
        IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream());
    }
}

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;//from w  w  w. j a  v  a2s. co  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: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");
    }/*from  w w  w  .j a v a  2 s  .  c  om*/

    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.cyclopsgroup.waterview.servlet.ServletRuntimeData.java

/**
 * Default constructor of default web runtime
 *
 * @param request Http request object/*  w  ww.j  av a  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: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 //from   w  w w . j  a va2 s .c  o  m
 * @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();
}