Example usage for java.net ConnectException getMessage

List of usage examples for java.net ConnectException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.evolveum.midpoint.model.test.AbstractModelIntegrationTest.java

protected DummyGroup getDummyGroup(String dummyInstanceName, String name) {
    DummyResource dummyResource = DummyResource.getInstance(dummyInstanceName);
    try {/*from www.  j  a v  a2 s . co m*/
        return dummyResource.getGroupByName(name);
    } catch (ConnectException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.webcurator.core.archive.oms.OMSUploadUtil.java

/**
 * Add content (a file really) to the OMS repository based upon the current sessionid
 * @param content The stream to read from
 * @param name The name to call the file in the OMS
 * @param actualSize The size of the stream
 * @return The MD5 of the file//from  w  w w. j a v a  2  s.co  m
 * @throws OMSUploadException
 */
public String uploadContent(InputStream content, String name, long actualSize) throws OMSUploadException {
    String msg = "";
    String md5 = "";
    try {
        int pos = 0;
        int part = 0;
        int parts = 0;
        long totalSize = 0;

        URL url = null;
        HttpURLConnection urlConn = null;
        boolean finished = false;
        MessageDigest md = MessageDigest.getInstance("MD5");

        for (; !finished; pos += partSize, part++) {
            long contentLength = Math.min(partSize, actualSize - (partSize * part));
            // URL of servlet.
            url = new URL(this.url);
            // URL connection channel.
            urlConn = getConnection(url, 5);
            // Let the run-time system (RTS) know that we want input.
            urlConn.setDoInput(true);
            // Let the RTS know that we want to do output.
            urlConn.setDoOutput(true);
            // No caching, we want the real thing.
            urlConn.setUseCaches(false);
            // Specify the content type.
            urlConn.setRequestProperty("Content-Type", "application/octet-stream");
            urlConn.setRequestProperty("Content-Length", "" + contentLength);
            urlConn.setRequestProperty("filename", toSafeFileName(name));
            urlConn.setRequestProperty("realfilename", name);
            urlConn.setRequestProperty("sessionid", sessionId);
            urlConn.setRequestProperty("applet", "true");
            urlConn.setRequestMethod("POST");
            // Send POST output.
            urlConn.setRequestProperty("part.number", part + "");
            urlConn.setRequestProperty("part.size", contentLength + "");
            OutputStream out = null;
            try {
                for (int u = 0; (out == null) && (u < 5); u++) {
                    try {
                        out = urlConn.getOutputStream();
                    } catch (ConnectException e) {
                        log.error("Connection Problem", e);
                    }
                }
                parts++;
                int sent = 0;
                byte[] buff = new byte[16384];
                int bytes = content.read(buff);
                while (bytes > 0) {
                    out.write(buff, 0, bytes);
                    md.update(buff, 0, bytes);
                    totalSize += bytes;
                    sent += bytes;
                    int toRead = (int) contentLength - sent;
                    if (toRead > 0) {
                        bytes = content.read(buff, 0, Math.min(buff.length, toRead));
                    } else {
                        bytes = 0;
                        if (totalSize >= actualSize) {
                            finished = true;
                        }
                    }
                }
            } catch (IOException e) {
                throw new OMSUploadException(e);
            } finally {
                out.flush();
                out.close();
            }
            // Get response data.
            BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            msg = input.readLine();
            input.close();
            urlConn.disconnect();
            if (!msg.equals("SUCCESS")) {
                throw new OMSUploadException("Upload failed - return code: " + msg);
            } else {
                log.debug("OMS returned SUCCESS");
            }
        }
        content.close();
        md5 = toHexString(md.digest());
        urlConn = getConnection(url, 5);
        // Let the run-time system (RTS) know that we want input.
        urlConn.setDoInput(true);
        urlConn.setRequestProperty("Content-Type", "application/octet-stream");
        urlConn.setRequestProperty("Content-Length", "0");
        urlConn.setRequestProperty("MD5-hash", md5);
        urlConn.setRequestProperty("filename", toSafeFileName(name));
        urlConn.setRequestProperty("realfilename", name);
        urlConn.setRequestProperty("sessionid", sessionId);
        urlConn.setRequestProperty("applet", "true");
        urlConn.setRequestMethod("POST");
        urlConn.setRequestProperty("part.number", parts + "");
        urlConn.setRequestProperty("part.size", totalSize + "");
        urlConn.setRequestProperty("total.size", totalSize + "");
        // Get response data.
        BufferedReader input2 = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        msg = input2.readLine();
        input2.close();
        urlConn.disconnect();
    } catch (Exception e) {
        msg = "Error: " + e.getMessage();
        throw new OMSUploadException(msg, e);
    }

    return md5;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient.java

/**
 * Creates an HTTP download connection item for the given download spec,
 * initialized for downloading a file from the TFS. The object returned is
 * an Apache HttpClient GetMethod object whose status code has been
 * validated to be HttpStatus.SC_OK. This means you can read the response
 * from this stream using getResponseBodyAsStream() or
 * getResponseBodyAsString() (or other methods). You must pass this method
 * object back into this class's finishDownloadRequest() when you are
 * finished.// ww  w.  ja v  a 2  s  .  co  m
 * <p>
 * If a TFS download proxy was set during the construction of TFSConnection,
 * it is contacted here. Otherwise, the host passed to the TFSConnection
 * constructor is contacted.
 * <p>
 * <b>NOTE:</b> This method is not synchronized (but is thread-safe) because
 * doing so would allow deadlock during concurrent downloads. When there are
 * more downloader threads than available connections in the HttpClient's
 * pool, a thread may sleep in the HttpClient code (while holding a lock on
 * this object) until a connection becomes available, which can only happen
 * if other threads finish using their connections (which they can't because
 * they need to acquire a lock on this object to do so).
 *
 * @param spec
 *        the spec object that describes the item being downloaded (not
 * @return a new GetMethod object that has been validated to have status
 *         HttpStatus.SC_OK. The caller can read its data using
 *         getResponseBodyAsStream or getResponseBodyAsString(), then close
 *         the stream with releaseConnection().
 * @throws MalformedURLException
 *         if an error occured building the URL from the spec and the
 *         existing connection information.
 * @throws DownloadProxyException
 *         if a download proxy was used and the HTTP GET failed for any
 *         reason.
 * @throws SocketException
 *         if a socket error occurred. This method handles most IO
 *         exceptions by rethrowing them as {@link VersionControlException}
 *         s, but {@link SocketException}s are thrown so callers can detect
 *         connection resets and retry their operation. Retrying
 *         automatically inside this method is problematic because it knows
 *         nothing about higher-level state that may need reset for a retry.
 */
private GetMethod beginDownloadRequest(final DownloadSpec spec)
        throws MalformedURLException, DownloadProxyException, SocketException {
    Check.notNull(spec, "spec"); //$NON-NLS-1$

    final TFProxyServerSettings tfProxyServerSettings = connection.getTFProxyServerSettings();

    String tfsProxyURL = null;
    if (tfProxyServerSettings.isAvailable()) {
        tfsProxyURL = tfProxyServerSettings.getURL();
    }

    /*
     * A note about URL encoding / escaping:
     *
     * The download spec that TFS gives us contains some already-escaped
     * values. If we pass that string into a URI class constructor or
     * resolve it against a URI, the escape characters will be
     * double-escaped. So we deal with URI strings only here.
     */

    String downloadURIString = null;
    String downloadHost = null;

    /*
     * URI Encoding Special Notice
     *
     * The download spec is a URI query string
     * ("name=value&zap=baz&other=stuff") but some of the query arguments
     * are already URI encoded ("s=before%2Fafter") and some of them are not
     * ("cp=/tfs/Collection Name With Spaces/")!
     *
     * To avoid breaking the string down into each args and encoding just
     * the ones we know are usually unencoded ("cp", which is the project
     * collection name), we call a special utility method in URIUtils which
     * exists pretty much just for this one case.
     */

    final String reEncodedDownloadSpec = URIUtils.encodeQueryIgnoringPercentCharacters(spec.getQueryString());

    if (tfsProxyURL == null) {
        /*
         * Use the existing server settings.
         */
        final URI uri = getDownloadURI();

        downloadURIString = uri.toString() + "?" + reEncodedDownloadSpec; //$NON-NLS-1$
        downloadHost = uri.getHost();
    } else {
        // TODO: Check with TFS2010 VC Proxy

        /*
         * TFS 2005 uses a proxy download file without a "V1.0" in it. TFS
         * 2008 introduced the "V1.0" part, but remains compatible with TFS
         * 2005's path. TFS 2010 drops the 2005 compat. To detect which
         * version, we check the supported features for "create branch",
         * which was introduced in 2008. Kind of a hack.
         */
        final String proxyDownloadFile = getServerSupportedFeatures().contains(SupportedFeatures.CREATE_BRANCH)
                ? VersionControlConstants.PROXY_DOWNLOAD_FILE_2008
                : VersionControlConstants.PROXY_DOWNLOAD_FILE_2005;

        final URI uri = URIUtils.newURI(tfsProxyURL).resolve(proxyDownloadFile);

        downloadURIString = uri.toString() + "?" //$NON-NLS-1$
                + reEncodedDownloadSpec + "&" //$NON-NLS-1$
                + VersionControlConstants.PROXY_REPOSITORY_ID_QUERY_STRING + "=" //$NON-NLS-1$
                + getServerGUID();
        downloadHost = uri.getHost();
    }

    /*
     * Construct a Get method for our HttpClient to use.
     */
    final GetMethod getMethod = new GetMethod(downloadURIString);
    getMethod.setDoAuthentication(true);

    final HttpClient client = getHTTPClient();
    int status = -1;

    /*
     * If any exception happens, finish the method immediately because we
     * won't be returning it. This releases the connection to the connection
     * manager.
     */
    try {
        status = client.executeMethod(getMethod);
    } catch (final ConnectException e) {
        finishDownloadRequest(getMethod);
        if (tfsProxyURL != null) {
            throw new DownloadProxyException(MessageFormat.format(
                    Messages.getString("VersionControlClient.CouldNotConnectToDownloadProxyServerFormat"), //$NON-NLS-1$
                    downloadHost, e.getMessage()));
        } else {
            throw new VersionControlException(
                    MessageFormat.format(Messages.getString("VersionControlClient.CouldNotConnecttoTFSFormat"), //$NON-NLS-1$
                            downloadHost, e.getLocalizedMessage()));
        }
    } catch (final UnknownHostException e) {
        finishDownloadRequest(getMethod);
        if (tfsProxyURL != null) {
            throw new DownloadProxyException(MessageFormat.format(
                    Messages.getString(
                            "VersionControlClient.CouldNotResolveDownloadProxyServertoNetworkAddressFormat"), //$NON-NLS-1$
                    downloadHost));
        } else {
            throw new VersionControlException(MessageFormat.format(
                    Messages.getString("VersionControlClient.CouldNotResolveTFSToNetworkAddressFormat"), //$NON-NLS-1$
                    downloadHost));
        }
    } catch (final SocketException e) {
        finishDownloadRequest(getMethod);
        throw e;
    } catch (final SocketTimeoutException e) {
        finishDownloadRequest(getMethod);
        if (tfsProxyURL != null) {
            throw new DownloadProxyException(MessageFormat.format(
                    Messages.getString("VersionControlClient.ErrorConnectingToDownloadProxyServerFormat"), //$NON-NLS-1$
                    downloadHost, e.getMessage()));
        } else {
            throw new VersionControlException(
                    MessageFormat.format(Messages.getString("VersionControlClient.ErrorConnectingToTFSFormat"), //$NON-NLS-1$
                            downloadHost, e.getLocalizedMessage()));
        }
    } catch (final IOException e) {
        finishDownloadRequest(getMethod);
        if (tfsProxyURL != null) {
            throw new DownloadProxyException(MessageFormat.format(
                    Messages.getString("VersionControlClient.ErrorConnectingToDownloadProxyServerFormat"), //$NON-NLS-1$
                    downloadHost, e.getMessage()));
        } else {
            throw new VersionControlException(
                    MessageFormat.format(Messages.getString("VersionControlClient.ErrorConnectingToTFSFormat"), //$NON-NLS-1$
                            downloadHost, e.getLocalizedMessage()));
        }
    }

    if (status != HttpStatus.SC_OK) {
        /*
         * Finish the method before we throw.
         */
        finishDownloadRequest(getMethod);

        if (tfsProxyURL != null) {
            throw new DownloadProxyException(MessageFormat.format(
                    Messages.getString("VersionControlClient.DownloadProxyAtURLReturnedHTTPStatusForGETFormat"), //$NON-NLS-1$
                    tfsProxyURL.toString(), status));
        } else {
            /* Handle status will always throw a VersionControlException */
            handleStatus(getMethod);
        }
    }

    return getMethod;
}