Example usage for java.net SocketException SocketException

List of usage examples for java.net SocketException SocketException

Introduction

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

Prototype

public SocketException(String msg) 

Source Link

Document

Constructs a new SocketException with the specified detail message.

Usage

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout)
        throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    HttpClientParams.setRedirecting(httpParams, true);

    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override/*from  ww  w . j a  va2  s  . co m*/
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketTimeoutException e) {
        e = new SocketTimeoutException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout,
        Boolean pRedirect) throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    if (!pRedirect) {
        HttpClientParams.setRedirecting(httpParams, false);
    }/*from  w ww.  j a v  a  2s.  c om*/
    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}

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

/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error
 * was a socket error rather than often more serious exceptions like
 * disk errors.//  ww w .j  a v a 2  s .  co  m
 */
private static IOException ioeToSocketException(IOException ioe) {

    if (ioe.getClass().equals(IOException.class)) {
        // "se" could be a new class in stead of SocketException.
        final IOException se = new SocketException("Original Exception : " + ioe);
        se.initCause(ioe);
        /*
         * Change the stacktrace so that original trace is not truncated
         * when printed.
         */
        se.setStackTrace(ioe.getStackTrace());
        return se;
    }
    // otherwise just return the same exception.
    return ioe;
}

From source file:org.jnode.net.ipv4.tcp.TCPControlBlock.java

/**
 * Wait for incoming requests/*from  w  w  w. j a v  a2s . c  o  m*/
 *
 * @throws SocketException
 */
public synchronized void appListen() throws SocketException {
    if (!isState(TCPS_CLOSED)) {
        throw new SocketException("Invalid connection state " + getStateName());
    }
    setState(TCPS_LISTEN);
}

From source file:org.jnode.net.ipv4.tcp.TCPControlBlock.java

/**
 * Active connect to a foreign address. This method blocks until the
 * connection has been established.//from   w  ww . j a  v a2  s.  c o  m
 *
 * @throws SocketException
 */
public synchronized void appConnect(IPv4Address fAddr, int fPort) throws SocketException {
    if (!isState(TCPS_CLOSED)) {
        throw new SocketException("Invalid connection state " + getStateName());
    }
    super.connect(getLocalAddress(), fAddr, fPort);
    for (int attempt = 0; attempt < TCP_MAXCONNECT; attempt++) {
        try {
            // Send the SYN
            sendSYN();
            // Update the state
            setState(TCPS_SYN_SENT);
            // Wait for an ESTABLISHED state
            waitUntilState(TCPS_ESTABLISHED, timeout);
            // Check for reset condition
            if (isRefused()) {
                throw new ConnectException("Connection refused");
            }
            if (DEBUG) {
                log.debug("Connected to " + fAddr + ":" + fPort);
            }
            return;
        } catch (TimeoutException ex) {
            // Ignore and just try again
        }
    }
    // Not succeeded to connect
    throw new ConnectException("Connection request timeout");
}

From source file:org.gbif.harvest.digir.DigirHarvesterTest.java

/**
 * Test method for {@link org.gbif.harvest.biocase.BiocaseHarvester#search(String, String, String, String, String,
 * String, Boolean, String, int)}. Difference from test3Harvest() being that this mocks the RequestUtils execute
 * method always returning a SocketException instead of a Diagnostics object.
 *//*from   w w w .  j  ava  2s .  c  o  m*/
