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.apache.camel.component.netty.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());
    }//w  w  w.j  a  va 2  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.getCause() != null) {
            cause.initCause(channelFuture.getCause());
        }
        throw cause;
    }
    Channel answer = channelFuture.getChannel();
    // to keep track of all channels in use
    ALL_CHANNELS.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<DummyPrivilege> listPrivileges() throws ConnectException, FileNotFoundException {
    if (getBreakMode == BreakMode.NONE) {
        return privileges.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 {//from  w ww.j a va2s  . com
        // 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.buaa.cfs.utils.NetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the
 * socket to./*from w w  w  .jav  a 2  s  .  c om*/
 *
 * @param socket
 * @param endpoint  the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout   timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        Class localClass = localAddr.getClass();
        Class remoteClass = endpoint.getClass();
        Preconditions.checkArgument(localClass.equals(remoteClass),
                "Local address %s must be of same family as remote address %s.", localAddr, endpoint);
        socket.bind(localAddr);
    }

    try {
        if (ch == null) {
            // let the default implementation handle it.
            socket.connect(endpoint, timeout);
        } else {
            //        SocketIOWithTimeout.connect(ch, endpoint, timeout);
        }
    } catch (SocketTimeoutException ste) {
        //      throw new ConnectTimeoutException(ste.getMessage());
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

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.//w  ww  . j a v  a 2  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:com.evolveum.icf.dummy.resource.DummyResource.java

private synchronized <T extends DummyObject> String addObject(Map<String, T> map, T newObject)
        throws ObjectAlreadyExistsException, ConnectException, FileNotFoundException, SchemaViolationException {
    if (addBreakMode == BreakMode.NONE) {
        // just go on
    } else if (addBreakMode == BreakMode.NETWORK) {
        throw new ConnectException("Network error during add (simulated error)");
    } else if (addBreakMode == BreakMode.IO) {
        throw new FileNotFoundException("IO error during add (simulated error)");
    } else if (addBreakMode == BreakMode.GENERIC) {
        // The connector will react with generic exception
        throw new IllegalArgumentException("Generic error during add (simulated error)");
    } else if (addBreakMode == BreakMode.RUNTIME) {
        // The connector will just pass this up
        throw new IllegalStateException("Generic rutime error during add (simulated error)");
    } else if (addBreakMode == BreakMode.UNSUPPORTED) {
        throw new UnsupportedOperationException("Unsupported operation: add (simulated error)");
    } else {//from www . j  a va 2 s.  c  om
        // This is a real error. Use this strange thing to make sure it passes up
        throw new RuntimeException("Unknown break mode " + addBreakMode);
    }

    Class<? extends DummyObject> type = newObject.getClass();
    String normalName = normalize(newObject.getName());
    if (normalName != null && forbiddenNames != null && forbiddenNames.contains(normalName)) {
        throw new ObjectAlreadyExistsException(normalName + " is forbidden to use as an object name");
    }

    String newId = UUID.randomUUID().toString();
    newObject.setId(newId);
    if (allObjects.containsKey(newId)) {
        throw new IllegalStateException("The hell is frozen over. The impossible has happened. ID " + newId
                + " already exists (" + type.getSimpleName() + " with identifier " + normalName + ")");
    }

    //this is "resource-generated" attribute (used to simulate resource which generate by default attributes which we need to sync)
    if (generateDefaultValues) {
        //         int internalId = allObjects.size();
        newObject.addAttributeValue(DummyAccount.ATTR_INTERNAL_ID, new Random().nextInt());
    }

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

    if (map.containsKey(mapKey)) {
        throw new ObjectAlreadyExistsException(
                type.getSimpleName() + " with name '" + normalName + "' already exists");
    }

    newObject.setResource(this);
    map.put(mapKey, newObject);
    allObjects.put(newId, newObject);

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

    return newObject.getName();
}

From source file:org.jboss.processFlow.knowledgeService.BaseKnowledgeSessionBean.java

protected synchronized void createKnowledgeBaseViaKnowledgeAgent(boolean forceRefresh) throws ConnectException {
    log.info("createKnowledgeBaseViaKnowledgeAgent() forceRefresh = " + forceRefresh);
    if (kbase != null && !forceRefresh)
        return;/*w ww.j a  v  a  2 s. com*/

    if (kagent != null) {
        kagent.dispose();
        kagent = null;
    }

    // investigate:  List<String> guvnorPackages = guvnorUtils.getBuiltPackageNames();
    // http://ratwateribm:8080/jboss-brms/org.drools.guvnor.Guvnor/package/org.jboss.processFlow/test-pfp-snapshot

    if (!guvnorUtils.guvnorExists()) {
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append(guvnorUtils.getGuvnorProtocol());
        sBuilder.append("://");
        sBuilder.append(guvnorUtils.getGuvnorHost());
        sBuilder.append("/");
        sBuilder.append(guvnorUtils.getGuvnorSubdomain());
        sBuilder.append("/rest/packages/");
        throw new ConnectException(
                "createKnowledgeBase() cannot connect to guvnor at URL : " + sBuilder.toString());
    }

    // for polling of guvnor to occur, the polling and notifier services must be started
    ResourceChangeScannerConfiguration sconf = ResourceFactory.getResourceChangeScannerService()
            .newResourceChangeScannerConfiguration();

    // Do not start change set notifications
    Integer droolsResourceScannerIntervalValue = -1;
    try {
        droolsResourceScannerIntervalValue = Integer.valueOf(droolsResourceScannerInterval);
    } catch (NumberFormatException nfe) {
        log.error("DroolsResourceScannerInterval is not an integer: " + droolsResourceScannerInterval, nfe);
    }
    if (droolsResourceScannerIntervalValue > 0) {
        sconf.setProperty("drools.resource.scanner.interval", droolsResourceScannerInterval);
        ResourceFactory.getResourceChangeScannerService().configure(sconf);
        ResourceFactory.getResourceChangeScannerService().start();
        ResourceFactory.getResourceChangeNotifierService().start();
    }

    KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration(); // implementation = org.drools.agent.impl.KnowledgeAgentConfigurationImpl

    /*  - incremental change set processing enabled
    - will create a single KnowledgeBase and always refresh that same instance
    */
    aconf.setProperty("drools.agent.newInstance", "false");
    if (droolsResourceScannerIntervalValue < 0) {
        aconf.setProperty("drools.agent.scanResources", Boolean.FALSE.toString());
        aconf.setProperty("drools.agent.scanDirectories", Boolean.FALSE.toString());
        aconf.setProperty("drools.agent.monitorChangeSetEvents", Boolean.FALSE.toString());
    }

    /*  -- Knowledge Agent provides automatic loading, caching and re-loading of resources
    -- the knowledge agent can update or rebuild this knowledge base as the resources it uses are changed
    */
    kagent = KnowledgeAgentFactory.newKnowledgeAgent("Guvnor default", aconf);
    StringReader sReader = guvnorUtils.createChangeSet();
    try {
        guvnorChangeSet = IOUtils.toString(sReader);
        sReader.close();
    } catch (Exception x) {
        x.printStackTrace();
    }

    kagent.applyChangeSet(ResourceFactory.newByteArrayResource(guvnorChangeSet.getBytes()));

    /*  - set KnowledgeBase as instance variable to this mbean for use throughout all functionality of this service
    - a knowledge base is a collection of compiled definitions, such as rules and processes, which are compiled using the KnowledgeBuilder
    - the knowledge base itself does not contain instance data, known as facts
    - instead, sessions are created from the knowledge base into which data can be inserted and where process instances may be started
    - creating the knowledge base can be heavy, whereas session creation is very light :  http://blog.athico.com/2011/09/small-efforts-big-improvements.html
    - a knowledge base is also serializable, allowing for it to be stored
    */
    kbase = kagent.getKnowledgeBase();
    lastKAgentRefresh = System.currentTimeMillis();
    log.info("createKnowledgeBaseViaKnowledgeAgent() just refreshed kBase via knowledgeAgent");
}

From source file:org.apache98.hadoop.hbase.ipc.RpcClient.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 a  va  2  s.  c  o  m*/
 * @param addr
 *            target address
 * @param exception
 *            the relevant exception
 * @return an exception to throw
 */
protected 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 because " + exception).initCause(exception);
    } else {
        return (IOException) new IOException("Call to " + addr + " failed on local exception: " + exception)
                .initCause(exception);
    }
}

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

/**
 * Send a String to the HTTP server using servlet defined by url and return
 * the corresponding input stream// w w w .  j  av  a2s. c o  m
 * 
 * 
 * @param requestParams
 *            the request parameters list with (parameter, value)
 * @param fileLength
 *            the file length (for the progress indicator). If 0, will not
 *            be used
 * @param file
 *            the file to create on the client side (PC)
 * 
 * @throws IllegalArgumentException
 *             if the file to download is null
 * @throws UnknownHostException
 *             Host url (http://www.acme.org) does not exists or no Internet
 *             Connection.
 * @throws ConnectException
 *             The Host is correct but the Servlet
 *             (http://www.acme.org/Servlet) failed with a status <> OK
 *             (200).
 * @throws IOException
 *             For all other IO / Network / System Error
 */
@Override
public InputStream getInputStream(List<SimpleNameValuePair> requestParams)
        throws IllegalArgumentException, UnknownHostException, ConnectException, RemoteException, IOException {

    InputStream in = null;

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

    URL theUrl;
    theUrl = new URL(this.url);

    conn = buildHttpUrlConnection(theUrl);
    conn.setRequestMethod(POST);
    conn.setDoOutput(true);

    debug("requestParams: " + requestParams);

    TimeoutConnector timeoutConnector = new TimeoutConnector(conn, connectTimeout);
    OutputStream os = timeoutConnector.getOutputStream();

    Writer writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(getPostDataString(requestParams));

    // writer.flush();
    writer.close();
    os.close();

    // 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(
                theUrl + ": Servlet failed: " + conn.getResponseMessage() + " status: " + statusCode);
    }

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

    return in;
}

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

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#listUserAccounts()
 *//*from   w  w w . j ava  2  s .  c om*/
