Example usage for java.net SocketTimeoutException getMessage

List of usage examples for java.net SocketTimeoutException getMessage

Introduction

In this page you can find the example usage for java.net SocketTimeoutException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:ch.cyberduck.core.ftp.FTPPath.java

/**
 * @param action Action that needs to open a data connection
 * @return True if action was successful
 * @throws IOException I/O error//w  w  w .  java2 s.  c om
 */
private boolean data(final DataConnectionAction action) throws IOException {
    try {
        // Make sure to always configure data mode because connect event sets defaults.
        if (this.getSession().getConnectMode().equals(FTPConnectMode.PASV)) {
            this.getSession().getClient().enterLocalPassiveMode();
        } else if (this.getSession().getConnectMode().equals(FTPConnectMode.PORT)) {
            this.getSession().getClient().enterLocalActiveMode();
        }
        return action.run();
    } catch (SocketTimeoutException failure) {
        log.warn("Timeout opening data socket:" + failure.getMessage());
        // Fallback handling
        if (Preferences.instance().getBoolean("ftp.connectmode.fallback")) {
            this.getSession().interrupt();
            this.getSession().check();
            try {
                return this.fallback(action);
            } catch (IOException e) {
                this.getSession().interrupt();
                log.warn("Connect mode fallback failed:" + e.getMessage());
                // Throw original error message
                throw failure;
            }
        }
    }
    return false;
}

From source file:vitro.vgw.wsiadapter.WSIAdapterCoap.java

/**
 * WSIAdapter interface/*from   w  ww  .j  a  va  2s.c o m*/
 */

public List<Node> getAvailableNodeList() throws WSIAdapterException {

    logger.info("Getting available nodes...");

    nodesList = new ArrayList<Node>();

    List<String> wsnProxyList = new LinkedList<String>();
    wsnProxyList.add(Network.WLAB_OFFICE_PROXY_ADDRESS);
    wsnProxyList.add(Network.WLAB_LAB_PROXY_ADDRESS);

    DatagramSocket serverSocket = null;
    DatagramSocket clientSocket = null;
    String cmdString = "route";

    for (int i = 0; i < wsnProxyList.size(); i++) {
        try {
            serverSocket = new DatagramSocket(Constants.UDPSHELL_VGW_PORT);

            String hostProxyString = wsnProxyList.get(i);
            InetAddress hostProxy = InetAddress.getByName(hostProxyString);

            clientSocket = new DatagramSocket();
            byte[] bufCmd = new byte[10];
            bufCmd = cmdString.getBytes();
            DatagramPacket outcomingPacket = new DatagramPacket(bufCmd, bufCmd.length, hostProxy,
                    Constants.PROXY_UDPFORWARDER_PORT);
            clientSocket.send(outcomingPacket);

            boolean otherPackets = false;

            serverSocket.setSoTimeout(Constants.PROXY_RESPONSE_TIMEOUT);
            logger.info("Quering " + hostProxyString);
            try {
                byte[] bufAck = new byte[10];
                DatagramPacket ackPacket = new DatagramPacket(bufAck, bufAck.length);
                serverSocket.receive(ackPacket);
                String ackString = new String(ackPacket.getData()).trim();
                if (ackString.equals("ack")) {
                    otherPackets = true;
                }
            } catch (SocketTimeoutException e) {
                logger.warn(e.getMessage());
            }

            serverSocket.setSoTimeout(0);

            while (otherPackets) {
                try {
                    byte[] bufIncoming = new byte[1000];
                    DatagramPacket incomingPacket = new DatagramPacket(bufIncoming, bufIncoming.length);
                    serverSocket.receive(incomingPacket);
                    String currentNodeIP = new String(incomingPacket.getData()).trim();
                    if (!currentNodeIP.equals("end")) {
                        logger.info("Node: " + currentNodeIP);
                        nodesList.add(new Node(currentNodeIP));
                    } else {
                        otherPackets = false;
                        logger.info("No other nodes from " + hostProxyString);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        } catch (UnknownHostException e) {
            logger.warn(e.getMessage() + " is not reachable.");
        } catch (SocketException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
            if (clientSocket != null) {
                clientSocket.close();
            }
        }
    }

    return nodesList;
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Cette mthode permet de tester un fichier par envoi dans un flux TCP du contenu de ce fichier.
 *
 * @param fileForTest/*  www . ja  v a2s .  co m*/
 *            - le fichier  tester
 * @return la chaine "OK" si pas de virus, "le nom du virus" en cas de dtection du virus ou la chaine
 *         retourn par clamav en cas d'erreur clamav
 * @throws ClamAVException
 *             Exception en cas d'erreur
 */
public ClamAvResponse checkByStream(final File fileForTest) throws ClamAVException {

    final StringBuilder resultat = new StringBuilder();
    ClamAvResponse result = null;

    // Rcupration de la taille du fichier
    final long fileForTestSize = fileForTest.length();
    SocketChannel channel = null;
    try {
        ClamAVCheckService.LOGGER.debug("Fichier a tester : '{}' ({} octets)", fileForTest.getAbsolutePath(),
                fileForTestSize);

        // Rcupration du fichier  stream
        final MappedByteBuffer bufFileForTestRead = this.recupFichierStream(fileForTest, fileForTestSize);

        // Ouverture de la socket
        channel = this.openSocket();
        this.readAndSendFile(resultat, fileForTestSize, channel, bufFileForTestRead);

        ClamAVCheckService.LOGGER.debug("Retour ClamAV {}", resultat);
    } catch (final SocketTimeoutException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, ClamAVCheckService.COMMANDE), e);
        result = ClamAvResponse.createTimeoutResponse();
    } catch (final UnknownHostException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, ClamAVCheckService.COMMANDE), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } catch (final IOException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, ClamAVCheckService.COMMANDE), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } finally {
        closeSocket(channel);
    }

    // ce qui veut dire que l'analyse s'est droule sans erreur
    if (result == null && resultat.length() > 0) {
        result = this.traitementReponseClamAV(resultat.toString(), TypeResponse.VIRUS);
    }

    return result;
}

