Example usage for java.net ConnectException ConnectException

List of usage examples for java.net ConnectException ConnectException

Introduction

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

Prototype

public ConnectException(String msg) 

Source Link

Document

Constructs a new ConnectException with the specified detail message as to why the connect error occurred.

Usage

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * Create a File from a remote URL./*w  w w  . j ava 2  s.c  o m*/
 * 
 * @param url
 *            the url of the site. Example http://www.yahoo.com
 * @param file
 *            the file to create from the download.
 * 
 * @throws IllegalArgumentException
 *             if the url or the file is null
 * @throws UnknownHostException
 *             Host url (http://www.acme.org) does not exists or no Internet
 *             Connection.
 * @throws FileNotFoundException
 *             Impossible to connect to the Host. May appear if, for
 *             example, the Web server is down. (Tomcat down ,etc.)
 * @throws IOException
 *             For all other IO / Network / System Error
 * @throws InterruptedException
 *             if download is interrupted by user through a
 *             TransferProgressManager
 */
@Override
public void downloadUrl(URL url, File file)
        throws IllegalArgumentException, UnknownHostException, FileNotFoundException, IOException

{
    if (file == null) {
        throw new IllegalArgumentException("file can not be null!");
    }

    if (url == null) {
        throw new IllegalArgumentException("url can not be null!");
    }

    InputStream in = null;
    OutputStream out = null;

    statusCode = 0; // Reset it!
    m_responseBody = null; // Reset it!

    try {

        conn = buildHttpUrlConnection(url);
        conn.setRequestMethod(GET);

        if ("gzip".equals(conn.getContentEncoding())) {
            in = new GZIPInputStream(conn.getInputStream());
        } else {
            in = conn.getInputStream();
        }

        // Analyze the error after request execution
        statusCode = conn.getResponseCode();

        if (statusCode != HttpURLConnection.HTTP_OK) {
            // The server is up, but the servlet is not accessible
            throw new ConnectException(
                    url + ": Servlet failed: " + conn.getResponseMessage() + " status: " + statusCode);
        }

        out = new BufferedOutputStream(new FileOutputStream(file));

        byte[] buf = new byte[4096];
        int len;
        int tempLen = 0;
        long filesLength = 0;

        while ((len = in.read(buf)) > 0) {
            tempLen += len;

            if (filesLength > 0 && tempLen > filesLength / MAXIMUM_PROGRESS_100) {
                tempLen = 0;
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            out.write(buf, 0, len);
        }

    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }

}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*from w  ww .j  a  v a 2s  . c  o  m*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:org.jzkit.z3950.util.ZEndpoint.java

protected void connect(String refid) throws ConnectException, IOException {
    if ((null != target_hostname) && (target_port > 0)) {
        log.debug("Attempting to connect to " + target_hostname + ":" + target_port);
        int timeout = 20000;
        z_assoc = new Socket(target_hostname, target_port);
        outgoing_data = z_assoc.getOutputStream();
        incoming_data = z_assoc.getInputStream();
    } else {/*w  w  w . j  a v  a  2  s.c  o  m*/
        throw new ConnectException("Properties do not contain ServiceHost and/or ServicePort");
    }

    log.debug("Connect completed OK, send init request (nodelay=" + z_assoc.getTcpNoDelay() + ", timeout="
            + z_assoc.getSoTimeout() + ", linger=" + z_assoc.getSoLinger() + ")");

    // Will allow user access to init parameters via props soon...
    // We might need to sleep here for a little while to give the remote target
    // a chance to warm up (testing against moray.stir.ac.uk indicates this to be
    // the case).

    AsnBitString version_info = new AsnBitString();
    version_info.setBit(0);
    version_info.setBit(1);
    version_info.setBit(2);

    AsnBitString options = new AsnBitString();
    options.setBit(0); // search
    options.setBit(1); // present
    options.setBit(2); // del Set
    // options.setBit(3);     // resourceReport
    // options.setBit(4);     // trigger Resource Control
    // options.setBit(5);     // ResourceControl
    // options.setBit(6);     // Access control
    options.setBit(7); // scan
    options.setBit(8); // Sort
                       // 9 is reserved
    options.setBit(10); // Extended Services
    // options.setBit(11);    // Level 1 Segmentations
    // options.setBit(12);    // Level 2 Segmentations
    options.setBit(13); // Concurent ops
    options.setBit(14); // Named result sets

    String s = null;

    // Init request, 8k pref. message size, 64k exceptional
    sendInitRequest(version_info, options, refid, auth_type, service_user_principal, service_user_group,
            service_user_credentials);

    log.debug("Sent init request");
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.LDAPUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#modifyUserEmail(java.lang.String, java.lang.String)
 *///from  w  w  w  .ja v  a 2  s .co  m
public synchronized boolean modifyUserEmail(final String userId, final String value)
        throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME
            + "#modifyUserEmail(final String userId, final String value) throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("userId: {}", userId);
        DEBUGGER.debug("userGuid: {}", value);
    }

    boolean isComplete = false;
    LDAPConnection ldapConn = null;
    LDAPConnectionPool ldapPool = null;

    try {
        ldapPool = (LDAPConnectionPool) svcBean.getAuthDataSource();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnectionPool: {}", ldapPool);
        }

        if (ldapPool.isClosed()) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        ldapConn = ldapPool.getConnection();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnection: {}", ldapConn);
        }

        if (!(ldapConn.isConnected())) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        List<Modification> modifyList = new ArrayList<Modification>(Arrays
                .asList(new Modification(ModificationType.REPLACE, userAttributes.getEmailAddr(), value)));

        LDAPResult ldapResult = ldapConn.modify(
                new ModifyRequest(new StringBuilder().append(userAttributes.getUserId() + "=" + userId + ",")
                        .append(repoConfig.getRepositoryUserBase() + "," + repoConfig.getRepositoryBaseDN())
                        .toString(), modifyList));

        if (DEBUG) {
            DEBUGGER.debug("LDAPResult: {}", ldapResult);
        }

        isComplete = (ldapResult.getResultCode() == ResultCode.SUCCESS);

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (LDAPException lx) {
        throw new UserManagementException(lx.getMessage(), lx);
    } catch (ConnectException cx) {
        throw new UserManagementException(cx.getMessage(), cx);
    } finally {
        if ((ldapPool != null) && ((ldapConn != null) && (ldapConn.isConnected()))) {
            ldapConn.close();
            ldapPool.releaseConnection(ldapConn);
        }
    }

    return isComplete;
}