public synchronized List<String[]> listUserAccounts() throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME + "#listUserAccounts() throws UserManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
    }

    List<String[]> results = null;
    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");
        }

        SearchRequest searchReq = new SearchRequest(
                repoConfig.getRepositoryUserBase() + "," + repoConfig.getRepositoryBaseDN(), SearchScope.SUB,
                Filter.create("(&(objectClass=" + repoConfig.getBaseObject() + "))"));

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

        SearchResult searchResult = ldapConn.search(searchReq);

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

        if (searchResult.getResultCode() == ResultCode.SUCCESS) {
            results = new ArrayList<String[]>();

            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
                String[] userData = new String[] { entry.getAttributeValue(userAttributes.getCommonName()),
                        entry.getAttributeValue(userAttributes.getUserId()) };

                if (DEBUG) {
                    for (String str : userData) {
                        DEBUGGER.debug(str);
                    }
                }

                results.add(userData);
            }
        } else {
            throw new ConnectException("No users were located with the search data provided");
        }
    } 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 results;
}

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

private synchronized <T extends DummyObject> void deleteObjectByName(Class<T> type, Map<String, T> map,
        String name) throws ObjectDoesNotExistException, ConnectException, FileNotFoundException {
    if (deleteBreakMode == BreakMode.NONE) {
        // go on/*from  w  w  w .j a  va 2s.c om*/
    } 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);
    }

    String normalName = normalize(name);
    T existingObject;

    if (!enforceUniqueName) {
        throw new IllegalStateException("Whoops! got into deleteObjectByName without enforceUniqueName");
    }

    if (map.containsKey(normalName)) {
        existingObject = map.get(normalName);
        map.remove(normalName);
        allObjects.remove(existingObject.getId());
    } 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, existingObject.getId(), name, DummyDeltaType.DELETE);
        deltas.add(delta);
    }
}