@Ignore("Because it waits for 3 minutes after each exception")
public void testHarvestWithSocketException() throws IOException, OperationStoppedException, HarvesterException {
    // Mocked SAXException
    RequestUtils requestUtils = mock(RequestUtils.class);
    when(requestUtils.executeGetRequestAndReturnDiagnostics(anyString(), any(ProtocolTypeEnum.class),
            any(RequestResponseWriterManager.class))).thenThrow(new SocketException("Socket Exception"));

    harvester = new DigirHarvester(new TemplateUtils(), fileUtils, requestUtils, new DigesterUtils(fileUtils),
            gbifLogger);

    // runs through all name ranges, doesn't just terminate first time it encounters a SAXException
    harvester.search(TEST_RESOURCE, TEST_DESTINATION, targetDirectory.getAbsolutePath(), TEST_PROTOCOL,
            TEST_MAX_SEARCH_RESPONSE, TEST_TARGET_COUNT);

    // collect search request files (so initial + 5 retries = 6 max)
    String[] files = targetDirectory.list(new PrefixFileFilter(Constants.SEARCH_REQUEST_FILENAME));
    assertEquals(6, files.length);

    // there were no search response files because the exception was thrown each time
    files = targetDirectory.list(new PrefixFileFilter(Constants.SEARCH_RESPONSE_FILENAME));
    assertEquals(0, files.length);
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.workers.CheckinWorker.java

/**
 * Upload the given source file to the Team Foundation Server. If an
 * exception is thrown, no clean-up of the source file is performed (the
 * caller must handle this condition).//from  ww w  . j a  va 2s. com
 *
 * @param uploadFile
 *        the compressed or uncompressed local file that will be sent to the
 *        server, which must exist (must not be <code>null</code> or empty)
 * @param parts
 *        partially populated content parts. The Range part and file part
 *        are filled in for each chunk here.
 * @param contentType
 *        the type of the file content (compressed or uncompressed).
 * @throws CoreCancelException
 *         if the upload was cancelled by the user via the
 *         {@link TaskMonitor}.
 */
private void retryableUpload(final File uploadFile, final Part[] parts, final String contentType)
        throws SocketException, CoreCancelException {
    Check.notNull(uploadFile, "uploadFile"); //$NON-NLS-1$
    Check.notNullOrEmpty(parts, "parts"); //$NON-NLS-1$
    Check.notNullOrEmpty(contentType, "contentType"); //$NON-NLS-1$

    PostMethod method = null;
    InputStream fileStream = null;
    BufferedInputStream bufferedStream = null;

    try {
        final long uploadFileLength = uploadFile.length();
        long uploadFilePos = 0;
        boolean aChunkHasBeenRetried = false;

        fileStream = new FileInputStream(uploadFile);
        bufferedStream = new BufferedInputStream(fileStream);

        do {
            final long bytesLeft = uploadFileLength - uploadFilePos;
            final long chunkSize = 0 < MAX_CHUNK_SIZE && MAX_CHUNK_SIZE < bytesLeft ? MAX_CHUNK_SIZE
                    : bytesLeft;

            final CancellableFilePart filePart;
            if (chunkSize == uploadFileLength) {
                /*
                 * The calculated chunk size can be equal to the size of the
                 * file only if:
                 *
                 * (1) this is the first iteration of the loop, and
                 *
                 * (2) the chunk size is zero, i.e. chunked upload is not
                 * allowed, or the entire file is small and fits in a single
                 * chunk.
                 *
                 * In this case we use the full file upload not bothering
                 * with chunks at all.
                 */

                filePart = new CancellableFilePart("content", "item", uploadFile, contentType, null); //$NON-NLS-1$ //$NON-NLS-2$
                /*
                 * NOTE We construct the file part in a special way so the
                 * character set is never sent to the server (TFS can't
                 * handle that header, and it causes an internal server
                 * error). If we construct the CancellableFilePart object
                 * with a null charset, the header is still included, and
                 * its value is the default charset. If we invoke
                 * setCharSet() with null, the header is never supplied
                 * (which is what we desire).
                 *
                 * Also, we use the file name "item" to match Visual
                 * Studio's implementation. Sending the actual file name
                 * doesn't seem to hurt, but appears to be ignored by the
                 * server.
                 */
                filePart.setCharSet(null);
            } else {
                /*
                 * Chunked upload. We mark the current position in the
                 * buffered stream to allow re-sending of the chunk in case
                 * redirection or authentication is required on the lower
                 * HTTP Client level.
                 */

                bufferedStream.mark(MAX_CHUNK_SIZE);
                filePart = new CancellableChunkPart(uploadFile, bufferedStream, contentType, chunkSize);
            }

            /*
             * The Range part. NOTE There must be the extra newline after
             * the range line, or it will cause an internal server error.
             */
            parts[5] = new StringPart(VersionControlConstants.RANGE_FIELD, "bytes=" //$NON-NLS-1$
                    + uploadFilePos + "-" //$NON-NLS-1$
                    + (uploadFilePos + chunkSize - 1) + "/" //$NON-NLS-1$
                    + uploadFile.length() + "\r\n", //$NON-NLS-1$
                    partCharSet);

            /*
             * The File part. It could be the entire file or its chunk.
             */
            parts[6] = filePart;

            int attempt = 0;

            do {
                attempt++;

                if (TaskMonitorService.getTaskMonitor().isCanceled()) {
                    throw new CoreCancelException();
                }

                try {
                    final String messageFormat = MessageFormat.format(
                            Messages.getString("CheckinWorker.UploadFileProgressFormat_SKIPVALIDATE"), //$NON-NLS-1$
                            change.getServerItem());
                    final FileProcessingProgressMonitorAdapter monitor = new FileProcessingProgressMonitorAdapter(
                            userCancellationMonitor, uploadFilePos, uploadFileLength, messageFormat);

                    TaskMonitorService.pushTaskMonitor(monitor);

                    /*
                     * Connect to the server.
                     */
                    method = client.beginUploadRequest();

                    /*
                     * Create the multi-part request entity that wraps our
                     * parts.
                     */
                    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

                    client.executeUploadRequest(method);

                    /*
                     * Uploaded successfully
                     */
                    uploadFilePos += chunkSize;
                    break;

                } catch (final SocketException e) {
                    if (attempt == MAX_CHUNK_RETRY_ATTEMPTS || chunkSize == uploadFileLength || client
                            .getServiceLevel().getValue() < WebServiceLevel.TFS_2012_QU1_1.getValue()) {
                        /*
                         * We're here because:
                         *
                         * i. We already have retried the chunk allowed
                         * number of times or
                         *
                         * ii. It does not make sense to retry because the
                         * server does not support chunk retrying or
                         *
                         * iii. We're uploading the entire file as one chunk
                         *
                         * The caller might wish to retry the entire file
                         */
                        throw e;
                    } else {
                        /*
                         * Let's retry this chunk. On the pre-Dev12.M46
                         * servers that could cause VersionControlException
                         * on the same or the following chunks and we'll
                         * need to retry the entire file.
                         */
                        aChunkHasBeenRetried = true;
                    }
                } catch (final VersionControlException e) {
                    if (aChunkHasBeenRetried) {
                        /*
                         * Most likely this is a pre-Dev12.M46 server that
                         * does not support chunk retrying.
                         *
                         * TODO. We might need to perform some deeper
                         * analysis of the exception as VS does.
                         */
                        throw new SocketException(
                                "This version of the TFS Server does not support chunk retrying."); //$NON-NLS-1$
                    } else {
                        throw e;
                    }
                } finally {
                    if (method != null) {
                        client.finishUploadRequest(method);
                    }

                    TaskMonitorService.popTaskMonitor();
                }
            } while (true);

        } while (uploadFilePos < uploadFileLength);
    } catch (final CancellableFilePart.SendDataCancellationException e) {
        /*
         * This is thrown by the CancellableFilePart because it must throw
         * an IOException to work inside Commons HTTP. Treat like a normal
         * cancel exception.
         */
        throw new CoreCancelException();
    } catch (final SocketException e) {
        /*
         * Throw this so it can be caught and the upload retried.
         */
        throw e;
    } catch (final IOException e) {
        throw new VersionControlException(e);
    } finally {
        if (bufferedStream != null) {
            try {
                bufferedStream.close();
            } catch (final IOException e) {
                // Do nothing.
            }
        }

        /*
         * Surprisingly the BufferedStream class does not close the
         * underlying file stream. So, we have to close it explicitly.
         */
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (final IOException e) {
                // Do nothing.
            }
        }
    }
}

