Example usage for java.net SocketException getClass

List of usage examples for java.net SocketException getClass

Introduction

In this page you can find the example usage for java.net SocketException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.googlecode.jcimd.TcpNetConnection.java

@Override
public void run() {
    logger.debug("Ready for replies...");
    Packet reply;/*from   ww  w.ja  v a2s .c o  m*/
    while (true) {
        try {
            reply = this.serializer.deserialize(this.socket.getInputStream());
        } catch (SocketException e) {
            break;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Read exception " + e.getClass().getName() + ": " + e.getCause() + ": "
                        + e.getMessage());
            }
            // since it's a socket exception, let's close without sending a logout operation
            closeSocket();
            break; // get out of this while-loop
        }
        AsyncReply asyncReply = pendingReplies.get("");
        asyncReply.setReply(reply);
    }
}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

@Override
protected boolean connect() {
    // ??, ??//  w w  w. ja v a  2s .  c  o  m
    boolean isSuccess = false;
    try {
        // 
        ftpClient.connect(hostName);
        log.debug("connect hostName:{}", hostName);

        boolean isLoginSuccess = ftpClient.login(userName, password);
        Object[] params = { userName, password, isLoginSuccess };
        log.debug("login:[{}] [{}], {}~~~", params);

        if (isLoginSuccess) {
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.error("FTP ???ReplyCode is:{},will ftpClient.disconnect()", replyCode);
                ftpClient.disconnect();
                return false;
            } else {
                // *******************************************************************************************
                //  ? ?login?, ??FTPClient.
                ftpClient.enterLocalPassiveMode();

                // FTPClientASCII?, ?
                // ??,?,[?login?]. ?????"TYPE I"
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

                String systemName = ftpClient.getSystemName();
                log.debug("ftpClient systemName:[{}]", systemName);

                // FTP??--??
                // FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
                // ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
                // ftpClient.configure(ftpClientConfig);

                // ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);

                //  ?
                isSuccess = true;
            }
        }
    } catch (SocketException e) {
        log.error(e.getClass().getName(), e);
        disconnect();
    } catch (IOException e) {
        disconnect();
        throw new UncheckedIOException(e);
    }
    log.info("connect :{}", isSuccess);
    return isSuccess;
}

From source file:me.schiz.jmeter.protocol.pop3.sampler.POP3Sampler.java

private SampleResult sampleConnect(SampleResult sr) {
    POP3Client client;//from   w w  w.  j a v a2 s .  c  o m

    if (getUseSSL()) {
        client = new POP3SClient(true);
        //      } else if(getUseSTARTTLS()) {
        //         client = new POP3SClient(false);
    } else {
        client = new POP3Client();
    }

    StringBuilder requestBuilder = new StringBuilder();
    try {
        //String request = "CONNECT \n";
        requestBuilder.append("CONNECT\n");
        requestBuilder.append("Host : " + getHostname() + ":" + getPort() + "\n");
        requestBuilder.append("Connect Timeout: " + getConnectionTimeout() + "\n");
        requestBuilder.append("Socket Timeout: " + getSoTimeout() + "\n");
        requestBuilder.append("Client : " + getClient() + "\n");
        if (getUseSSL())
            requestBuilder.append("SSL : true\n");
        else
            requestBuilder.append("SSL : false\n");
        //         if(getUseSTARTTLS())    request += "STARTTLS : true\n";
        //         else request += "STARTTLS : false\n";

        sr.setRequestHeaders(requestBuilder.toString());
        sr.sampleStart();
        client.setConnectTimeout(getConnectionTimeout());
        client.connect(getHostname(), getPort());
        if (client.isConnected()) {
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL())
                protoType = SessionStorage.proto_type.SSL;
            //            if(getUseSSL() && !getUseSTARTTLS()) protoType = SessionStorage.proto_type.SSL;
            //            if(!getUseSSL() && getUseSTARTTLS()) protoType = SessionStorage.proto_type.STARTTLS;

            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            client.setTcpNoDelay(getTcpNoDelay());
            sr.setResponseCode(RC_200);
            sr.setResponseData(client.getReplyString().getBytes());
            sr.setSuccessful(true);
        } else {
            sr.setResponseCode(RC_500);
            sr.setSuccessful(false);
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + client + "` ", se);
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + client + "` ", ioe);
    }
    sr.sampleEnd();
    return sr;
}