From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(FormDetails... values) {

    String auth = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_AUTH);
    setAuth(auth);//  w w  w .java  2s . co  m

    int total = values.length;
    int count = 1;

    HashMap<String, String> result = new HashMap<String, String>();

    try {
        for (int i = 0; i < total; i++) {
            FormDetails fd = values[i];

            if (isCancelled()) {
                result.put(fd.formID, "cancelled");
                return result;
            }

            publishProgress(fd.formID, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

            String message = "";
            /*
             * Downloaded forms are placed in a staging directory
             * (STALE_FORMS_PATH). Once they are deemed complete, they are
             * atomically moved into the FORMS_PATH. For atomicity, the Form
             * definition file will be stored WITHIN the media folder.
             */

            /* download to here... under STALE_FORMS_PATH */
            File tempFormPath = null;
            /* download to here.. under STALE_FORMS_PATH */
            File tempMediaPath = null;
            /* existing with exactly the same formVersion is here... */
            File existingMediaPath = null;
            /* existing to be moved here... under STALE_FORMS_PATH */
            File staleMediaPath = null;
            /* after downloaded and unpacked, move it here... */
            // File formPath = null; // don't know tableId yet...
            /* after downloaded and unpacked, move it here... */
            // File mediaPath = null; // don't know tableId yet...
            try {
                /*
                 * path to the directory containing the newly downloaded or stale data
                 */
                String baseStaleMediaPath;
                boolean isFramework;
                if (fd.formID.equals(FormsColumns.COMMON_BASE_FORM_ID)) {
                    /*
                     * the Common Javascript Framework is stored in the Framework
                     * directories
                     */
                    baseStaleMediaPath = ODKFileUtils.getStaleFrameworkFolder(getAppName()) + File.separator;
                    isFramework = true;
                } else {
                    baseStaleMediaPath = ODKFileUtils.getStaleFormsFolder(getAppName()) + File.separator;
                    isFramework = false;
                }

                try {
                    // clean up friendly form name...
                    String rootName = fd.formID;
                    if (!rootName.matches("^\\p{L}\\p{M}*(\\p{L}\\p{M}*|\\p{Nd}|_)*$")) {
                        // error!
                        message += appContext.getString(R.string.invalid_form_id, fd.formID, fd.formName);
                        WebLogger.getLogger(appName).e(t,
                                "Invalid form_id: " + fd.formID + " for: " + fd.formName);
                    } else {

                        // figure out what to name this when we move it
                        // out of /odk/appname/tables/tableId/forms/formId...
                        int rev = 2;
                        {
                            // proposed name of form 'media' directory and form
                            // file...
                            String tempMediaPathName = baseStaleMediaPath + rootName;

                            tempMediaPath = new File(tempMediaPathName);
                            tempFormPath = new File(tempMediaPath, ODKFileUtils.FILENAME_XFORMS_XML);

                            while (tempMediaPath.exists()) {
                                try {
                                    if (tempMediaPath.exists()) {
                                        FileUtils.deleteDirectory(tempMediaPath);
                                    }
                                    WebLogger.getLogger(appName).i(t,
                                            "Successful delete of stale directory: " + tempMediaPathName);
                                } catch (IOException ex) {
                                    WebLogger.getLogger(appName).printStackTrace(ex);
                                    WebLogger.getLogger(appName).i(t,
                                            "Unable to delete stale directory: " + tempMediaPathName);
                                }
                                tempMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                                tempMediaPath = new File(tempMediaPathName);
                                tempFormPath = new File(tempMediaPath, ODKFileUtils.FILENAME_XFORMS_XML);
                                rev++;
                            }
                        }

                        // and find a name that any existing directory could be
                        // renamed to... (continuing rev counter)
                        String staleMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                        staleMediaPath = new File(staleMediaPathName);

                        while (staleMediaPath.exists()) {
                            try {
                                if (staleMediaPath.exists()) {
                                    FileUtils.deleteDirectory(staleMediaPath);
                                }
                                WebLogger.getLogger(appName).i(t,
                                        "Successful delete of stale directory: " + staleMediaPathName);
                            } catch (IOException ex) {
                                WebLogger.getLogger(appName).printStackTrace(ex);
                                WebLogger.getLogger(appName).i(t,
                                        "Unable to delete stale directory: " + staleMediaPathName);
                            }
                            staleMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                            staleMediaPath = new File(staleMediaPathName);
                            rev++;
                        }

                        // we have a candidate mediaPath and formPath.
                        // The existing tableId directory is where we
                        // will eventually be placing this data, with
                        // the tableId == the formId from the legacy
                        // pathway.
                        if (isFramework) {
                            existingMediaPath = new File(ODKFileUtils.getAssetsFolder(getAppName()));
                        } else {
                            existingMediaPath = new File(ODKFileUtils.getTablesFolder(getAppName(), fd.formID));
                        }
                        ODKFileUtils.createFolder(existingMediaPath.getAbsolutePath());

                        if (fd.manifestUrl == null) {
                            message += appContext.getString(R.string.no_manifest, fd.formID);
                            WebLogger.getLogger(appName).e(t, "No Manifest for: " + fd.formID);
                        } else {
                            // download the media files -- it is an error if there
                            // are none...
                            String error = downloadManifestAndMediaFiles(tempMediaPath, existingMediaPath, fd,
                                    count, total);
                            if (error != null) {
                                message += error;
                            } else {
                                error = explodeZips(fd, tempMediaPath, count, total);
                                if (error != null) {
                                    message += error;
                                } else if (tempFormPath.exists()) {
                                    message += appContext.getString(R.string.xforms_file_exists,
                                            ODKFileUtils.FILENAME_XFORMS_XML, fd.formID);
                                    WebLogger.getLogger(appName).e(t, ODKFileUtils.FILENAME_XFORMS_XML
                                            + " was present in exploded download of " + fd.formID);
                                } else {
                                    // OK so far -- download the form definition
                                    // file
                                    // note that this is the reverse order from ODK1
                                    downloadXform(fd, tempFormPath,
                                            new File(existingMediaPath, ODKFileUtils.FILENAME_XFORMS_XML));
                                }
                            }
                        }
                    }
                } catch (SocketTimeoutException se) {
                    WebLogger.getLogger(appName).printStackTrace(se);
                    message += se.getMessage();
                } catch (Exception e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    if (e.getCause() != null) {
                        message += e.getCause().getMessage();
                    } else {
                        message += e.getMessage();
                    }
                }

                if (message.equals("")) {
                    // OK. Everything is downloaded, unzipped, and present in the
                    // tempMediaPath
                    // directory... assume everything is OK and just move it...

                    // TODO: with the restructuring of the directory structure, step (3)
                    // won't be necessary
                    // (0) ensure there is no instances folder coming from the server
                    // (affects recovery)
                    // (1) move the existingMediaPath to the staleMediaPath
                    // (2) move the tempMediaPath to the existingMediaPath
                    // (3) move the staleMediaPath/instances folder to the
                    // existingMediaPath/instances.
                    File existingInstances = new File(existingMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);
                    File staleInstances = new File(staleMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);
                    File tempInstances = new File(tempMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);

                    try {
                        // (0) ensure there is no instances folder coming from the server
                        if (tempInstances.exists()) {
                            FileUtils.deleteDirectory(tempInstances);
                        }
                        // (1) move any current directory to the stale tree.
                        if (existingMediaPath.exists()) {
                            FileUtils.moveDirectory(existingMediaPath, staleMediaPath);
                        }
                        // (2) move the temp directory to the current location.
                        FileUtils.moveDirectory(tempMediaPath, existingMediaPath);
                        // (3) move any instances back to the current location.
                        if (staleInstances.exists()) {
                            FileUtils.moveDirectory(staleInstances, existingInstances);
                        }
                    } catch (IOException ex) {
                        WebLogger.getLogger(appName).printStackTrace(ex);
                        message += ex.toString();
                        if (staleMediaPath.exists()) {
                            // try to move this back, since we failed somehow...
                            try {
                                if (existingInstances.exists()) {
                                    FileUtils.moveDirectory(existingInstances, staleInstances);
                                }
                                if (existingMediaPath.exists()) {
                                    FileUtils.deleteDirectory(existingMediaPath);
                                }
                                FileUtils.moveDirectory(staleMediaPath, existingMediaPath);
                            } catch (IOException e) {
                                WebLogger.getLogger(appName).printStackTrace(e);
                            }
                        }
                    }
                }
            } finally {
                if (!message.equalsIgnoreCase("")) {
                    // failure...
                    // we should always delete the temp file / directory.
                    // it is always a new file / directory, so there is no harm
                    // doing this.
                    if (tempMediaPath.exists()) {
                        try {
                            FileUtils.deleteDirectory(tempMediaPath);
                        } catch (IOException e) {
                            WebLogger.getLogger(appName).printStackTrace(e);
                        }
                    }
                } else {
                    message = appContext.getString(R.string.success);
                }
            }
            count++;
            result.put(fd.formID, message);
        }
    } finally {
        Survey.getInstance().setRunInitializationTask(getAppName());
    }
    return result;
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

public XDMResponse sendXCAPRequest(final XDMRequest request) throws XCAPException, SAXException {

    Logger.log("XCAP REQUEST", "------------------------------ Request Begin ------------------------------");
    Logger.log("XCAP REQUEST", "METHOD: " + request.getMethod());
    Logger.log("XCAP REQUEST", "URI: " + request.getURI());
    Logger.log("XCAP REQUEST", "HEADERS: " + request.getHeaders());
    Logger.log("XCAP REQUEST", "TYPE: " + request.getEntityType());
    Logger.log("XCAP REQUEST", "ID: " + request.getIMSEntityId());
    Logger.log("XCAP REQUEST", "BODY: " + request.getBody());
    Logger.log("XCAP REQUEST", "------------------------------ Request End ------------------------------");

    // final String content = "content goes here";
    // final String etag = "etag goes here";
    // final String mimeType = "mime type goes here";

    XDMResponse retValue = null;//from  w  w  w .ja  v a  2  s.  co m

    final HttpClient httpclient = HttpClientHolder.httpClient;

    HttpResponse response = null;
    try {
        // prepare and send first request
        HttpRequestBase httpRequest = createHttpRequest(request);

        prepareUrlConnection(request, httpRequest, lastChallenge.get());
        // HttpURLConnection urlConnection = (HttpURLConnection)
        // url.openConnection();

        /*
         * System.out.println("AllowUserInteraction = " +
         * urlConnection.getAllowUserInteraction());
         * System.out.println("DoInput = " + urlConnection.getDoInput());
         * System.out.println("DoOutput = " + urlConnection.getDoOutput());
         * System.out.println("DefaultUseCaches = " +
         * urlConnection.getDefaultUseCaches());
         * System.out.println("InstanceFollowRedirects = " +
         * urlConnection.getInstanceFollowRedirects());
         * System.out.println("UseCaches = " +
         * urlConnection.getUseCaches());
         * System.out.println("DefaultAllowUserInteraction = " +
         * HttpURLConnection.getDefaultAllowUserInteraction());
         * urlConnection.setDoInput(true); urlConnection.setDoOutput(true);
         * urlConnection.setAllowUserInteraction(true);
         * URLConnection.setDefaultAllowUserInteraction(true);
         */
        printRequest(httpRequest);
        response = httpclient.execute(httpRequest);
        printResponse(response);

        // if (urlConnection.getResponseCode() == 401) {//this line causes
        // additional request to server without auth challenge
        boolean isAuthRequired = response.containsHeader("WWW-Authenticate");
        if (isAuthRequired) {
            String wwwAuthenticateHeader = response.getFirstHeader("WWW-Authenticate").getValue();
            AuthenticationChallenge challenge = (AuthenticationChallenge) ChallengeParser
                    .consume(wwwAuthenticateHeader);
            lastChallenge.set(challenge);

            response.getEntity().consumeContent();

            // prepare and send second request with auth
            HttpRequestBase httpRequestWithAuth = createHttpRequest(request);
            prepareUrlConnection(request, httpRequestWithAuth, challenge);

            printRequest(httpRequest);
            response = httpclient.execute(httpRequestWithAuth);
            printResponse(response);
        }

        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode == HttpStatus.SC_OK || responseCode == 201) {

            final Header etagHeader = response.getFirstHeader("ETag");
            Logger.log(TAG, "etagHeader: " + etagHeader);
            final Header contentTypeHeader = response.getFirstHeader("Content-Type");
            Logger.log(TAG, "contentTypeHeader: " + contentTypeHeader);

            final byte[] content = extractBody(response);
            Logger.log(TAG, "extracted");
            Logger.log(TAG, "BODY: " + (content != null ? new String(content, DEFAULT_CHARSET) : ""));

            retValue = new XDMResponseImpl(content == null ? null : db.parse(new ByteArrayInputStream(content)),
                    content, etagHeader != null ? etagHeader.getValue() : null,
                    contentTypeHeader != null ? contentTypeHeader.getValue() : null);
        } else {
            String reasonPhrase = response.getStatusLine().getReasonPhrase();
            XCAPException xcapException = new XCAPException(responseCode, reasonPhrase);
            if (responseCode == HttpStatus.SC_CONFLICT) {
                // TODO Add XCAPError
            }
            throw xcapException;
        }
    } catch (SocketTimeoutException e) {
        Logger.log(TAG, e.getMessage());
        XCAPException xcapException = new XCAPException(408, "Request Timeout");
        throw xcapException;
    } catch (IOException e) {
        Logger.log(TAG, e.getMessage());
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                if (response.getEntity() != null)
                    response.getEntity().consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return retValue;
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * start download reading task.//from w w  w.  j a v a2s .  c o m
 */
private void startSocketDownloadTask() {

    mDownloadTemporaryPacketSize = 0;

    try {
        final HttpFrame httpFrame = new HttpFrame();

        mTimeStart = System.currentTimeMillis();
        mTimeEnd = 0;

        if (mRepeatWrapper.isFirstDownload()) {
            mRepeatWrapper.setFirstDownloadRepeat(false);
            mRepeatWrapper.setStartDate(mTimeStart);
        }

        final HttpStates httFrameState = httpFrame.decodeFrame(mSocket.getInputStream());

        SpeedTestUtils.checkHttpFrameError(mForceCloseSocket, mListenerList, httFrameState);

        final HttpStates httpHeaderState = httpFrame.parseHeader(mSocket.getInputStream());
        SpeedTestUtils.checkHttpHeaderError(mForceCloseSocket, mListenerList, httpHeaderState);

        SpeedTestUtils.checkHttpContentLengthError(mForceCloseSocket, mListenerList, httpFrame);

        if (httpFrame.getStatusCode() == SpeedTestConst.HTTP_OK
                && httpFrame.getReasonPhrase().equalsIgnoreCase("ok")) {

            mDownloadPckSize = new BigDecimal(httpFrame.getContentLength());

            if (mRepeatWrapper.isRepeatDownload()) {
                mRepeatWrapper.updatePacketSize(mDownloadPckSize);
            }

            downloadReadingLoop();
            mTimeEnd = System.currentTimeMillis();

            closeSocket();

            mReportInterval = false;

            if (!mRepeatWrapper.isRepeatDownload()) {
                closeExecutors();
            }

            final SpeedTestReport report = mSocketInterface.getLiveDownloadReport();

            for (int i = 0; i < mListenerList.size(); i++) {
                mListenerList.get(i).onDownloadFinished(report);
            }

        } else {

            mReportInterval = false;

            for (int i = 0; i < mListenerList.size(); i++) {
                mListenerList.get(i).onDownloadError(SpeedTestError.INVALID_HTTP_RESPONSE,
                        "Error status code " + httpFrame.getStatusCode());
            }

            closeSocket();

            if (!mRepeatWrapper.isRepeatDownload()) {
                closeExecutors();
            }
        }

    } catch (SocketTimeoutException e) {
        mReportInterval = false;
        SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, true, e.getMessage());
        mTimeEnd = System.currentTimeMillis();
        closeSocket();
        closeExecutors();
    } catch (IOException | InterruptedException e) {
        mReportInterval = false;
        catchError(true, e.getMessage());
    }
    mErrorDispatched = false;
}

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

/**
 * scans all GET and POST parameters for Path Traversal vulnerabilities
 *
 * @param msg//from  ww w .  ja va2 s. co  m
 * @param param
 * @param value
 */
@Override
public void scan(HttpMessage msg, String param, String value) {

    try {
        // figure out how aggressively we should test
        int nixCount = 0;
        int winCount = 0;
        int dirCount = 0;
        int localTraversalLength = 0;

        // DEBUG only
        if (log.isDebugEnabled()) {
            log.debug("Attacking at Attack Strength: " + this.getAttackStrength());
        }

        switch (this.getAttackStrength()) {
        case LOW:
            // This works out as a total of 2+2+2+0*4+1 = 7 reqs / param
            nixCount = 2;
            winCount = 2;
            dirCount = 2;
            localTraversalLength = 0;
            break;

        case MEDIUM:
            // This works out as a total of 2+4+4+1*4+1 = 15 reqs / param
            nixCount = 2;
            winCount = 4;
            dirCount = 4;
            localTraversalLength = 1;
            break;

        case HIGH:
            // This works out as a total of 4+8+7+2*4+1 = 28 reqs / param
            nixCount = 4;
            winCount = 8;
            dirCount = 7;
            localTraversalLength = 2;
            break;

        case INSANE:
            // This works out as a total of 6+18+19+4*4+1 = 60 reqs / param
            nixCount = NIX_LOCAL_FILE_TARGETS.length;
            winCount = WIN_LOCAL_FILE_TARGETS.length;
            dirCount = LOCAL_DIR_TARGETS.length;
            localTraversalLength = 4;
            break;

        default:
            // Default to off
        }

        if (log.isDebugEnabled()) {
            log.debug("Checking [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                    + getBaseMsg().getRequestHeader().getURI() + "], parameter [" + param
                    + "] for Path Traversal to local files");
        }

        // Check 1: Start detection for Windows patterns
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        if (inScope(Tech.Windows)) {

            for (int h = 0; h < winCount; h++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, WIN_LOCAL_FILE_TARGETS[h], WIN_PATTERN) || isStop()) {
                    // Dispose all resources
                    // Exit the plugin
                    return;
                }
            }
        }

        // Check 2: Start detection for *NIX patterns
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        if (inScope(Tech.Linux) || inScope(Tech.MacOS)) {

            for (int h = 0; h < nixCount; h++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, NIX_LOCAL_FILE_TARGETS[h], NIX_PATTERN) || isStop()) {
                    // Dispose all resources
                    // Exit the plugin
                    return;
                }
            }
        }

        // Check 3: Detect if this page is a directory browsing component
        // example: https://www.buggedsite.org/log/index.php?dir=C:\
        // note that depending on the AttackLevel, the number of prefixes that we will try
        // changes.
        for (int h = 0; h < dirCount; h++) {

            // Check if a there was a finding or the scan has been stopped
            // if yes dispose resources and exit
            if (sendAndCheckPayload(param, LOCAL_DIR_TARGETS[h], DIR_PATTERN) || isStop()) {
                // Dispose all resources
                // Exit the plugin
                return;
            }
        }

        // Check 4: Start detection for internal well known files
        // try variants based on increasing ../ ..\ prefixes and the presence of the / and \
        // trailer
        // e.g. WEB-INF/web.xml, /WEB-INF/web.xml, ../WEB-INF/web.xml, /../WEB-INF/web.xml, ecc.
        // Both slashed and backslashed variants are checked
        // -------------------------------
        // Currently we've always checked only for J2EE known files
        // and this remains also for this version
        //
        // Web.config for .NET in the future?
        // -------------------------------
        String sslashPattern = "WEB-INF/web.xml";
        // The backslashed version of the same check
        String bslashPattern = sslashPattern.replace('/', '\\');

        if (inScope(Tech.Tomcat)) {

            for (int idx = 0; idx < localTraversalLength; idx++) {

                // Check if a there was a finding or the scan has been stopped
                // if yes dispose resources and exit
                if (sendAndCheckPayload(param, sslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, bslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, '/' + sslashPattern, WAR_PATTERN)
                        || sendAndCheckPayload(param, '\\' + bslashPattern, WAR_PATTERN) || isStop()) {

                    // Dispose all resources
                    // Exit the plugin
                    return;
                }

                sslashPattern = "../" + sslashPattern;
                bslashPattern = "..\\" + bslashPattern;
            }
        }

        // Check 5: try a local file Path Traversal on the file name of the URL (which obviously
        // will not be in the target list above).
        // first send a query for a random parameter value, and see if we get a 200 back
        // if 200 is returned, abort this check (on the url filename itself), because it would
        // be unreliable.
        // if we know that a random query returns <> 200, then a 200 response likely means
        // something!
        // this logic is all about avoiding false positives, while still attempting to match on
        // actual vulnerabilities
        msg = getNewMsg();
        setParameter(msg, param, NON_EXISTANT_FILENAME);

        // send the modified message (with a hopefully non-existent filename), and see what we
        // get back
        try {
            sendAndReceive(msg);

        } catch (SocketException | IllegalStateException | UnknownHostException | IllegalArgumentException
                | InvalidRedirectLocationException | URIException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                        + msg.getRequestHeader().getURI().toString());
            }

            return; // Something went wrong, no point continuing
        }

        // do some pattern matching on the results.
        Pattern errorPattern = Pattern.compile("Exception|Error");
        Matcher errorMatcher = errorPattern.matcher(msg.getResponseBody().toString());

        String urlfilename = msg.getRequestHeader().getURI().getName();

        // url file name may be empty, i.e. there is no file name for next check
        if (!StringUtils.isEmpty(urlfilename)
                && (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK || errorMatcher.find())) {

            if (log.isDebugEnabled()) {
                log.debug("It is possible to check for local file Path Traversal on the url filename on ["
                        + msg.getRequestHeader().getMethod() + "] [" + msg.getRequestHeader().getURI() + "], ["
                        + param + "]");
            }

            String prefixedUrlfilename;

            // for the url filename, try each of the prefixes in turn
            for (String prefix : LOCAL_FILE_RELATIVE_PREFIXES) {

                prefixedUrlfilename = prefix + urlfilename;
                msg = getNewMsg();
                setParameter(msg, param, prefixedUrlfilename);

                // send the modified message (with the url filename), and see what we get back
                try {
                    sendAndReceive(msg);

                } catch (SocketException | IllegalStateException | UnknownHostException
                        | IllegalArgumentException | InvalidRedirectLocationException | URIException ex) {
                    if (log.isDebugEnabled()) {
                        log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage()
                                + " when accessing: " + msg.getRequestHeader().getURI().toString());
                    }

                    continue; // Something went wrong, move to the next prefix in the loop
                }

                // did we get an Exception or an Error?
                errorMatcher = errorPattern.matcher(msg.getResponseBody().toString());
                if ((msg.getResponseHeader().getStatusCode() == HttpStatusCode.OK) && (!errorMatcher.find())) {

                    // if it returns OK, and the random string above did NOT return ok, then
                    // raise an alert
                    // since the filename has likely been picked up and used as a file name from
                    // the parameter
                    bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM, null, param, prefixedUrlfilename, null,
                            msg);

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

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

        // Check 6 for local file names
        // TODO: consider making this check 1, for performance reasons
        // TODO: if the original query was http://www.example.com/a/b/c/d.jsp?param=paramvalue
        // then check if the following gives comparable results to the original query
        // http://www.example.com/a/b/c/d.jsp?param=../c/paramvalue
        // if it does, then we likely have a local file Path Traversal vulnerability
        // this is nice because it means we do not have to guess any file names, and would only
        // require one
        // request to find the vulnerability
        // but it would be foiled by simple input validation on "..", for instance.

    } catch (SocketTimeoutException ste) {
        log.warn("A timeout occurred while checking [" + msg.getRequestHeader().getMethod() + "] ["
                + msg.getRequestHeader().getURI() + "], parameter [" + param + "] for Path Traversal. "
                + "The currently configured timeout is: " + Integer.toString(
                        Model.getSingleton().getOptionsParam().getConnectionParam().getTimeoutInSecs()));

        if (log.isDebugEnabled()) {
            log.debug("Caught " + ste.getClass().getName() + " " + ste.getMessage());
        }

    } catch (IOException e) {
        log.warn("An error occurred while checking [" + msg.getRequestHeader().getMethod() + "] ["
                + msg.getRequestHeader().getURI() + "], parameter [" + param + "] for Path Traversal."
                + "Caught " + e.getClass().getName() + " " + e.getMessage());
    }
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {/*from   www  .  j a v a 2 s .c  o  m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED,
                        request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders,
                        true);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "SocketTimeoutException");
            }
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "ConnectTimeoutException");
            }
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "MalformedURLException");
            }
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                Log.e("Connection Error", " " + e.getMessage());
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "IOException statusCode:" + statusCode + " url:" + request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:watch.oms.omswatch.actioncenter.helpers.WatchPostAsyncTaskHelper.java

/**
 * @param//from   w ww  .  j a  v  a  2  s.  c  o m
 * @param
 * @return
 */
/*private String processPostResponse(String clientTableName, HttpEntity httpEntity){
   String       response          =   null;
   String       jsonString         =   null;
   JSONObject    responseJSONObject   =   null;
           
   try{
 jsonString = EntityUtils.toString(httpEntity);
         
 JSONObject responseWebServiceJSON =  new JSONObject(jsonString);
         
 responseJSONObject = responseWebServiceJSON
       .getJSONObject(OMSMessages.RESPONSE_STRING
             .getValue());
   }catch(JSONException jex){
 if(jex!=null && jex.getMessage().contains("No value for "+(OMSMessages.RESPONSE_STRING.getValue()))){
    Log.d(TAG, "response key is not present. Assuming json response contains data set");
    // This changes are for Oasis Project. # Start
    DataParser dataParser = new DataParser(context);
    // This changes are for Oasis Project. # End
    dataParser.parseAndUpdate(jsonString);
    response = "BLPostSuccess";
 }else{
    Log.e(TAG,
          "Exception occurred while reading the json response. Error is:"
                + jex.getMessage());
 }
 return response = OMSMessages.ACTION_CENTER_FAILURE.getValue();
   } catch (ParseException e) {
 Log.e(TAG,
       "Exception occurred while parsing the json response. Error is:"
             + e.getMessage());
   } catch (IOException e) {
 Log.e(TAG,
       "IO Exception occurred while parsing the json response. Error is:"
             + e.getMessage());
   }
            
   try{
 String code = responseJSONObject
       .getString(OMSMessages.CODE.getValue());
 if (code.equals(OMSMessages.DEFAULT_JSON_CODE.getValue())) {
    Log.i(TAG,
          "Response Message :"
                + responseJSONObject
                      .getString(OMSMessages.MESSAGE
                            .getValue()));
    double processedModifiedDate = responseJSONObject
          .getDouble(OMSMessages.PROCESSED_DATE
                .getValue());
            
    parseJSONObject(jsonPayLoad.toString(),
          OMSDatabaseConstants.STATUS_TYPE_FINISHED,
          processedModifiedDate);
    progressString = context.getResources().getString(
          R.string.post_success);
    response = "BLPostSuccess";
        
 } else {
    Log.e(TAG,
          "Response Message :"
                + responseJSONObject
                      .getString(OMSMessages.MESSAGE
                            .getValue()));
    try {
       Log.e(TAG,
             "Response Message Additional:"
                   + responseJSONObject
                         .getString(OMSMessages.ERROR_ADDITIONAL_MESSAGE
                               .getValue()));
    } catch (JSONException je) {
       // ignore if field is not available
    }
    response = OMSMessages.ACTION_CENTER_FAILURE
          .getValue();
            
            
    ContentValues contentValues = new ContentValues();
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
          OMSDatabaseConstants.ACTION_STATUS_TRIED);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL,
          serviceUrl);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME,
          tableName);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE,
          OMSDatabaseConstants.POST_TYPE_REQUEST);
    contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME,
          schemaName);
 actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues,
          uniqueRowId,configAppId);
 }
   } catch (JSONException e) {
 Log.e(TAG,
       "Exception occurred while updating the Action Queue status."
             + e.getMessage());
 e.printStackTrace();
   } catch (IllegalFormatConversionException e) {
 Log.e(TAG,
       "Exception occurred while updating the Action Queue status."
             + e.getMessage());
 e.printStackTrace();
   }
   return response;
}*/

private String fetchPostResponse(JSONObject jsonPayLoad, String serviceURL) {
    String postResponse = "";
    InputStream inputStream = null;
    OutputStream os = null;
    HttpURLConnection conn = null;
    try {
        /* conn = (HttpURLConnection) AppSecurityAndPerformance.getInstance()
            .getAppGuardSecuredHttpsUrlConnection(serviceURL);*/
        URL urlToRequest = new URL(serviceURL);
        conn = (HttpURLConnection) urlToRequest.openConnection();
        String jsonMessage = jsonPayLoad.toString();
        conn.setReadTimeout(10000 /*milliseconds*/ );
        conn.setConnectTimeout(15000 /* milliseconds */ );
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(jsonMessage.getBytes().length);

        //make some HTTP header nicety
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.setRequestProperty("Content-Encoding", "gzip");

        /*// AppMonitor
           analyzer.startNetworkConnection(serviceURL, OMSMessages.CONNECTION_PREFIX.getValue()
          + connectionID);
           if(conn!=null){
              // AppMonitor
              analyzer.updateConnectionStatus(connectionID, true);
           }
          //open*/
        conn.connect();
        //setup send
        os = new BufferedOutputStream(conn.getOutputStream());
        os.write(jsonMessage.getBytes());
        //clean up
        os.flush();
        inputStream = new BufferedInputStream(conn.getInputStream());
        String serviceResponse = convertStreamToString(inputStream);
        int statusCode = conn.getResponseCode();

        if (statusCode == OMSConstants.STATUSCODE_OK) {
            // AppMonitor
            /*analyzer.receivedConnectionResponse(connectionID,
             conn.getContentLength(),
             OMSDatabaseConstants.POST_TYPE_REQUEST);*/
            if (serviceResponse != null) {
                Log.d(TAG, "PostResponse for HTTPURLConnection:::" + serviceResponse);
                postResponse = processHttpURLConnectionPostResponse(clientTableName, serviceResponse);
                String traceType = OMSApplication.getInstance().getTraceType();
                OMSApplication.getInstance().setTraceType(OMSConstants.TRACE_TYPE_SERVER);
                /*ServerDBUpdateHelper dbhelper = new ServerDBUpdateHelper(context);
                dbhelper.insertCallTraceTypeData(ConsoleDBConstants.CALL_TRACE_TYPE_TABLE, ""+OMSApplication.getInstance().getAppId());*/
                /*Log.i(TAG, "Server Response time::"+OMSApplication.getInstance().getServerProcessDuration());
                Log.i(TAG, "DataBase Response time::"+OMSApplication.getInstance().getDatabaseProcessDuration());
                */ Log.i(TAG, serviceURL + "\n" + "ServerResponseTime::"
                        + OMSApplication.getInstance().getServerProcessDuration() + "\n"
                        + "DataBaseResponseTime::" + OMSApplication.getInstance().getDatabaseProcessDuration());
                OMSApplication.getInstance().setTraceType(traceType);
                return postResponse;
            } else {
                Log.e(TAG, "HttpEntity is NULL :" + jsonPayLoad.toString());
            }

        } else {
            postResponse = OMSMessages.ACTION_CENTER_FAILURE.getValue();
            inputStream = new BufferedInputStream(conn.getInputStream());
            // AppMonitor
            /*analyzer.receivedConnectionResponse(connectionID,
             conn.getContentLength(),
             OMSDatabaseConstants.POST_TYPE_REQUEST);*/
            String result = convertStreamToString(inputStream);
            if (result != null) {
                Log.d(TAG, "Post Service Response :" + result);
                try {
                    JSONObject resultJSON = new JSONObject(result);

                    JSONObject childResponse = resultJSON.getJSONObject("response");
                    if (!childResponse.getString("code").equals("00")) {
                        postResponse = OMSMessages.BL_FAILURE.getValue();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(OMSMessages.ERROR.getValue(), conn.getResponseCode());
                    jsonObject.put(OMSMessages.ERROR_DESCRIPTION.getValue(), conn.getResponseMessage());
                    result = jsonObject.toString();

                } catch (JSONException e) {
                    Log.e(TAG, "JSON Exception occurred in ActionCenterFailure." + e.getMessage());
                    e.printStackTrace();
                }
            }

            parseJSONObject(jsonPayLoad.toString(), OMSDatabaseConstants.STATUS_TYPE_TRIED, 0.0);

            ContentValues contentValues = new ContentValues();
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
                    OMSDatabaseConstants.ACTION_STATUS_TRIED);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE,
                    OMSDatabaseConstants.POST_TYPE_REQUEST);
            contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName);
            actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId);

            //response = OMSMessages.FAILED.getValue();
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "Post Action Failed");
        }

    } catch (SocketTimeoutException se) {
        progressDialog.dismiss();
        Log.e(TAG, "SocketTimeoutException occurred while Posting the Actions" + se.getMessage());
        if (rListener != null) {
            rListener.receiveResult(OMSMessages.ACTION_CENTER_FAILURE.getValue());
        }
        se.printStackTrace();
    } /* catch (ClientProtocolException e) {
        progressDialog.dismiss();
        Log.e(TAG,
         "ClientProtocolException occurred while Posting the Actions"
               + e.getMessage());
        e.printStackTrace();
      }*/
    catch (ProtocolException pe) {
        progressDialog.dismiss();
        postResponse = OMSMessages.BL_FAILURE.getValue();
        Log.e(TAG, "ProtocolException");
    } catch (MalformedURLException mle) {
        progressDialog.dismiss();
        postResponse = OMSMessages.BL_FAILURE.getValue();
        Log.e(TAG, "MalformedURLException");
    }

    catch (IOException e) {
        progressDialog.dismiss();
        Log.e(TAG, "IOException occurred while Posting the Actions" + e.getMessage());
        e.printStackTrace();

        ContentValues contentValues = new ContentValues();
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
                OMSDatabaseConstants.ACTION_STATUS_TRIED);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE, OMSDatabaseConstants.POST_TYPE_REQUEST);
        contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName);
        actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId);
        postResponse = OMSMessages.BL_FAILURE.getValue();
        return postResponse;
    }

    finally {
        //clean up
        try {
            os.close();
        } catch (NullPointerException ex) {
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "NullPointerException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            inputStream.close();
        } catch (NullPointerException ex) {
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "NullPointerException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        conn.disconnect();
    }
    return postResponse;
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * Write download request to server host.
 *
 * @param data HTTP request to send to initiate download process
 *//*from www  .j  a v  a  2s .  c  o  m*/
private void writeDownload(final byte[] data) {

    connectAndExecuteTask(new Runnable() {
        @Override
        public void run() {

            if (mSocket != null && !mSocket.isClosed()) {

                try {
                    if ((mSocket.getOutputStream() != null) && (writeFlushSocket(data) != 0)) {
                        throw new SocketTimeoutException();
                    }
                } catch (SocketTimeoutException e) {
                    SpeedTestUtils.dispatchSocketTimeout(mForceCloseSocket, mListenerList, true,
                            SpeedTestConst.SOCKET_WRITE_ERROR);
                    closeSocket();
                    closeExecutors();
                } catch (IOException e) {
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, e.getMessage());
                    closeExecutors();
                }
            }
        }
    }, true);
}