From source file:org.jnode.net.ipv4.tcp.TCPControlBlock.java

/**
 * Active close the connection by the application.
 */// w w w .  j a v  a  2 s . c o  m
public/* synchronized */void appClose() throws SocketException {
    if (DEBUG) {
        if (log.isDebugEnabled()) {
            log.debug("active close state=" + getStateName());
        }
    }

    try {
        switch (curState) {
        case TCPS_SYN_RECV:
        case TCPS_ESTABLISHED:
            sendFIN();
            setState(TCPS_FIN_WAIT_1);

            // this is blocking the closing of the socket/output stream
            // - Martin Husted Hartvig 01/03/2005
            // the waitUntilState have to rethinked
            // waitUntilState(TCPS_CLOSED, 0);
            break;
        case TCPS_SYN_SENT:
        case TCPS_LISTEN:
            setState(TCPS_CLOSED);
            break;
        case TCPS_CLOSE_WAIT:
            sendFIN();
            setState(TCPS_LAST_ACK);
            waitUntilState(TCPS_CLOSED, 0);
            break;
        case TCPS_CLOSED:
            // Ignore
            break;
        default:
            throw new SocketException("Illegal state in close (" + getStateName() + ")");
        }
    } catch (TimeoutException ex) {
        throw (SocketException) new SocketException("Timeout").initCause(ex);
    }
    if (isReset()) {
        throw new SocketException("Connection reset");
    }
}