From source file:me.schiz.jmeter.protocol.smtp.sampler.SMTPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    SMTPClient client;/*  w w  w  .j a va2 s  . co m*/

    if (getUseSSL()) {
        client = new SMTPSClient(true);
    } else if (getUseSTARTTLS()) {
        client = new SMTPSClient(false);
    } else {
        client = new SMTPClient();
    }

    try {
        String request = "CONNECT \n";
        request += "Host : " + getHostname() + ":" + getPort() + "\n";
        request += "Default Timeout : " + getDefaultTimeout() + "\n";
        request += "Connect Timeout : " + getConnectionTimeout() + "\n";
        request += "So Timeout : " + getSoTimeout() + "\n";
        request += "Client : " + getClient() + "\n";
        if (getUseSSL())
            request += "SSL : true\n";
        else
            request += "SSL : false\n";
        if (getUseSTARTTLS())
            request += "STARTTLS : true\n";
        else
            request += "STARTTLS : false\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        client.connect(getHostname(), getPort());
        if (client.isConnected()) {
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL() && !getUseSTARTTLS())
                protoType = SessionStorage.proto_type.SSL;
            if (!getUseSSL() && getUseSTARTTLS())
                protoType = SessionStorage.proto_type.STARTTLS;

            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            client.setTcpNoDelay(getTcpNoDelay());
            sr.setResponseCode(String.valueOf(client.getReplyCode()));
            sr.setResponseData(client.getReplyString().getBytes());
            setSuccessfulByResponseCode(sr, client.getReplyCode());
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + client + "` ", se);
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + client + "` ", ioe);
    }
    sr.sampleEnd();
    return sr;
}

From source file:me.schiz.jmeter.protocol.imap.sampler.IMAPSampler.java

