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:gal.udc.fic.muei.tfm.dap.flipper.web.rest.AccountResource.java

/**
 * POST  /register -> register the user.
 *///  w  ww .  ja  va 2s  .co m
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {
    return userRepository.findOneByLogin(userDTO.getLogin())
            .map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
                                userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
                                userDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort(); // "80"

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:org.infoscoop.web.OpenIDFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    // basically just check for openId parameters
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();

    String reqUri = request.getRequestURI();
    String srvPath = request.getServletPath();
    String actionName = reqUri.substring(reqUri.lastIndexOf("/"), reqUri.length());
    String uid = (String) session.getAttribute("Uid");

    if (uid == null) {

        uid = (String) session.getAttribute("openid");
        if (log.isInfoEnabled())
            log.info(uid + " is logged in by openid.");
        session.setAttribute("Uid", uid);
    }//from  w  w  w  . ja  va  2  s.  c om
    if (uid == null) {
        String host_url = request.getScheme() + "://" + request.getServerName()
                + (request.getServerPort() != 80 && request.getServerPort() != 443
                        ? (":" + request.getServerPort())
                        : "")
                + request.getContextPath();

        if ("/openid_login".equalsIgnoreCase(actionName)) {
            try {
                String returnToUrl = host_url + "/openid_consumer_return";
                String openid = request.getParameter("openid");
                List discoveries = this.consumerMgr.discover(openid);
                DiscoveryInformation discovered = this.consumerMgr.associate(discoveries);

                session.setAttribute("openid-disco", discovered);

                AuthRequest authReq = this.consumerMgr.authenticate(discovered, returnToUrl);

                if (!discovered.isVersion2()) {
                    response.sendRedirect(authReq.getDestinationUrl(true));
                } else {
                    response.setContentType("text/html");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
                    out.println("<form method=\"POST\" name=\"openid-form-redirection\" action=\""
                            + authReq.getOPEndpoint() + "\">");
                    Map pm = authReq.getParameterMap();
                    Iterator keyit = pm.keySet().iterator();
                    Object key;
                    Object value;
                    while (keyit.hasNext()) {
                        key = keyit.next();
                        value = pm.get(key);
                        out.println("<input type=\"hidden\" name=\"" + key + "\" value=\"" + value + "\"/>");
                    }
                    out.println("<button type=\"submit\">Continue...</button>");
                    out.println("</form>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                }
            } catch (OpenIDException e) {
                log.error(e.getMessage(), e);
            }
            return;
        } else if ("/openid_consumer_return".equalsIgnoreCase(actionName)) {
            try {
                ParameterList responselist = new ParameterList(request.getParameterMap());

                DiscoveryInformation discovered = (DiscoveryInformation) session.getAttribute("openid-disco");

                StringBuffer receivingURL = request.getRequestURL();
                String queryString = request.getQueryString();
                if (queryString != null && queryString.length() > 0)
                    receivingURL.append("?").append(request.getQueryString());

                VerificationResult verification = this.consumerMgr.verify(receivingURL.toString(), responselist,
                        discovered);

                // examine the verification result and extract the verified identifier
                Identifier verified = verification.getVerifiedId();
                if (verified != null) {
                    AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();

                    session.setAttribute("openid", authSuccess.getIdentity());
                    session.setAttribute("openid-claimed", authSuccess.getClaimed());
                    System.out.println(authSuccess.getClaimed());
                    response.sendRedirect("."); // success
                }
            } catch (OpenIDException e) {
                log.error(e.getMessage(), e);
                if (this.opIdentifier != null)
                    response.sendRedirect(this.opIdentifier);
                else {
                    String loginUrl = host_url + "/login.jsp";
                    response.sendRedirect(loginUrl);
                }
            }
            return;

        } else if (!isExcludePath(request.getServletPath())) {
            try {
                if (this.opIdentifier != null) {
                    String loginUrl = host_url + "/openid_login?openid="
                            + URLEncoder.encode(this.opIdentifier, "UTF-8");
                    response.sendRedirect(loginUrl);
                } else {
                    String loginUrl = host_url + "/login.jsp";
                    response.sendRedirect(loginUrl);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
            return;
        }
    }
    chain.doFilter(servletRequest, servletResponse);
}

From source file:it.jugpadova.blo.EventBo.java

@RemoteMethod
public void updateBadgePanel(String continent, String country, String jugName, String pastEvents,
        String orderByDate, String jebShowJUGName, String jebShowCountry, String jebShowDescription,
        String jebShowParticipants, String badgeStyle, String locale, String maxResults) {
    WebContext wctx = WebContextFactory.get();
    HttpServletRequest req = wctx.getHttpServletRequest();
    ScriptSession session = wctx.getScriptSession();
    Util util = new Util(session);
    java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.DEFAULT,
            new Locale(locale));
    java.lang.String baseUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();/* www . j a v  a  2  s .  com*/
    it.jugpadova.bean.EventSearch eventSearch = new it.jugpadova.bean.EventSearch();
    eventSearch.setContinent(continent);
    eventSearch.setCountry(country);
    eventSearch.setJugName(jugName);
    eventSearch.setPastEvents(java.lang.Boolean.parseBoolean(pastEvents));
    eventSearch.setOrderByDate(orderByDate);
    if (StringUtils.isNotBlank(maxResults)) {
        try {
            eventSearch.setMaxResults(new Integer(maxResults));
        } catch (NumberFormatException numberFormatException) {
            /* ignore it */
        }
    }
    java.util.List<it.jugpadova.po.Event> events = this.search(eventSearch);
    boolean showJUGName = java.lang.Boolean.parseBoolean(jebShowJUGName);
    boolean showCountry = java.lang.Boolean.parseBoolean(jebShowCountry);
    boolean showDescription = java.lang.Boolean.parseBoolean(jebShowDescription);
    boolean showParticipants = java.lang.Boolean.parseBoolean(jebShowParticipants);
    util.setValue("badgeCode",
            this.getBadgePageCode(baseUrl, continent, country, jugName, pastEvents, orderByDate, jebShowJUGName,
                    jebShowCountry, jebShowDescription, jebShowParticipants, badgeStyle, locale, maxResults));
    util.setValue("badgePreview", this.getBadgeHtmlCode(events, dateFormat, baseUrl, showJUGName, showCountry,
            showDescription, showParticipants, badgeStyle, locale));
}

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

/**
 * GET?/*from   w ww . j a v a2 s  .c  om*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doGet(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 {
        // [draft-ietf-scim-api-13 3.2.2.1. Query Endpoints]
        //  Queries MAY be performed against a SCIM resource object, a resource
        //  type endpoint, or a SCIM server root.

        // ServiceProviderConfigs ??????????

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

        // ??
        @SuppressWarnings("unchecked")
        Map<String, Object> serviceProviderConfigsObject = (Map<String, Object>) context
                .getAttribute("ServiceProviderConfigs");

        try {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, serviceProviderConfigsObject);
            String serviceProviderConfigs = writer.toString();
            serviceProviderConfigs = String.format(serviceProviderConfigs, location);

            response.setContentType("application/scim+json;charset=UTF-8");
            response.setHeader("Location", request.getRequestURL().toString());
            PrintWriter out = response.getWriter();
            out.println(serviceProviderConfigs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

public String getDefServiceLocationUrl(HttpServletRequest req) {
    return "http:" + (req.isSecure() ? "s" : "") + "//" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();//  w  ww .j  a  v a2  s  .  co m
}

From source file:it.jugpadova.blo.EventBo.java

/**
 * Ajax method for a full text search on events.
 *
 * @param searchQuery The text to search
 * @param maxResults The max number of results. No limit if maxResults <= 0.
 *//*  w  ww. j  av a 2  s  .com*/
@RemoteMethod
public void fullTextSearch(String searchQuery, boolean pastEvents, String locale, int maxResults) {
    if (StringUtils.isNotBlank(searchQuery)) {
        WebContext wctx = WebContextFactory.get();
        HttpServletRequest req = wctx.getHttpServletRequest();
        ScriptSession session = wctx.getScriptSession();
        Util util = new Util(session);
        java.text.DateFormat dateFormat = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT,
                new Locale(locale));
        java.lang.String baseUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                + req.getContextPath();
        List<Event> events = null;
        try {
            events = this.search(searchQuery, pastEvents, maxResults);
        } catch (ParseException pex) {
            logger.info("Error parsing query: " + searchQuery);
        } catch (Exception ex) {
            logger.error("Error searching events", ex);
        }
        if (events != null && events.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Event event : events) {
                sb.append("<div>\n");
                sb.append("<div class=\"eventDate\">").append(dateFormat.format(event.getStartDate()))
                        .append("</div>");
                if (event.getOwner() != null) {
                    sb.append("<div class=\"eventSignature\"><a href=\"")
                            .append(event.getOwner().getJug().getWebSiteUrl()).append("\">")
                            .append(event.getOwner().getJug().getName()).append("</a></div>");
                }
                sb.append("<div class=\"eventContent\"><a href=\"").append(baseUrl).append("/event/")
                        .append(event.getId()).append("\">").append(event.getTitle()).append("</a></div>");
                sb.append("</div>\n");
            }
            util.setValue("content_textSearch_result", sb.toString(), false);
        } else {
            util.setValue("content_textSearch_result", "", false);
        }
    }
}

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

/**
 * {@inheritDoc}//from w  ww  .j  av a2s .  c  o  m
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String spDestination;
    String userIdentifier;
    String languages;

    AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
    if (null != service) {
        userIdentifier = service.getUserIdentifier();
        spDestination = service.getSPDestination();
        languages = service.getPreferredLanguages();
    } else {
        userIdentifier = this.userIdentifier;
        if (null != this.spDestination) {
            spDestination = this.spDestination;
        } else {
            spDestination = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort() + request.getContextPath() + this.spDestinationPage;
        }
        languages = this.languages;
    }

    try {
        LOG.debug("discovering the identity...");
        LOG.debug("user identifier: " + userIdentifier);
        List discoveries = this.consumerManager.discover(userIdentifier);
        LOG.debug("associating with the IdP...");
        DiscoveryInformation discovered = this.consumerManager.associate(discoveries);
        request.getSession().setAttribute("openid-disc", discovered);

        LOG.debug("SP destination: " + spDestination);

        AuthRequest authRequest = this.consumerManager.authenticate(discovered,
                getReturnTo(spDestination, request.getSession()), spDestination);

        /*
         * We also piggy-back an attribute fetch request.
         */
        FetchRequest fetchRequest = FetchRequest.createFetchRequest();

        // required attributes
        fetchRequest.addAttribute(OpenIDAXConstants.AX_FIRST_NAME_PERSON_TYPE, true);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_LAST_NAME_PERSON_TYPE, true);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_NAME_PERSON_TYPE, true);

        // optional attributes
        fetchRequest.addAttribute(OpenIDAXConstants.AX_GENDER_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_CODE_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_POSTAL_ADDRESS_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CITY_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_NATIONALITY_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_PLACE_OF_BIRTH_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_BIRTHDATE_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_NUMBER_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_BEGIN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CARD_VALIDITY_END_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_PHOTO_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_RRN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_CERT_AUTHN_TYPE, false);
        fetchRequest.addAttribute(OpenIDAXConstants.AX_AGE_TYPE, false);

        authRequest.addExtension(fetchRequest, "ax");

        /*
         * Piggy back UI Extension if any languages were specified
         */
        if (null != languages) {
            UserInterfaceMessage uiMessage = new UserInterfaceMessage();
            uiMessage.setLanguages(languages);
            authRequest.addExtension(uiMessage, "ui");
        }

        LOG.debug("redirecting to producer with authn request...");
        response.sendRedirect(authRequest.getDestinationUrl(true));
    } catch (OpenIDException e) {
        throw new ServletException("OpenID error: " + e.getMessage(), e);
    }
}

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