From source file:com.evolveum.icf.dummy.resource.DummyResource.java

private synchronized <T extends DummyObject> void deleteObjectById(Class<T> type, Map<String, T> map, String id)
        throws ObjectDoesNotExistException, ConnectException, FileNotFoundException {
    if (deleteBreakMode == BreakMode.NONE) {
        // go on/*from   w w  w . j a  va2 s .  com*/
    } else if (deleteBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (deleteBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (deleteBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (deleteBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (deleteBreakMode == BreakMode.UNSUPPORTED) {
        throw new UnsupportedOperationException("Not supported (simulated error)");
    } else {
        // This is a real error. Use this strange thing to make sure it passes up
        throw new RuntimeException("Unknown schema break mode " + schemaBreakMode);
    }

    DummyObject object = allObjects.get(id);
    if (object == null) {
        throw new ObjectDoesNotExistException(type.getSimpleName() + " with id '" + id + "' does not exist");
    }
    if (!type.isInstance(object)) {
        throw new IllegalStateException(
                "Arrrr! Wanted " + type + " with ID " + id + " but got " + object + " instead");
    }
    T existingObject = (T) object;
    String normalName = normalize(object.getName());

    allObjects.remove(id);

    String mapKey;
    if (enforceUniqueName) {
        mapKey = normalName;
    } else {
        mapKey = id;
    }

    if (map.containsKey(mapKey)) {
        map.remove(mapKey);
    } else {
        throw new ObjectDoesNotExistException(
                type.getSimpleName() + " with name '" + normalName + "' does not exist");
    }

    if (syncStyle != DummySyncStyle.NONE) {
        int syncToken = nextSyncToken();
        DummyDelta delta = new DummyDelta(syncToken, type, id, object.getName(), DummyDeltaType.DELETE);
        deltas.add(delta);
    }
}

From source file:io.hummer.util.ws.WebServiceClient.java

public static Definition getWsdlDefinition(String wsdlURL) throws Exception {
    WSDLFactory wsdlFactory = WSDLFactory.newInstance();

    try {// w  w  w.j a  v a  2s.  com
        int timeoutMS = 5 * 1000; // timeout of 5 seconds..
        Class<?> clazz = Class.forName("sun.net.www.http.HttpClient");
        Method m = clazz.getMethod("New", URL.class, Proxy.class, int.class);
        try {
            Object conn = m.invoke(null, new URL(wsdlURL), null, timeoutMS);
            conn.getClass().getMethod("closeServer").invoke(conn);
        } catch (Exception e) {
            throw new ConnectException("Unable to retrieve WSDL at " + wsdlURL);
        }
    } catch (Exception e) {
        /* most likely, sun.net.www.http.HttpClient could not be found --> swallow */}

    WSDLReader wsdlReader = wsdlFactory.newWSDLReader();

    wsdlReader.setFeature(Constants.FEATURE_VERBOSE, false);
    wsdlReader.setFeature(Constants.FEATURE_IMPORT_DOCUMENTS, true);

    Definition wsdl = wsdlReader.readWSDL(wsdlURL);
    return wsdl;
}

From source file:org.kawanfw.commons.client.http.HttpTransferOne.java

/**
 * Create a File from a remote URL./*  w ww  . j  av a  2s .  c  om*/
 * 
 * @param url
 *            the url of the site. Example http://www.yahoo.com
 * @param file
 *            the file to create from the download.
 * 
 * @throws IllegalArgumentException
 *             if the url or the file is null
 * @throws UnknownHostException
 *             Host url (http://www.acme.org) does not exists or no Internet
 *             Connection.
 * 
 * @throws IOException
 *             For all other IO / Network / System Error
 */
@Override
public String getUrlContent(URL url) throws IllegalArgumentException, UnknownHostException, IOException

{

    if (url == null) {
        throw new IllegalArgumentException("url can not be null!");
    }

    InputStream in = null;
    statusCode = 0; // Reset it!
    m_responseBody = null; // Reset it!

    try {

        conn = buildHttpUrlConnection(url);
        conn.setRequestMethod(GET);

        if ("gzip".equals(conn.getContentEncoding())) {
            in = new GZIPInputStream(conn.getInputStream());
        } else {
            in = conn.getInputStream();
        }

        // Analyze the error after request execution
        statusCode = conn.getResponseCode();

        if (statusCode != HttpURLConnection.HTTP_OK) {
            // The server is up, but the servlet is not accessible
            throw new ConnectException(
                    url + ": Servlet failed: " + conn.getResponseMessage() + " status: " + statusCode);
        }

        int writeBufferSize = DefaultParms.DEFAULT_WRITE_BUFFER_SIZE;
        int maxLengthForString = DefaultParms.DEFAULT_MAX_LENGTH_FOR_STRING;
        if (sessionParameters != null) {
            maxLengthForString = sessionParameters.getMaxLengthForString();
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[writeBufferSize];
        int len = 0;
        int totalLen = 0;
        while ((len = in.read(buf)) > 0) {
            totalLen += len;

            if (totalLen > maxLengthForString) {
                throw new IOException("URL content is too big for download into a String. "
                        + "Maximum length authorized is: " + maxLengthForString);
            }

            out.write(buf, 0, len);
        }

        String content = new String(out.toByteArray());
        return content;

    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:com.taobao.adfs.distributed.rpc.Client.java

/**
 * Take an IOException and the address we were trying to connect to and return an IOException with the input exception
 * as the cause. The new exception provides the stack trace of the place where the exception is thrown and some extra
 * diagnostics information. If the exception is ConnectException or SocketTimeoutException, return a new one of the
 * same type; Otherwise return an IOException.
 * // w  ww  .  j ava2s .c o  m
 * @param addr
 *          target address
 * @param exception
 *          the relevant exception
 * @return an exception to throw
 */
private IOException wrapException(InetSocketAddress addr, IOException exception) {
    if (exception instanceof ConnectException) {
        // connection refused; include the host:port in the error
        return (ConnectException) new ConnectException(
                "Call to " + addr + " failed on connection exception: " + exception).initCause(exception);
    } else if (exception instanceof SocketTimeoutException) {
        return (SocketTimeoutException) new SocketTimeoutException(
                "Call to " + addr + " failed on socket timeout exception: " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);

    }
}

From source file:com.evolveum.icf.dummy.resource.DummyResource.java

private <T extends DummyObject> void renameObject(Class<T> type, Map<String, T> map, String id, String oldName,
        String newName) throws ObjectDoesNotExistException, ObjectAlreadyExistsException, ConnectException,
        FileNotFoundException {/*from  ww  w . jav a2  s  .  c o m*/
    if (modifyBreakMode == BreakMode.NONE) {
        // go on
    } else if (modifyBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (modifyBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (modifyBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (modifyBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (modifyBreakMode == BreakMode.UNSUPPORTED) {
        throw new UnsupportedOperationException("Not supported (simulated error)");
    } else {
        // This is a real error. Use this strange thing to make sure it passes up
        throw new RuntimeException("Unknown schema break mode " + schemaBreakMode);
    }

    T existingObject;
    if (enforceUniqueName) {
        String normalOldName = normalize(oldName);
        String normalNewName = normalize(newName);
        existingObject = map.get(normalOldName);
        if (existingObject == null) {
            throw new ObjectDoesNotExistException("Cannot rename, " + type.getSimpleName() + " with username '"
                    + normalOldName + "' does not exist");
        }
        if (map.containsKey(normalNewName)) {
            throw new ObjectAlreadyExistsException("Cannot rename, " + type.getSimpleName() + " with username '"
                    + normalNewName + "' already exists");
        }
        map.put(normalNewName, existingObject);
        map.remove(normalOldName);
    } else {
        existingObject = (T) allObjects.get(id);
    }
    existingObject.setName(newName);
    if (existingObject instanceof DummyAccount) {
        changeDescriptionIfNeeded((DummyAccount) existingObject);
    }
}

From source file:com.cws.esolutions.security.dao.usermgmt.impl.LDAPUserManager.java

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#modifyUserContact(java.lang.String, java.util.List)
 *//*w  ww  . j  a  v a  2s  . c om*/
public synchronized boolean modifyUserContact(final String userId, final List<String> values)
        throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME
            + "#modifyUserContact(final String userId, final String value, final String attribute) throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", userId);
        DEBUGGER.debug("Value: {}", values);
    }

    boolean isComplete = false;
    LDAPConnection ldapConn = null;
    LDAPConnectionPool ldapPool = null;

    try {
        ldapPool = (LDAPConnectionPool) svcBean.getAuthDataSource();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnectionPool: {}", ldapPool);
        }

        if (ldapPool.isClosed()) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        ldapConn = ldapPool.getConnection();

        if (DEBUG) {
            DEBUGGER.debug("LDAPConnection: {}", ldapConn);
        }

        if (!(ldapConn.isConnected())) {
            throw new ConnectException("Failed to create LDAP connection using the specified information");
        }

        List<Modification> modifyList = new ArrayList<Modification>(Arrays.asList(new Modification(
                ModificationType.REPLACE, userAttributes.getTelephoneNumber(), values.get(0))));

        LDAPResult ldapResult = ldapConn.modify(
                new ModifyRequest(new StringBuilder().append(userAttributes.getUserId() + "=" + userId + ",")
                        .append(repoConfig.getRepositoryUserBase() + "," + repoConfig.getRepositoryBaseDN())
                        .toString(), modifyList));

        if (DEBUG) {
            DEBUGGER.debug("LDAPResult: {}", ldapResult);
        }

        isComplete = (ldapResult.getResultCode() == ResultCode.SUCCESS);

        if (DEBUG) {
            DEBUGGER.debug("isComplete: {}", isComplete);
        }
    } catch (LDAPException lx) {
        throw new UserManagementException(lx.getMessage(), lx);
    } catch (ConnectException cx) {
        throw new UserManagementException(cx.getMessage(), cx);
    } finally {
        if ((ldapPool != null) && ((ldapConn != null) && (ldapConn.isConnected()))) {
            ldapConn.close();
            ldapPool.releaseConnection(ldapConn);
        }
    }

    return isComplete;
}