private SampleResult sampleConnect(SampleResult sr) {
    IMAPClient client;// ww  w .  j  a  v a 2s. c  o m
    if (getUseSSL()) {
        client = new IMAPSClient(true);
    } else {
        client = new IMAPClient();
    }
    try {
        String request = "CONNECT \n";
        request += "Host : " + getHostname() + ":" + getPort() + "\n";
        request += "Default Timeout : " + getDefaultTimeout() + "\n";
        request += "Connect Timeout : " + getConnectionTimeout() + "\n";
        request += "So Timeout : " + getSoTimeout() + "\n";
        request += "Client : " + getClient() + "\n";

        sr.setRequestHeaders(request);
        sr.sampleStart();
        client.setDefaultTimeout(getDefaultTimeout());
        client.setConnectTimeout(getConnectionTimeout());
        if (getLocalAddr().isEmpty())
            client.connect(getHostname(), getPort());
        else
            client.connect(getHostname(), getPort(), InetAddress.getByName(getLocalAddr()), 0);
        if (client.isConnected()) {
            log.info("imap client " + getClient() + " connected from " + client.getLocalAddress() + ":"
                    + client.getLocalPort());
            SessionStorage.proto_type protoType = SessionStorage.proto_type.PLAIN;
            if (getUseSSL())
                protoType = SessionStorage.proto_type.SSL;
            SessionStorage.getInstance().putClient(getSOClient(), client, protoType);
            client.setSoTimeout(getSoTimeout());
            sr.setSuccessful(true);
            sr.setResponseCodeOK();
            sr.setResponseData(client.getReplyString().getBytes());
        } else {
            client.close();
            sr.setSuccessful(false);
            sr.setResponseCode("java.net.ConnectException");
            sr.setResponseMessage("Not connected");
        }
    } catch (SocketException se) {
        sr.setResponseMessage(se.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(se.getClass().getName());
        log.error("client `" + getClient() + "` ", se);
        removeClient();
    } catch (IOException ioe) {
        sr.setResponseMessage(ioe.toString());
        sr.setSuccessful(false);
        sr.setResponseCode(ioe.getClass().getName());
        log.error("client `" + getClient() + "` ", ioe);
        removeClient();
    } finally {
        sr.sampleEnd();
    }
    return sr;
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private boolean dispatchFileWithCache(PublishingFile publishingFile, HttpServletRequest request,
        HttpServletResponse response, FileCache fileCache, long lastModified, String designEncoding,
        String contentType, WGPRequestPath path) throws HttpErrorException, IOException, WGAPIException {
    boolean outputHandled = false;
    byte[] data = fileCache.getFile(publishingFile, lastModified);

    // Serve from cache
    if (data != null) {
        try {/*  w ww .j av  a2 s  .  c om*/
            // B000041DA
            ByteArrayDataSource dataIn = new ByteArrayDataSource(data, publishingFile.getFileName(),
                    contentType);
            writeData(dataIn, request, response, publishingFile.getTextEncoding(), data.length,
                    publishingFile.getSourceHint(), true);
        } catch (java.net.SocketException exc) {
            _log.warn("Dispatch of cached file request failed bc. of socket error: " + exc.getMessage());
        } catch (java.io.IOException exc) {
            if (!exc.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                _log.warn("Dispatch of cached file request failed bc. of IO error: " + exc.getMessage());
            }
        }
        outputHandled = true;
    }

    // Try to put to cache, if below threshold
    else {

        // First test if the file is available
        if (!publishingFile.isAvailable()) {
            throw new HttpErrorException(404, "File not found: " + publishingFile.getName(),
                    path.getDatabaseKey());
        }

        // Look if file size is below cache threshold - if so, collect data and
        // put into cache, then serve
        long threshold = fileCache.getThreshold();
        long fileSize = publishingFile.getFileSize();
        if (fileSize != -1 && threshold >= fileSize) {

            // Put into cache
            InputStream inputStream = publishingFile.getInputStream();
            try {
                ByteArrayOutputStream outCache = new ByteArrayOutputStream((int) fileSize);
                WGUtils.inToOut(inputStream, outCache, 2048);
                data = outCache.toByteArray();
                fileCache.putFile(publishingFile, data, lastModified);
            } catch (java.net.SocketException exc) {
                _log.warn("Caching of file request failed bc. of socket error: " + exc.getMessage());
            } catch (java.io.IOException exc) {
                if (!exc.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                    _log.warn("Caching of file request failed bc. of IO error: " + exc.getMessage());
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                    }
                }
            }

            // Writing from cache to out
            try {
                // B000041DA
                ByteArrayDataSource dataIn = new ByteArrayDataSource(data, publishingFile.getFileName(),
                        contentType);
                if (designEncoding != null) {
                    writeData(dataIn, request, response, designEncoding, data.length,
                            publishingFile.getSourceHint(), true);
                } else {
                    writeData(dataIn, request, response, null, data.length, publishingFile.getSourceHint(),
                            true);
                }
            } catch (java.net.SocketException exc) {
                _log.warn("Dispatch of file request failed bc. of socket error: " + exc.getMessage());
            } catch (java.io.IOException exc) {
                if (!exc.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                    _log.warn("Dispatch of file request failed bc. of IO error: " + exc.getMessage());
                }
            }

            outputHandled = true;

        }
    }
    return outputHandled;
}

From source file:de.innovationgate.wgpublisher.WGPDispatcher.java

private void dispatchPublishingFile(PublishingFile publishingFile, HttpServletRequest request,
        HttpServletResponse response, String textOutputEncoding, FileCache fileCache, WGPRequestPath path)
        throws WGException, HttpErrorException, IOException {

    // Collect HTTP client hints (if enabled)
    ClientHints clientHints = new ClientHints();
    boolean useHttpClientHints = false;
    if (publishingFile.getDatabase() != null) {
        Database database = WGA.get(request, response, getCore()).database(publishingFile.getDatabase());
        if (database instanceof App
                && ((Boolean) database.getPublisherOption(WGACore.DBATTRIB_USE_NONFINAL_HT_FEATURES)) == true) {
            useHttpClientHints = true;//from w  w w  . j  ava  2  s  . c om
        }
    }

    if (useHttpClientHints) {
        String dprStr = request.getHeader("CH-DPR");
        if (dprStr != null) {
            try {
                clientHints.setDevicePixelRatio(Float.valueOf(dprStr));
            } catch (NumberFormatException e) {
                getCore().getLog().warn("Client uses unparseable device pixel ratio: " + dprStr);
            }
        }
    }

    // Optionally select derivate
    Float usedDevicePixelRatio = null;
    try {

        String derivate = request.getParameter(URLPARAM_DERIVATE);
        if (derivate != null) {
            DerivateQuery derivateQuery = getCore().getFileDerivateManager().parseDerivateQuery(derivate);
            if (publishingFile instanceof DocumentPublishingFile) {
                DocumentPublishingFile docPublishingFile = (DocumentPublishingFile) publishingFile;
                WGFileDerivateMetaData derivateMd = docPublishingFile.queryDerivate(derivateQuery, clientHints);
                if (derivateMd != null) {
                    usedDevicePixelRatio = docPublishingFile.getUsedDevicePixelRatio();
                    publishingFile = new DerivatePublishingFile(this, docPublishingFile.getContainer(),
                            derivateMd);

                }
            } else if (!isFallbackToOriginalOnDerivateQuery(derivateQuery, publishingFile)) {
                throw new WGNotSupportedException("Derivate queries are not supported on this file type");
            }

        }

    } catch (WGNotSupportedException e) {
        throw new HttpErrorException(412, e.getMessage(), path.getDatabaseKey());
    } catch (WGInvalidDerivateQueryException e) {
        throw new HttpErrorException(400, "Invalid derivate query: " + e.getMessage(), path.getDatabaseKey());
    } catch (WGFailedDerivateQueryException e) {
        throw new HttpErrorException(412,
                "No derivate of file '" + publishingFile.getFileName() + "' matches the derivate query",
                path.getDatabaseKey());
    }

    // Put out the used device pixel ratio, if any
    if (usedDevicePixelRatio != null) {
        response.setHeader("Vary", "CH-DPR");
        response.setHeader("DPR", usedDevicePixelRatio.toString());
    }

    // Handle browser cache
    long lastModified = determinePublishingFileLastModified(publishingFile, request, response);

    if (browserCacheIsValid(request, lastModified, publishingFile.getETag())) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    } else {
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("ETag", '"' + publishingFile.getETag() + '"');
    }

    // Optionally inject online scaling information to file object
    String maxHeightStr = request.getParameter(URLPARAM_MAXHEIGHT);
    String maxWidthStr = request.getParameter(URLPARAM_MAXWIDTH);
    if (maxHeightStr != null || maxWidthStr != null) {
        try {
            int maxHeight = -1;
            if (maxHeightStr != null) {
                maxHeight = Integer.parseInt(maxHeightStr);
            }
            int maxWidth = -1;
            if (maxWidthStr != null) {
                maxWidth = Integer.parseInt(maxWidthStr);
            }
            publishingFile.setOnlineScaling(maxWidth, maxHeight, clientHints);
        } catch (NumberFormatException e) {
            getCore().getLog().error("Unparseable online scaling metrics", e);
        } catch (Exception e) {
            getCore().getLog().error("Exception setting online scaling information", e);
        }
    }

    // Put out content type
    String contentType = publishingFile.getContentType();
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    response.setContentType(contentType);

    // Content Disposition Header - Either if download forced or a disposition filename has been specified
    Boolean forceDownload = Boolean.parseBoolean(request.getParameter("forcedownload"));
    if (forceDownload) {
        response.setHeader("Content-disposition",
                "attachment" + (publishingFile.getDispositionFileName() != null
                        ? ";filename=" + publishingFile.getDispositionFileName()
                        : ""));
    } else if (publishingFile.getDispositionFileName() != null) {
        response.setHeader("Content-disposition", "inline;filename=" + publishingFile.getDispositionFileName());
    }

    // Allow accept ranges on all CS with optimized file handling and binary responses
    if (publishingFile.isAllowAcceptRanges() && isBinary(request, response)) {
        response.setHeader("Accept-Ranges", "bytes");
    }

    try {
        // Look if file is cached - If so, send it and exit
        if (fileCache != null) {
            boolean outputHandled = dispatchFileWithCache(publishingFile, request, response, fileCache,
                    lastModified, textOutputEncoding, contentType, path);
            if (outputHandled) {
                return;
            }
        }

        // We serve from cache so must retrieve the file. Test for availability now which may load the document.
        if (!publishingFile.isAvailable()) {
            throw new HttpErrorException(404, "File not found: " + publishingFile.getName(),
                    path.getDatabaseKey());
        }

        // File is above threshold and not in cache - serve from database
        writeData(publishingFile, request, response, publishingFile.getTextEncoding(),
                publishingFile.getFileSize(), publishingFile.getSourceHint(),
                publishingFile.isAllowAcceptRanges() && isBinary(request, response));
    } catch (java.net.SocketException exc) {
        _log.warn("Dispatch of file request failed bc. of socket error: " + exc.getMessage());
    } catch (java.io.IOException exc) {
        if (!exc.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
            _log.warn("Dispatch of file request failed bc. of IO error: " + exc.getMessage());
        }
    } catch (HttpErrorException exc) {
        throw exc;
    } catch (Exception exc) {
        _log.error("Exception dispatching file " + publishingFile.getName(), exc);
    }
}

