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:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*from w ww.  j a va  2s  . co m*/

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        method = new ExtendedGetMethod();
    else
        method = new ExtendedPostMethod();

    method.setDecompress(false);

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
        connectionHeader = connectionHeader.toLowerCase();
        if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0)
            connectionHeader = null;
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    long contentLength = -1;
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if (dontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr))
            contentLength = request.getContentLength();

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                method.setRequestHeader(lhdr, val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
            }
        }
    }

    // Proxy headers
    method.setRequestHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor)
        method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());

    if (method instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) method)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80)
        url.append(":" + httpRequest.getServerPort());
    if (httpRequest.getServletPath() != null) {
        url.append(httpRequest.getServletPath());
        method.setPath(httpRequest.getServletPath());
        if (httpRequest.getQueryString() != null) {
            url.append("?" + httpRequest.getQueryString());
            method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString());
        }
    }
    hostConfiguration.setHost(new URI(url.toString(), true));

    // SoapUI.log("PROXY to:" + url);

    monitor.fireBeforeProxy(request, response, method, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody()));
    capturedData.setResponseContent(new String(method.getDecompressedResponseBody()));

    monitor.fireAfterProxy(request, response, method, capturedData);

    if (!response.isCommitted()) {
        StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
        // capturedData = null;

        // copy headers to response
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (String name : responseHeaders.keySet()) {
            for (String header : responseHeaders.get(name))
                httpResponse.addHeader(name, header);
        }

        IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());
    }

    synchronized (this) {
        if (checkContentType(method)) {
            monitor.addMessageExchange(capturedData);
        }
    }
}

From source file:org.exoplatform.outlook.OutlookServiceImpl.java

/**
 * Inits the document link./* w w w . j av a 2  s . c o m*/
 *
 * @param siteType the site type
 * @param driveName the drive name
 * @param portalName the portal name
 * @param nodeURI the node URI
 * @param node the node
 * @throws OutlookException the outlook exception
 */
