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:com.evolveum.icf.dummy.resource.DummyResource.java

private <T extends DummyObject> T getObjectByName(Map<String, T> map, String name)
        throws ConnectException, FileNotFoundException {
    if (!enforceUniqueName) {
        throw new IllegalStateException(
                "Attempt to search object by name while resource is in non-unique name mode");
    }/*  ww w  .j  a v  a  2 s.c  o m*/
    if (getBreakMode == BreakMode.NONE) {
        return map.get(normalize(name));
    } else if (schemaBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (schemaBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (schemaBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (schemaBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (schemaBreakMode == 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);
    }
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {/*ww  w.j av a 2s. co  m*/
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * send frame data to SocketStream//from  ww  w .j a  v  a 2s  .com
 *
 * @param frame
 */
void sendFrame(final byte[] frame) {
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (mSendLock) {
                    if (mSocket == null) {
                        throw new ConnectException("Socket not connected");
                    }
                    OutputStream outputStream = mSocket.getOutputStream();
                    outputStream.write(frame);
                    outputStream.flush();
                }
            } catch (IOException e) {
                emitterOnError(e);
            }
        }
    });
}

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

/**
 * Get and analyze the response.//from  w  w  w.  ja va  2 s  .c om
 * 
 * @param conn
 *            the URL connection in use
 * 
 * @throws UnknownHostException
 * @throws ConnectException
 * @throws RemoteException
 * @throws IOException
 */
private void getAndAnalyzeResponse(HttpURLConnection conn)
        throws UnknownHostException, ConnectException, RemoteException, IOException {

    BufferedReader reader = null;
    File contentFile = null;

    try {

        // 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);
        }

        // it's ok to use a buffered stream with SSL with HttpUrlConnection
        // Check the server sent us back a compressed content
        if ("gzip".equals(conn.getContentEncoding())) {
            reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getInputStream())));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }

        // line 1: Contains the request status - line 2: Contains the datas
        String responseStatus = reader.readLine();
        // debug("responseStatus        : " + responseStatus);

        if (doReceiveInFile) {
            // Content is saved back into a file, minus the first line
            // status
            receiveFile = HttpTransferUtil.createKawansoftTempFile();
            copyResponseIntoFile(reader, receiveFile);
        } else {
            copyResponseIntoString(reader);
        }

        // Analyze applicative response header
        // "SEND_OK"
        // "SEND_FAILED"

        if (responseStatus.startsWith(TransferStatus.SEND_OK)) {
            return; // OK!
        } else if (responseStatus.startsWith(TransferStatus.SEND_FAILED)) {
            BufferedReader bufferedReaderException = null;

            debug(TransferStatus.SEND_FAILED);

            try {
                // We must throw the remote exception
                if (doReceiveInFile) {
                    bufferedReaderException = new BufferedReader(new FileReader(receiveFile));
                    HttpTransferUtil.throwTheRemoteException(bufferedReaderException);
                } else {
                    bufferedReaderException = new BufferedReader(new StringReader(m_responseBody));
                    HttpTransferUtil.throwTheRemoteException(bufferedReaderException);
                }
            } finally {
                IOUtils.closeQuietly(bufferedReaderException);

                if (doReceiveInFile && !DEBUG) {
                    receiveFile.delete();
                }
            }
        } else {

            String message = "The Server response does not start with awaited SEND_OK or SEND_FAILED." + CR_LF
                    + "This could be a configuration failure with an URL that does not correspond to a Kawansoft Servlet."
                    + CR_LF + "URL: " + url + CR_LF
                    + "This could also be a communication failure. Content of server response: " + CR_LF;

            message += FileUtils.readFileToString(contentFile);
            throw new IOException(message);
        }
    } finally {

        IOUtils.closeQuietly(reader);

        if (!DEBUG) {
            FileUtils.deleteQuietly(contentFile);
        }

    }

}

From source file:org.jlibrary.core.axis.client.AxisSecurityDelegate.java

public Ticket login(Credentials credentials, String name) throws UserNotFoundException, AuthenticationException,
        SecurityException, ConnectException, RepositoryNotFoundException {

    try {/*www.j  a  va  2  s  . co m*/
        call.removeAllParameters();

        call.setOperationName("login");
        call.addParameter("credentials", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("name", XMLType.XSD_STRING, ParameterMode.IN);

        call.setReturnType(XMLType.XSD_ANY);

        Ticket ticket = (Ticket) call.invoke(new Object[] { credentials, name });
        return ticket;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("ConnectException") != -1) {
            throw new ConnectException(fault.getFaultString());
        }
        if (fault.getFaultString().indexOf("RepositoryNotFoundException") != -1) {
            throw new RepositoryNotFoundException(fault.getFaultString());
        }
        throw createSecurityException((AxisFault) e);
    }
}

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