From source file:org.apache.hadoop.hbase.TestIPv6NIOServerSocketChannel.java

/**
 * Checks whether we are effected by the JDK issue on windows, and if so
 * ensures that we are running with preferIPv4Stack=true.
 *//*from ww  w  .  j  a va2  s.com*/
@Test
public void testServerSocket() throws IOException {
    byte[] addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
    InetAddress inetAddr = InetAddress.getByAddress(addr);

    try {
        bindServerSocket(inetAddr);
        bindNIOServerSocket(inetAddr);
        //if on *nix or windows JDK7, both will pass
    } catch (java.net.SocketException ex) {
        //On Windows JDK6, we will get expected exception:
        //java.net.SocketException: Address family not supported by protocol family
        //or java.net.SocketException: Protocol family not supported
        Assert.assertFalse(ex.getClass().isInstance(BindException.class));
        Assert.assertTrue(ex.getMessage().toLowerCase().contains("protocol family"));
        LOG.info("Received expected exception:");
        LOG.info(ex);

        //if this is the case, ensure that we are running on preferIPv4=true
        ensurePreferIPv4();
    }
}

From source file:org.opencms.loader.CmsJspLoader.java

/**
 * Dispatches the current request to the OpenCms internal JSP.<p>
 * //from  w  w w  .  j  a  v  a  2s  .c  om
 * @param controller the current controller
 * 
 * @return the content of the processed JSP
 * 
 * @throws ServletException if inclusion does not work
 * @throws IOException if inclusion does not work
 */