protected void initDocumentLink(SiteType siteType, String driveName, String portalName, String nodeURI,
        HierarchyNode node) throws OutlookException {
    // WebDAV URL
    initWebDAVLink(node);

    // Portal URL
    // Code adapted from ECMS's PermlinkActionComponent.getPermlink()

    String npath = node.getPath().replaceAll("/+", "/");

    String path = new StringBuilder().append(driveName).append(npath).toString();
    PortalRequestContext portalRequest = Util.getPortalRequestContext();
    if (portalRequest != null) {
        NodeURL nodeURL = portalRequest.createURL(NodeURL.TYPE);
        NavigationResource resource = new NavigationResource(siteType, portalName, nodeURI);
        nodeURL.setResource(resource);
        nodeURL.setQueryParameterValue("path", path);

        HttpServletRequest request = portalRequest.getRequest();
        try {
            URI requestUri = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), null, null, null);

            StringBuilder url = new StringBuilder();
            url.append(requestUri.toASCIIString());
            url.append(nodeURL.toString());
            node.setUrl(url.toString());
        } catch (URISyntaxException e) {
            throw new OutlookException("Error creating server URL " + request.getRequestURI().toString(), e);
        }
    } else {
        LOG.warn("Portal request not found. Node URL will be its WebDAV link. Node: " + node.getPath());
        node.setUrl(node.getWebdavUrl());
    }
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given {@link HttpServletResponse}
 * //from w ww  . j  a 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
 * @param digest
 * @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, ProxyInfo proxyInfo)
        throws IOException, ServletException {

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

    httpMethodProxyRequest.setFollowRedirects(false);

    InputStream inputStreamServerResponse = null;
    ByteArrayOutputStream baos = null;

    try {

        // //////////////////////////
        // Execute the request
        // //////////////////////////

        int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

        onRemoteResponse(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(Utils.LOCATION_HEADER).getValue();

            if (stringLocation == null) {
                throw new ServletException("Recieved status code: " + stringStatusCode + " but no "
                        + Utils.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(
                    Utils.getProxyHostAndPort(proxyInfo) + proxyInfo.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(Utils.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(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && header.getValue().toLowerCase().contains("gzip"))
                continue;
            else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            //                else if (header.getName().equalsIgnoreCase(Utils.HTTP_HEADER_WWW_AUTHENTICATE))
            //                    continue;                
            else
                httpServletResponse.setHeader(header.getName(), header.getValue());
        }

        // ///////////////////////////////////
        // Send the content to the client
        // ///////////////////////////////////

        inputStreamServerResponse = httpMethodProxyRequest.getResponseBodyAsStream();

        if (inputStreamServerResponse != null) {
            byte[] b = new byte[proxyConfig.getDefaultStreamByteSize()];

            baos = new ByteArrayOutputStream(b.length);

            int read = 0;
            while ((read = inputStreamServerResponse.read(b)) > 0) {
                baos.write(b, 0, read);
                baos.flush();
            }

            baos.writeTo(httpServletResponse.getOutputStream());
        }

    } catch (HttpException e) {
        if (LOGGER.isLoggable(Level.SEVERE))
            LOGGER.log(Level.SEVERE, "Error executing HTTP method ", e);
    } finally {
        try {
            if (inputStreamServerResponse != null)
                inputStreamServerResponse.close();
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing request input stream ", e);
            throw new ServletException(e.getMessage());
        }

        try {
            if (baos != null) {
                baos.flush();
                baos.close();
            }
        } catch (IOException e) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, "Error closing response stream ", e);
            throw new ServletException(e.getMessage());
        }

        httpMethodProxyRequest.releaseConnection();
    }
}

From source file:org.sakaiproject.entitybroker.util.http.EntityHttpServletRequest.java

/**
 * Set all the values from a request on this request object and set this request
 * as the one which the values were copied from
 * @param req any request/*from   w w  w . j a  va 2s.c om*/
 */
public void setRequestValues(HttpServletRequest req) {
    if (req == null) {
        throw new IllegalArgumentException("request cannot be null");
    }
    // get the collections of values out
    Enumeration<String> attribNames = req.getAttributeNames();
    while (attribNames.hasMoreElements()) {
        String name = (String) attribNames.nextElement();
        Object obj = req.getAttribute(name);
        if (obj != null) {
            attributes.put(name, obj);
        }
    }
    Cookie[] ck = req.getCookies();
    if (ck != null) {
        for (int i = 0; i < ck.length; i++) {
            cookies.add(ck[i]);
        }
    }
    Enumeration<String> headerNames = req.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        Enumeration<String> henum = req.getHeaders(name);
        Vector<String> v = new Vector<String>(1);
        while (henum.hasMoreElements()) {
            String h = henum.nextElement();
            v.add(h);
        }
    }
    for (Entry<String, String[]> entry : (Set<Entry<String, String[]>>) req.getParameterMap().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    // get the basic values out
    this.locale = req.getLocale();
    this.method = req.getMethod();
    this.contentType = req.getContentType();
    this.characterEncoding = req.getCharacterEncoding() == null ? "UTF-8" : req.getCharacterEncoding();
    this.contentLength = req.getContentLength();

    this.contextPath = req.getContextPath();
    this.pathInfo = req.getPathInfo();
    this.queryString = req.getQueryString();
    this.requestURI = req.getRequestURI();
    this.servletPath = req.getServletPath();

    this.scheme = req.getScheme();
    this.protocol = req.getProtocol();
    this.serverName = req.getServerName();
    this.serverPort = req.getServerPort();
    this.remoteAddr = req.getRemoteAddr();
    this.remoteHost = req.getRemoteHost();

    this.realDispatcher = true;
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {//  w  w w .j a  v  a2  s  . co m
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.apache.hadoop.hdfs.server.datanode.DatanodeJspHelper.java

static void generateFileChunks(JspWriter out, HttpServletRequest req, Configuration conf)
        throws IOException, InterruptedException {
    long startOffset = 0;
    int datanodePort = 0;

    final String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    final String nnAddr = req.getParameter(JspHelper.NAMENODE_ADDRESS);
    if (nnAddr == null) {
        out.print(JspHelper.NAMENODE_ADDRESS + " url param is null");
        return;/* w w  w.j a  va2s  .  c  om*/
    }
    final String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null)
        namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    final String filename = JspHelper
            .validatePath(StringEscapeUtils.unescapeHtml(req.getParameter("filename")));
    if (filename == null) {
        out.print("Invalid input (filename absent)");
        return;
    }

    final Long blockId = JspHelper.validateLong(req.getParameter("blockId"));
    if (blockId == null) {
        out.print("Invalid input (blockId absent)");
        return;
    }

    final DFSClient dfs = getDFSClient(ugi, nnAddr, conf);

    String bpid = null;
    Token<BlockTokenIdentifier> blockToken = BlockTokenSecretManager.DUMMY_TOKEN;
    List<LocatedBlock> blks = dfs.getNamenode().getBlockLocations(filename, 0, Long.MAX_VALUE)
            .getLocatedBlocks();
    if (blks == null || blks.size() == 0) {
        out.print("Can't locate file blocks");
        dfs.close();
        return;
    }

    boolean needBlockToken = conf.getBoolean(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY,
            DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_DEFAULT);

    for (int i = 0; i < blks.size(); i++) {
        if (blks.get(i).getBlock().getBlockId() == blockId) {
            bpid = blks.get(i).getBlock().getBlockPoolId();
            if (needBlockToken) {
                blockToken = blks.get(i).getBlockToken();
            }
            break;
        }
    }

    final Long genStamp = JspHelper.validateLong(req.getParameter("genstamp"));
    if (genStamp == null) {
        out.print("Invalid input (genstamp absent)");
        return;
    }

    long blockSize = 0;
    final String blockSizeStr = req.getParameter("blockSize");
    if (blockSizeStr == null) {
        out.print("Invalid input (blockSize absent)");
        return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    final int chunkSizeToView = JspHelper.string2ChunkSizeToView(req.getParameter("chunkSizeToView"),
            getDefaultChunkSize(conf));

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0)
        startOffset = 0;
    else
        startOffset = Long.parseLong(startOffsetStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
        out.print("Invalid input (datanodePort absent)");
        return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);
    out.print("<h3>File: ");
    JspHelper.printPathWithLinks(filename, out, namenodeInfoPort, tokenString, nnAddr);
    out.print("</h3><hr>");
    String parent = new File(filename).getParent();
    JspHelper.printGotoForm(out, namenodeInfoPort, tokenString, parent, nnAddr);
    out.print("<hr>");
    out.print("<a href=\"/browseDirectory.jsp?dir=" + URLEncoder.encode(parent, "UTF-8") + "&namenodeInfoPort="
            + namenodeInfoPort + JspHelper.getDelegationTokenUrlParam(tokenString)
            + JspHelper.getUrlParam(JspHelper.NAMENODE_ADDRESS, nnAddr)
            + "\"><i>Go back to dir listing</i></a><br>");
    out.print("<a href=\"#viewOptions\">Advanced view/download options</a><br>");
    out.print("<hr>");

    String authority = req.getServerName() + ":" + req.getServerPort();
    String nextUrl = generateLinksForAdjacentBlock(NEXT_BLOCK, authority, datanodePort, startOffset,
            chunkSizeToView, blockSize, blockId, genStamp, dfs, filename, conf, req.getScheme(), tokenString,
            namenodeInfoPort, nnAddr);
    if (nextUrl != null) {
        out.print("<a href=\"" + nextUrl + "\">View Next chunk</a>&nbsp;&nbsp;");
    }

    String prevUrl = generateLinksForAdjacentBlock(PREV_BLOCK, authority, datanodePort, startOffset,
            chunkSizeToView, blockSize, blockId, genStamp, dfs, filename, conf, req.getScheme(), tokenString,
            namenodeInfoPort, nnAddr);
    if (prevUrl != null) {
        out.print("<a href=\"" + prevUrl + "\">View Prev chunk</a>&nbsp;&nbsp;");
    }

    out.print("<hr>");
    out.print("<textarea cols=\"100\" rows=\"25\" wrap=\"virtual\" style=\"width:100%\" READONLY>");
    try {
        JspHelper.streamBlockInAscii(new InetSocketAddress(req.getServerName(), datanodePort), bpid, blockId,
                blockToken, genStamp, blockSize, startOffset, chunkSizeToView, out, conf, dfs.getConf(), dfs,
                getSaslDataTransferClient(req));
    } catch (Exception e) {
        out.print(e);
    }
    out.print("</textarea>");
    dfs.close();
}

From source file:com.juicioenlinea.application.servlets.particular.DemandaServlet.java

private void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession(false);
    Particular demandante = (Particular) session.getAttribute("usuario");

    StringBuilder sb = new StringBuilder();
    sb.append("<response>");

    if (request.getContentLengthLong() > 104857600) {
        response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
        sb.append("<message>");
        sb.append(new Messages().getClientMessage("error", 7));
        sb.append("</message>");
    } else {/*from  w ww .  j a  v  a  2  s.  co  m*/
        // Campos formulario
        UploadFile uf = new UploadFile(request);

        String numeroDemanda = ToolBox.createNumeroDemanda();
        String nombre = uf.getFormField("nombre");
        String descripcion = uf.getFormField("descripcion");
        int estado = 1;
        System.out.println("Archivos: " + uf.getFiles().size());
        // Validamos datos
        if (numeroDemanda == null || numeroDemanda.equals("") || nombre == null || nombre.equals("")
                || descripcion == null || descripcion.equals("") || uf.getFiles().size() < 1) {

            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            sb.append("<message>");
            sb.append(new Messages().getClientMessage("error", 1));
            sb.append("</message>");
        } else {
            // Tiempo
            Date fechaCreacion = ToolBox.dateFormat(new Date());

            // Obtenemos 3 magistrados con menos demandas asignadas
            MagistradoDAO madao = new MagistradoDAO();
            Set<Magistrado> magistrados = madao.get3Magistrado();

            if (magistrados == null || magistrados.size() < 3) {
                magistrados = madao.readAll3();
            }

            // Objetos de TIEMPO
            Tiempo tiempo = new Tiempo();
            tiempo.setFechaCreacion(fechaCreacion);
            TiempoDAO tidao = new TiempoDAO();

            // Objeto de DEMANDA
            Demanda demanda = new Demanda();
            demanda.setParticularByIdParticularDemandante(demandante);
            demanda.setTiempo(tiempo);
            demanda.setNumeroDemanda(numeroDemanda);
            demanda.setNombreDemanda(nombre);
            demanda.setDescripcion(descripcion);
            demanda.setEstado(estado);
            demanda.setMagistrados(magistrados);

            DemandaDAO dedao = new DemandaDAO();
            if (!tidao.create(tiempo) || !dedao.create(demanda)) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                sb.append("<message>");
                sb.append(new Messages().getClientMessage("error", 4));
                sb.append("</message>");
            } else {
                // Guardamos los documentos
                String sala = "s1";
                String uri = request.getScheme() + "://" + request.getServerName() + ":"
                        + request.getServerPort() + "/" + this.getServletContext().getContextPath();

                for (FileItem fi : uf.getFiles()) {
                    // Documentos
                    Documento documento = new Documento();
                    documento.setDemanda(demanda);
                    documento.setParticular(demandante);
                    documento.setFechaCarga(ToolBox.dateFormat(new Date()));
                    documento.setRuta(
                            uf.saveFile(fi, this.getServletContext().getRealPath(""), sala, numeroDemanda));
                    documento.setEstado(1);
                    documento.setNombre(fi.getName());

                    DocumentoDAO dodao = new DocumentoDAO();

                    if (!dodao.create(documento)) {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        sb.append("<message>");
                        sb.append(new Messages().getClientMessage("error", 7));
                        sb.append("</message>");
                        break;
                    }
                }

                //Mail mail = new Mail(demandante.getCatalogousuarios().getCorreo(), "Demanda creada", "Nmero de demanda: " + numeroDemanda);
                Mail mail = new Mail("eddy_wallace@hotmail.com", "Demanda creada",
                        "Nmero de demanda: " + numeroDemanda);

                if (!mail.sendMail()) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("error", 8));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                } else {
                    sb.append("<message>");
                    sb.append(new Messages().getClientMessage("ok", 5));
                    sb.append("</message>");

                    sb.append("<redirect>");
                    sb.append(uri).append("/aplicacion/particular/Demanda?action=demandasHechas");
                    sb.append("</redirect>");
                }
            }
        }
    }

    sb.append("</response>");
    PrintWriter pw = response.getWriter();
    pw.write(sb.toString());
}