public static String buildUrl(String action, HttpServletRequest request, HttpServletResponse response,
        Map 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;//from ww  w.j  a v  a  2  s.  com
        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);
    } else {
        buildParametersString(params, link, "&");
    }

    String result = link.toString();

    while (result.indexOf("<script>") > 0) {
        result = result.replaceAll("<script>", "script");
    }
    try {
        result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
        // Could not encode the URL for some reason
        // Use it unchanged
        result = link.toString();
    }

    return result;
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();// w w  w .j av  a2s  .c  o  m
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}

From source file:org.apache.servicemix.http.processors.ConsumerProcessor.java

private void processGetRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String query = request.getQueryString();
    if (query != null && query.trim().equalsIgnoreCase("wsdl")) {
        String uri = request.getRequestURI();
        if (!uri.endsWith("/")) {
            uri += "/";
        }/*from w w w.  j a  v  a  2 s  .c om*/
        uri += "main.wsdl";
        response.sendRedirect(uri);
        return;
    }
    String path = request.getPathInfo();
    if (path.charAt(0) == '/') {
        path = path.substring(1);
    }

    // Set protocol, host, and port in the component
    HttpComponent comp = (HttpComponent) endpoint.getServiceUnit().getComponent();
    comp.setProtocol(request.getScheme());
    comp.setHost(request.getServerName());
    comp.setPort(request.getServerPort());
    comp.setPath(request.getContextPath());

    // Reload the wsdl
    endpoint.reloadWsdl();

    Node node = (Node) endpoint.getWsdls().get(path);
    generateDocument(response, node);
}