protected byte[] dispatchJsp(CmsFlexController controller) throws ServletException, IOException {

    // get request / response wrappers
    CmsFlexRequest f_req = controller.getCurrentRequest();
    CmsFlexResponse f_res = controller.getCurrentResponse();

    try {
        f_req.getRequestDispatcher(controller.getCmsObject().getSitePath(controller.getCmsResource()))
                .include(f_req, f_res);
    } catch (SocketException e) {
        // uncritical, might happen if client (browser) does not wait until end of page delivery
        LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
    }

    byte[] result = null;
    HttpServletResponse res = controller.getTopResponse();

    if (!controller.isStreaming() && !f_res.isSuspended()) {
        try {
            // if a JSP error page was triggered the response will be already committed here
            if (!res.isCommitted() || m_errorPagesAreNotCommitted) {

                // check if the current request was done by a workplace user
                boolean isWorkplaceUser = CmsWorkplaceManager.isWorkplaceUser(f_req);

                // check if the content was modified since the last request
                if (controller.isTop() && !isWorkplaceUser
                        && CmsFlexController.isNotModifiedSince(f_req, controller.getDateLastModified())) {
                    if (f_req.getParameterMap().size() == 0) {
                        // only use "expires" header on pages that have no parameters,
                        // otherwise some browsers (e.g. IE 6) will not even try to request 
                        // updated versions of the page
                        CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                m_clientCacheMaxAge);
                    }
                    res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return null;
                }

                // get the result byte array
                result = f_res.getWriterBytes();
                HttpServletRequest req = controller.getTopRequest();
                if (req.getHeader(CmsRequestUtil.HEADER_OPENCMS_EXPORT) != null) {
                    // this is a non "on-demand" static export request, don't write to the response stream
                    req.setAttribute(CmsRequestUtil.HEADER_OPENCMS_EXPORT,
                            new Long(controller.getDateLastModified()));
                } else if (controller.isTop()) {
                    // process headers and write output if this is the "top" request/response                                  
                    res.setContentLength(result.length);
                    // check for preset error code
                    Integer errorCode = (Integer) req.getAttribute(CmsRequestUtil.ATTRIBUTE_ERRORCODE);
                    if (errorCode == null) {
                        // set last modified / no cache headers only if this is not an error page
                        if (isWorkplaceUser) {
                            res.setDateHeader(CmsRequestUtil.HEADER_LAST_MODIFIED, System.currentTimeMillis());
                            CmsRequestUtil.setNoCacheHeaders(res);
                        } else {
                            // set date last modified header                        
                            CmsFlexController.setDateLastModifiedHeader(res, controller.getDateLastModified());
                            if ((f_req.getParameterMap().size() == 0)
                                    && (controller.getDateLastModified() > -1)) {
                                // only use "expires" header on pages that have no parameters
                                // and that are cachable (i.e. 'date last modified' is set)
                                // otherwise some browsers (e.g. IE 6) will not even try to request 
                                // updated versions of the page
                                CmsFlexController.setDateExpiresHeader(res, controller.getDateExpires(),
                                        m_clientCacheMaxAge);
                            }
                        }
                        // set response status to "200 - OK" (required for static export "on-demand")
                        res.setStatus(HttpServletResponse.SC_OK);
                    } else {
                        // set previously saved error code
                        res.setStatus(errorCode.intValue());
                    }
                    // process the headers
                    CmsFlexResponse.processHeaders(f_res.getHeaders(), res);
                    res.getOutputStream().write(result);
                    res.getOutputStream().flush();
                }
            }
        } catch (IllegalStateException e) {
            // uncritical, might happen if JSP error page was used
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        } catch (SocketException e) {
            // uncritical, might happen if client (browser) does not wait until end of page delivery
            LOG.debug(Messages.get().getBundle().key(Messages.LOG_IGNORING_EXC_1, e.getClass().getName()), e);
        }
    }

    return result;
}