private <T extends DummyObject> T getObjectById(Class<T> expectedClass, String id)
        throws ConnectException, FileNotFoundException {
    if (getBreakMode == BreakMode.NONE) {
        DummyObject dummyObject = allObjects.get(id);
        if (dummyObject == null) {
            return null;
        }//from  www. j  av a2 s .  c om
        if (!expectedClass.isInstance(dummyObject)) {
            throw new IllegalStateException("Arrrr! Wanted " + expectedClass + " with ID " + id + " but got "
                    + dummyObject + " instead");
        }
        return (T) dummyObject;
    } else if (schemaBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (schemaBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (schemaBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (schemaBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (schemaBreakMode == 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);
    }
}

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

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#loadUserAccount(java.lang.String)
 *//*  w ww.  j  a v a 2 s . c o  m*/
public synchronized List<Object> loadUserAccount(final String userGuid) throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME
            + "#loadUserAccount(final String userGuid) throws UserManagementException";

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

    LDAPConnection ldapConn = null;
    List<Object> userAccount = 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");
        }

        Filter searchFilter = Filter.create("(&(objectClass=" + repoConfig.getBaseObject() + ")" + "(&("
                + userAttributes.getCommonName() + "=" + userGuid + ")))");

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

        SearchRequest searchRequest = new SearchRequest(
                repoConfig.getRepositoryUserBase() + "," + repoConfig.getRepositoryBaseDN(), SearchScope.SUB,
                searchFilter);

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

        SearchResult searchResult = ldapConn.search(searchRequest);

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

        if (searchResult.getResultCode() == ResultCode.SUCCESS) {
            if (searchResult.getEntryCount() == 1) {
                SearchResultEntry entry = searchResult.getSearchEntries().get(0);

                if (DEBUG) {
                    DEBUGGER.debug("SearchResultEntry: {}", entry);
                }

                userAccount = new ArrayList<Object>();

                for (String returningAttribute : userAttributes.getReturningAttributes()) {
                    if (DEBUG) {
                        DEBUGGER.debug("returningAttribute: {}", returningAttribute);
                    }

                    if (entry.hasAttribute(returningAttribute)) {
                        userAccount.add(entry.getAttributeValue(returningAttribute));
                    }
                }

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

                if (StringUtils.isNotBlank(userAttributes.getMemberOf())) {
                    Filter roleFilter = Filter.create(
                            "(&(objectClass=groupOfUniqueNames)" + "(&(uniqueMember=" + entry.getDN() + ")))");

                    if (DEBUG) {
                        DEBUGGER.debug("SearchFilter: {}", roleFilter);
                    }

                    SearchRequest roleSearch = new SearchRequest(repoConfig.getRepositoryRoleBase(),
                            SearchScope.SUB, roleFilter, userAttributes.getCommonName());

                    if (DEBUG) {
                        DEBUGGER.debug("SearchRequest: {}", roleSearch);
                    }

                    SearchResult roleResult = ldapConn.search(roleSearch);

                    if (DEBUG) {
                        DEBUGGER.debug("searchResult: {}", roleResult);
                    }

                    if ((roleResult.getResultCode() == ResultCode.SUCCESS)
                            && (roleResult.getEntryCount() != 0)) {
                        List<String> roles = new ArrayList<String>();

                        for (SearchResultEntry role : roleResult.getSearchEntries()) {
                            if (DEBUG) {
                                DEBUGGER.debug("SearchResultEntry: {}", role);
                            }

                            roles.add(role.getAttributeValue(userAttributes.getCommonName()));
                        }

                        userAccount.add(roles);
                    }
                }

                if (DEBUG) {
                    DEBUGGER.debug("UserAccount: {}", userAccount);
                }
            } else {
                throw new UserManagementException("Multiple users were located for the provided information");
            }
        } else {
            throw new UserManagementException("Search request failed: " + searchResult.getResultCode());
        }
    } 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 userAccount;
}

From source file:org.apache.camel.component.netty4.NettyProducer.java

protected Channel openChannel(ChannelFuture channelFuture) throws Exception {
    // blocking for channel to be done
    if (LOG.isTraceEnabled()) {
        LOG.trace("Waiting for operation to complete {} for {} millis", channelFuture,
                configuration.getConnectTimeout());
    }/*www  . j a  va2 s  .  c  o  m*/
    // here we need to wait it in other thread
    final CountDownLatch channelLatch = new CountDownLatch(1);
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            channelLatch.countDown();
        }
    });

    try {
        channelLatch.await(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    } catch (InterruptedException ex) {
        throw new CamelException(
                "Interrupted while waiting for " + "connection to " + configuration.getAddress());
    }

    if (!channelFuture.isDone() || !channelFuture.isSuccess()) {
        ConnectException cause = new ConnectException("Cannot connect to " + configuration.getAddress());
        if (channelFuture.cause() != null) {
            cause.initCause(channelFuture.cause());
        }
        throw cause;
    }
    Channel answer = channelFuture.channel();
    // to keep track of all channels in use
    allChannels.add(answer);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating connector to address: {}", configuration.getAddress());
    }
    return answer;
}

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

public Collection<DummyGroup> listGroups() throws ConnectException, FileNotFoundException {
    if (getBreakMode == BreakMode.NONE) {
        return groups.values();
    } else if (schemaBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error (simulated error)");
    } else if (schemaBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error (simulated error)");
    } else if (schemaBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error (simulated error)");
    } else if (schemaBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic error (simulated error)");
    } else if (schemaBreakMode == BreakMode.UNSUPPORTED) {
        throw new UnsupportedOperationException("Not supported (simulated error)");
    } else {/* w w  w  .j av a  2s  .co  m*/
        // This is a real error. Use this strange thing to make sure it passes up
        throw new RuntimeException("Unknown schema break mode " + schemaBreakMode);
    }
}