From source file:org.jnode.net.ipv4.tcp.TCPControlBlock.java

/**
 * Send data to the foreign side. This method can split-up the data in
 * chunks and blocks until there is space in the send buffer to hold the
 * data.//  www . java  2 s . c om
 *
 * @param data
 * @param offset
 * @param length
 * @throws SocketException
 */
public void appSendData(byte[] data, int offset, int length) throws SocketException {
    if (DEBUG) {
        log.debug("appSendData(data, " + offset + ", " + length + ")");
    }
    if (!isState(TCPS_ESTABLISHED) && !isState(TCPS_CLOSE_WAIT)) {
        throw new SocketException("Illegal state to send data: " + getStateName());
    }
    if (offset < 0) {
        throw new IllegalArgumentException("offset " + offset);
    }
    if (length < 0) {
        throw new IllegalArgumentException("length " + length);
    }
    final int mss = outChannel.getMss();
    while (length > 0) {
        final int chunk = Math.min(length, mss);
        // Create the TCP header
        final TCPHeader hdr = createOutgoingTCPHeader(TCPF_ACK, inChannel.getRcvNext());
        // Create the IP header
        final IPv4Header ipHdr = createOutgoingIPv4Header();
        // Send the chunk of data
        outChannel.send(ipHdr, hdr, data, offset, chunk);
        // Update length & offset
        offset += chunk;
        length -= chunk;
    }
}

From source file:com.microsoft.tfs.core.httpclient.HttpConnection.java

/**
 * Sets <code>SO_TIMEOUT</code> value directly on the underlying
 * {@link Socket socket}. This method does not change the default read
 * timeout value set via {@link HttpConnectionParams}.
 *
 * @param timeout/* w  ww. java2s.  co m*/
 *        the timeout value
 * @throws SocketException
 *         - if there is an error in the underlying protocol, such as a TCP
 *         error.
 * @throws IllegalStateException
 *         if not connected
 *
 * @since 3.0
 */
public void setSocketTimeout(final int timeout) throws SocketException, IllegalStateException {
    assertOpen();
    if (socket != null) {
        LOG.trace("Set socket timeout to " + timeout);
        try {
            socket.setSoTimeout(timeout);
        } catch (final Throwable t) {
            LOG.debug("", t);
            if (t instanceof SocketException) {
                throw (SocketException) t;
            }
            if (t instanceof IllegalStateException) {
                throw (IllegalStateException) t;
            }
            throw new SocketException(t.getMessage());
        }
    }
}