From source file:org.zaproxy.zap.extension.ascanrules.CommandInjectionPlugin.java

/**
 * Tests for injection vulnerabilities with the given payloads.
 *
 * @param paramName the name of the parameter that will be used for testing for injection
 * @param value the value of the parameter that will be used for testing for injection
 * @param targetCount the number of requests for normal payloads
 * @param blindTargetCount the number of requests for blind payloads
 * @param osPayloads the normal payloads
 * @param blindOsPayloads the blind payloads
 * @return {@code true} if the vulnerability was found, {@code false} otherwise.
 *///ww  w.  jav  a2s . c  om
private boolean testCommandInjection(String paramName, String value, int targetCount, int blindTargetCount,
        Map<String, Pattern> osPayloads, List<String> blindOsPayloads) {
    // Start testing OS Command Injection patterns
    // ------------------------------------------
    String payload;
    String paramValue;
    Iterator<String> it = osPayloads.keySet().iterator();
    List<Long> responseTimes = new ArrayList<>(targetCount);
    long elapsedTime;

    // -----------------------------------------------
    // Check 1: Feedback based OS Command Injection
    // -----------------------------------------------
    // try execution check sending a specific payload
    // and verifying if it returns back the output inside
    // the response content
    // -----------------------------------------------
    for (int i = 0; it.hasNext() && (i < targetCount); i++) {
        payload = it.next();
        if (osPayloads.get(payload).matcher(getBaseMsg().getResponseBody().toString()).find()) {
            continue; // The original matches the detection so continue to next
        }

        HttpMessage msg = getNewMsg();
        paramValue = value + payload;
        setParameter(msg, paramName, paramValue);

        if (log.isDebugEnabled()) {
            log.debug("Testing [" + paramName + "] = [" + paramValue + "]");
        }

        try {
            // Send the request and retrieve the response
            try {
                sendAndReceive(msg, false);
            } catch (SocketException ex) {
                if (log.isDebugEnabled())
                    log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                            + msg.getRequestHeader().getURI().toString()
                            + "\n The target may have replied with a poorly formed redirect due to our input.");
                continue; // Something went wrong, move to next payload iteration
            }
            elapsedTime = msg.getTimeElapsedMillis();
            responseTimes.add(elapsedTime);

            // Check if the injected content has been evaluated and printed
            String content = msg.getResponseBody().toString();
            Matcher matcher = osPayloads.get(payload).matcher(content);
            if (matcher.find()) {
                // We Found IT!
                // First do logging
                if (log.isDebugEnabled()) {
                    log.debug("[OS Command Injection Found] on parameter [" + paramName + "] with value ["
                            + paramValue + "]");
                }

                // Now create the alert message
                this.bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, msg.getRequestHeader().getURI().toString(),
                        paramName, paramValue, null, matcher.group(), msg);

                // All done. No need to look for vulnerabilities on subsequent
                // payloads on the same request (to reduce performance impact)
                return true;
            }

        } catch (IOException ex) {
            // Do not try to internationalise this.. we need an error message in any event..
            // if it's in English, it's still better than not having it at all.
            log.warn("Command Injection vulnerability check failed for parameter [" + paramName
                    + "] and payload [" + payload + "] due to an I/O error", ex);
        }

        // Check if the scan has been stopped
        // if yes dispose resources and exit
        if (isStop()) {
            // Dispose all resources
            // Exit the plugin
            return false;
        }
    }

    // -----------------------------------------------
    // Check 2: Time-based Blind OS Command Injection
    // -----------------------------------------------
    // Check for a sleep shell execution according to
    // the previous experimented request time execution
    // It uses deviations and average for the real delay checking...
    // 7? =   99.9999999997440% of the values
    // so response time should be less than 7*stdev([normal response times])
    // Math reference: http://www.answers.com/topic/standard-deviation
    // -----------------------------------------------
    double deviation = getResponseTimeDeviation(responseTimes);
    double lowerLimit = (deviation >= 0) ? getResponseTimeAverage(responseTimes) + TIME_STDEV_COEFF * deviation
            : timeSleepSeconds * 1000;

    it = blindOsPayloads.iterator();

    String timeSleepSecondsStr = String.valueOf(timeSleepSeconds);
    for (int i = 0; it.hasNext() && (i < blindTargetCount); i++) {
        HttpMessage msg = getNewMsg();
        payload = it.next();

        paramValue = value + payload.replace("{0}", timeSleepSecondsStr);
        setParameter(msg, paramName, paramValue);

        if (log.isDebugEnabled()) {
            log.debug("Testing [" + paramName + "] = [" + paramValue + "]");
        }

        try {
            // Send the request and retrieve the response
            try {
                sendAndReceive(msg, false);
            } catch (SocketException ex) {
                if (log.isDebugEnabled())
                    log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                            + msg.getRequestHeader().getURI().toString()
                            + "\n The target may have replied with a poorly formed redirect due to our input.");
                continue; // Something went wrong, move to next blind iteration
            }
            elapsedTime = msg.getTimeElapsedMillis();

            // Check if enough time has passed
            if (elapsedTime >= lowerLimit && elapsedTime > timeSleepSeconds * 1000) {

                // Probably we've to confirm it launching again the query
                // But we arise the alert directly with MEDIUM Confidence...

                // We Found IT!
                // First do logging
                if (log.isDebugEnabled()) {
                    log.debug("[Blind OS Command Injection Found] on parameter [" + paramName + "] with value ["
                            + paramValue + "]");
                }

                // Now create the alert message
                this.bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, msg.getRequestHeader().getURI().toString(),
                        paramName, paramValue, null, null, msg);

                // All done. No need to look for vulnerabilities on subsequent
                // payloads on the same request (to reduce performance impact)
                return true;
            }

        } catch (IOException ex) {
            // Do not try to internationalise this.. we need an error message in any event..
            // if it's in English, it's still better than not having it at all.
            log.warn("Blind Command Injection vulnerability check failed for parameter [" + paramName
                    + "] and payload [" + payload + "] due to an I/O error", ex);
        }

        // Check if the scan has been stopped
        // if yes dispose resources and exit
        if (isStop()) {
            // Dispose all resources
            // Exit the plugin
            return false;
        }
    }
    return false;
}