From source file:com.zimbra.soap.SoapServlet.java

private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int len = req.getContentLength();
    byte[] buffer;
    boolean isResumed = true;

    // resuming from a Jetty Continuation does *not* reset the HttpRequest's input stream -
    // therefore we store the read buffer in the Continuation, and use the stored buffer
    // if we're resuming
    buffer = (byte[]) req.getAttribute("com.zimbra.request.buffer");
    if (buffer == null) {
        isResumed = false;/*from   ww w .j  a v  a  2 s  .c om*/

        // Look up max request size
        int maxSize = 0;
        try {
            maxSize = Provisioning.getInstance().getLocalServer()
                    .getIntAttr(Provisioning.A_zimbraSoapRequestMaxSize, 0);
        } catch (ServiceException e) {
            ZimbraLog.soap.warn("Unable to look up %s.  Not limiting the request size.",
                    Provisioning.A_zimbraSoapRequestMaxSize, e);
        }
        if (maxSize <= 0) {
            maxSize = Integer.MAX_VALUE;
        }

        // Read the request
        boolean success;
        if (len > maxSize) {
            success = false;
        } else {
            BufferStream bs = null;

            try {
                bs = new BufferStream(len, maxSize, maxSize);
                int in = (int) bs.readFrom(req.getInputStream(), len >= 0 ? len : Integer.MAX_VALUE);

                if (len > 0 && in < len)
                    throw new EOFException("SOAP content truncated " + in + "!=" + len);
                success = in <= maxSize;
                buffer = bs.toByteArray();
            } finally {
                ByteUtil.closeStream(bs);
            }
        }

        // Handle requests that exceed the size limit
        if (!success) {
            String sizeString = (len < 0 ? "" : " size " + len);
            String msg = String.format("Request%s exceeded limit of %d bytes set for %s.", sizeString, maxSize,
                    Provisioning.A_zimbraSoapRequestMaxSize);
            ServiceException e = ServiceException.INVALID_REQUEST(msg, null);
            ZimbraLog.soap.warn(null, e);
            Element fault = SoapProtocol.Soap12.soapFault(e);
            Element envelope = SoapProtocol.Soap12.soapEnvelope(fault);
            sendResponse(req, resp, envelope);
            return;
        }

        req.setAttribute("com.zimbra.request.buffer", buffer);
    }

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put(SERVLET_CONTEXT, getServletContext());
    context.put(SERVLET_REQUEST, req);
    context.put(SERVLET_RESPONSE, resp);

    try {
        Boolean isAdminReq = isAdminRequest(req);
        context.put(IS_ADMIN_REQUEST, isAdminReq);
    } catch (ServiceException se) {
        ZimbraLog.soap.warn("unable to determine isAdminReq", se);
    }

    // setup IPs in the context and add to logging context
    RemoteIP remoteIp = new RemoteIP(req, ZimbraServlet.getTrustedIPs());
    context.put(SoapEngine.SOAP_REQUEST_IP, remoteIp.getClientIP());
    context.put(SoapEngine.ORIG_REQUEST_IP, remoteIp.getOrigIP());
    context.put(SoapEngine.REQUEST_IP, remoteIp.getRequestIP());
    remoteIp.addToLoggingContext();

    //checkAuthToken(req.getCookies(), context);
    context.put(SoapEngine.REQUEST_PORT, req.getServerPort());
    Element envelope = null;
    try {
        envelope = mEngine.dispatch(req.getRequestURI(), buffer, context);
        if (context.containsKey(INVALIDATE_COOKIES)) {
            ZAuthToken.clearCookies(resp);
        }
    } catch (Throwable e) {
        if (e instanceof OutOfMemoryError) {
            Zimbra.halt("handler exception", e);
        }

        if (ZimbraLog.soap.isTraceEnabled() && !context.containsKey(SoapEngine.SOAP_REQUEST_LOGGED)) {
            ZimbraLog.soap.trace(!isResumed ? "C:\n%s" : "C: (resumed)\n%s",
                    new String(buffer, Charsets.UTF_8));
        }

        // don't interfere with Jetty Continuations -- pass the exception right up
        if (e.getClass().getName().equals("org.eclipse.jetty.continuation.ContinuationThrowable"))
            throw (Error) e;

        ZimbraLog.soap.warn("handler exception", e);
        Element fault = SoapProtocol.Soap12.soapFault(ServiceException.FAILURE(e.toString(), e));
        envelope = SoapProtocol.Soap12.soapEnvelope(fault);
    }

    if (ZimbraLog.soap.isTraceEnabled()) {
        ZimbraLog.soap.trace("S:\n%s", envelope.prettyPrint());
    }
    sendResponse(req, resp, envelope);
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information.//  w  ww  . j a v a  2 s  . com
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}