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.bbytes.jfilesync.sync.JFileSyncListenerClientThread.java

public void copyFileToDestinationFolder(File dir, FileSyncMessage fileSyncMessage) {
    try {//from www . jav a 2 s.co  m
        if (ftpClient == null || !ftpClient.isConnected()) {
            ftpClient = ftpClientFactory.getClientInstance();
            if (!ftpClient.isConnected()) {
                throw new ConnectException("FTP client not connected. Make sure FTP server is running");
            }
        }
        FTPFile file = ftpClient
                .mlistFile(fileSyncMessage.getBaseFolderRelativePath() + "/" + fileSyncMessage.getFileName());
        OutputStream output;
        output = new FileOutputStream(dir.getPath() + File.separator + fileSyncMessage.getFileName());
        // get the file from the remote system
        ftpClient.retrieveFile(fileSyncMessage.getFileName(), output);
        // close output stream
        output.close();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:org.kawanfw.sql.api.server.web.WebServerApi.java

/**
 * Stops the embedded Web server running on the designated port.
 * //ww w . jav  a2  s.  co m
 * @param port
 *            the port on which the SQL Web server is running
 * 
 * @throws IOException
 *             if the semaphore file (that signals to the Web Server to
 *             stop) can not be created
 */
public void stopServer(int port) throws IOException {

    PortSemaphoreFile portSemaphoreFile = new PortSemaphoreFile(port);

    if (!portSemaphoreFile.exists()) {
        throw new ConnectException("WARNING! There is no SQL Web server running on port " + port);
    }

    // Always Force the deletion of the semaphore file:
    try {
        portSemaphoreFile.delete();
    } catch (IOException ioe) {
        throw new IOException("Can not stop the Web server. Please delete manually the semaphore file "
                + portSemaphoreFile.getSemaphoreFile() + " and then retry. ", ioe);
    }

    if (TomcatStarterUtil.available(port)) {
        throw new ConnectException("WARNING! There is no SQL Web server running on port " + port);
    }

}

From source file:org.apache.hadoop.hbase.client.TestFastFailWithoutTestUtil.java

public void testInterceptorIntercept() throws IOException, InterruptedException {
    Configuration conf = HBaseConfiguration.create();
    long CLEANUP_TIMEOUT = 50;
    long FAST_FAIL_THRESHOLD = 10;
    conf.setBoolean(HConstants.HBASE_CLIENT_FAST_FAIL_MODE_ENABLED, true);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_CLEANUP_MS_DURATION_MS, CLEANUP_TIMEOUT);
    conf.setLong(HConstants.HBASE_CLIENT_FAST_FAIL_THREASHOLD_MS, FAST_FAIL_THRESHOLD);

    PreemptiveFastFailInterceptor interceptor = TestFastFailWithoutTestUtil.createPreemptiveInterceptor(conf);
    FastFailInterceptorContext context = (FastFailInterceptorContext) interceptor.createEmptyContext();

    RetryingCallable<?> callable = getDummyRetryingCallable(getSomeServerName());

    // Lets simulate some work flow here.
    int tries = 0;
    context.prepare(callable, tries);//  w w w  .j  a  va  2  s  . c  o m
    interceptor.intercept(context);
    interceptor.handleFailure(context, new ConnectException("Failed to connect to server"));
    interceptor.updateFailureInfo(context);
    assertTrue("Interceptor should have updated didTry to true", context.didTry());
    assertTrue("The call shouldn't have been successful if there was a ConnectException",
            context.getCouldNotCommunicateWithServer().booleanValue());
    assertNull("Once a failure is identified, the first time the FailureInfo is generated for the server,"
            + " but it is not assigned to the context yet. It would be assigned on the next" + " intercept.",
            context.getFailureInfo());
    assertEquals(context.getTries(), tries);
    assertFalse("We are still in the first attempt and so we dont set this variable to true yet.",
            context.isRetryDespiteFastFailMode());

    Thread.sleep(FAST_FAIL_THRESHOLD + 1); // We sleep so as to make sure that
                                           // we
                                           // actually consider this server as a
                                           // dead server in the next attempt.
    tries++;

    context.prepare(callable, tries);
    interceptor.intercept(context);
    interceptor.handleFailure(context, new ConnectException("Failed to connect to server"));
    interceptor.updateFailureInfo(context);
    assertTrue("didTru should remain true", context.didTry());
    assertTrue("The call shouldn't have been successful if there was a ConnectException",
            context.getCouldNotCommunicateWithServer().booleanValue());
    assertNotNull("The context this time is updated with a failureInfo, since we already gave it a try.",
            context.getFailureInfo());
    assertEquals(context.getTries(), tries);
    assertTrue("Since we are alone here we would be given the permission to retryDespiteFailures.",
            context.isRetryDespiteFastFailMode());
    context.clear();

    Thread.sleep(CLEANUP_TIMEOUT); // Lets try and cleanup the data in the fast
                                   // fail failure maps.

    tries++;

    context.clear();
    context.prepare(callable, tries);
    interceptor.occasionallyCleanupFailureInformation();
    assertNull("The cleanup should have cleared the server",
            interceptor.repeatedFailuresMap.get(context.getServer()));
    interceptor.intercept(context);
    interceptor.handleFailure(context, new ConnectException("Failed to connect to server"));
    interceptor.updateFailureInfo(context);
    assertTrue("didTru should remain true", context.didTry());
    assertTrue("The call shouldn't have been successful if there was a ConnectException",
            context.getCouldNotCommunicateWithServer().booleanValue());
    assertNull("The failureInfo is cleared off from the maps.", context.getFailureInfo());
    assertEquals(context.getTries(), tries);
    assertFalse("Since we are alone here we would be given the permission to retryDespiteFailures.",
            context.isRetryDespiteFastFailMode());
    context.clear();

}

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

/**
 * @see com.cws.esolutions.security.dao.usermgmt.interfaces.UserManager#addUserAccount(java.util.List, java.util.List)
 *///from w ww  . ja  v a2  s  .  c o  m
public synchronized boolean addUserAccount(final List<String> userAccount, final List<String> roles)
        throws UserManagementException {
    final String methodName = LDAPUserManager.CNAME
            + "#addUserAccount(final List<String> userAccount, final List<String> roles) throws UserManagementException";

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

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

    try {
        final StringBuilder userDN = new StringBuilder()
                .append(userAttributes.getUserId() + "=" + userAccount.get(0) + ",")
                .append(repoConfig.getRepositoryUserBase() + "," + repoConfig.getRepositoryBaseDN());

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

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

        // have a connection, create the user
        List<Attribute> newAttributes = new ArrayList<Attribute>(
                Arrays.asList(new Attribute("objectClass", repoConfig.getBaseObject()),
                        new Attribute(userAttributes.getCommonName(), userAccount.get(0)),
                        new Attribute(userAttributes.getUserId(), userAccount.get(1)),
                        new Attribute(userAttributes.getEmailAddr(), userAccount.get(2)),
                        new Attribute(userAttributes.getGivenName(), userAccount.get(3)),
                        new Attribute(userAttributes.getSurname(), userAccount.get(4)),
                        new Attribute(userAttributes.getDisplayName(),
                                userAccount.get(3) + " " + userAccount.get(4)),
                        new Attribute(securityAttributes.getIsSuspended(), userAccount.get(5)),
                        new Attribute(securityAttributes.getLockCount(), "0"),
                        new Attribute(securityAttributes.getExpiryDate(), new Date().toString())));

        if (DEBUG) {
            DEBUGGER.debug("List<Attribute>: {}", newAttributes);
        }

        AddRequest addRequest = new AddRequest(userDN.toString(), newAttributes);

        LDAPResult ldapResult = ldapConn.add(addRequest);

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

        if (ldapResult.getResultCode() == ResultCode.SUCCESS) {
            for (String role : roles) {
                if (DEBUG) {
                    DEBUGGER.debug("String: {}", role);
                }

                StringBuilder roleDN = new StringBuilder().append("cn=" + role)
                        .append(repoConfig.getRepositoryRoleBase());

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

                AddRequest addToGroup = new AddRequest(roleDN.toString(),
                        new ArrayList<Attribute>(Arrays.asList(new Attribute("objectClass", "uniqueMember"),
                                new Attribute("uniqueMember", userDN.toString()))));

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

                LDAPResult addToGroupResult = ldapConn.add(addToGroup);

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

                if (addToGroupResult.getResultCode() != ResultCode.SUCCESS) {
                    throw new UserManagementException("Failed to add user to group: " + role);
                }
            }

            return true;
        }
    } catch (ConnectException cx) {
        throw new UserManagementException(cx.getMessage(), cx);
    } catch (LDAPException lx) {
        throw new UserManagementException(lx.getMessage(), lx);
    } finally {
        if ((ldapPool != null) && ((ldapConn != null) && (ldapConn.isConnected()))) {
            ldapConn.close();
            ldapPool.releaseConnection(ldapConn);
        }
    }

    return isUserCreated;
}

From source file:com.hellblazer.process.impl.JavaProcessImpl.java

/**
 * @throws ConnectException//from ww  w  . ja  v a 2  s. c om
 */
@Override
public JMXConnector getLocalJmxConnector(String connectorName)
        throws ConnectException, NoLocalJmxConnectionException {
    if (jmxc != null) {
        return jmxc;
    }

    if (!process.isActive()) {
        throw new ConnectException("Cannot establish local JMX connection as process is not active: " + this);
    }

    String address;
    try {
        VirtualMachine vm = VirtualMachine.attach("" + process.getPid());
        Properties props = vm.getSystemProperties();
        address = props.getProperty(connectorName);

        if (address == null) {
            throw new ConnectException(
                    "Unable to find address for remote JMX connection with name = " + connectorName);
        }
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot obtain local JMX connector address of: " + this);
        cex.initCause(e);
        throw cex;
    } catch (AttachNotSupportedException e) {
        throw new RuntimeException(e);
    }

    JMXServiceURL jmxUrl;
    try {
        jmxUrl = new JMXServiceURL(address);
    } catch (MalformedURLException e) {
        ConnectException cex = new ConnectException("Invalid local JMX URL for " + this + " : " + address);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc = JMXConnectorFactory.connect(jmxUrl);
    } catch (java.rmi.ConnectException e) {
        if (e.getMessage().startsWith("Connection refused")) {
            throw new NoLocalJmxConnectionException("Local JMX connector address does not exist for: " + this);
        }
        ConnectException cex = new ConnectException("Underlying RMI communications exception");
        cex.initCause(e);
        throw cex;
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    try {
        jmxc.connect();
    } catch (IOException e) {
        ConnectException cex = new ConnectException("Cannot establish local JMX connection to: " + this);
        cex.initCause(e);
        throw cex;
    }

    return jmxc;
}

From source file:com.ning.http.client.providers.NettyAsyncHttpProvider.java

Channel performConnect(Url url) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Lookup cache: " + url.toString());

    Channel channel = lookupInCache(url);
    if (channel != null)
        return channel;

    if (log.isDebugEnabled())
        log.debug("performConnect: " + url.toString());
    configure();//from  ww  w .ja va2s.  c o  m
    ChannelFuture channelFuture = null;

    if (config.getProxyServer() == null) {
        channelFuture = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    } else {
        channelFuture = bootstrap.connect(
                new InetSocketAddress(config.getProxyServer().getHost(), config.getProxyServer().getPort()));
    }

    // Blocking connect
    channel = channelFuture.awaitUninterruptibly().getChannel();

    if (!channel.isConnected()) {
        throw new ConnectException("Connection refused: " + url.toString());
    }
    return channel;
}

From source file:org.apache.tajo.rpc.NettyClientBase.java

private ConnectException makeConnectException(InetSocketAddress address, ChannelFuture future) {
    if (future.cause() instanceof UnresolvedAddressException) {
        return new ConnectException("Can't resolve host name: " + address.toString());
    } else {/*from  w w  w .  ja  v  a2  s.c o  m*/
        return new ConnectTimeoutException(future.cause().getMessage());
    }
}

From source file:org.apache.hadoop.hbase.catalog.TestCatalogTracker.java

/**
 * Test we survive a connection refused {@link ConnectException}
 * @throws IOException/*from   w w  w  .  ja  v a  2s  . com*/
 * @throws InterruptedException
 * @throws KeeperException
 * @throws ServiceException
 */
@Test
public void testGetMetaServerConnectionFails()
        throws IOException, InterruptedException, KeeperException, ServiceException {
    testVerifyMetaRegionLocationWithException(new ConnectException("Connection refused"));
}

From source file:org.apache.hadoop.hbase.ipc.HBaseRPC.java

/**
 * @param protocol protocol interface//from   ww w.  j a  v a  2  s  . c o  m
 * @param clientVersion which client version we expect
 * @param addr address of remote service
 * @param conf configuration
 * @param maxAttempts max attempts
 * @param rpcTimeout timeout for each RPC
 * @param timeout timeout in milliseconds
 * @return proxy
 * @throws IOException e
 */
@SuppressWarnings("unchecked")
public static VersionedProtocol waitForProxy(Class protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int maxAttempts, int rpcTimeout, long timeout) throws IOException {
    // HBase does limited number of reconnects which is different from hadoop.
    long startTime = System.currentTimeMillis();
    IOException ioe;
    int reconnectAttempts = 0;
    while (true) {
        try {
            return getProxy(protocol, clientVersion, addr, conf, rpcTimeout);
        } catch (SocketTimeoutException te) { // namenode is busy
            LOG.info("Problem connecting to server: " + addr);
            ioe = te;
        } catch (IOException ioex) {
            // We only handle the ConnectException.
            ConnectException ce = null;
            if (ioex instanceof ConnectException) {
                ce = (ConnectException) ioex;
                ioe = ce;
            } else if (ioex.getCause() != null && ioex.getCause() instanceof ConnectException) {
                ce = (ConnectException) ioex.getCause();
                ioe = ce;
            } else if (ioex.getMessage().toLowerCase().contains("connection refused")) {
                ce = new ConnectException(ioex.getMessage());
                ioe = ce;
            } else {
                // This is the exception we can't handle.
                ioe = ioex;
            }
            if (ce != null) {
                handleConnectionException(++reconnectAttempts, maxAttempts, protocol, addr, ce);
            }
        }
        // check if timed out
        if (System.currentTimeMillis() - timeout >= startTime) {
            throw ioe;
        }

        // wait for retry
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ie) {
            // IGNORE
        }
    }
}

From source file:org.gbif.ipt.service.registry.impl.RegistryManagerImplTest.java

@Test
public void testGetExtensionsThrowsRegistryException()
        throws IOException, URISyntaxException, SAXException, ParserConfigurationException {
    // mock response from Registry as ClassCastException
    ConnectException connectException = new ConnectException("ConnectException occurred!");
    when(mockHttpUtil.get(anyString())).thenThrow(connectException);

    // create instance of RegistryManager
    RegistryManager manager = new RegistryManagerImpl(mockAppConfig, mockDataDir, mockHttpUtil,
            mockSAXParserFactory, mockConfigWarnings, mockSimpleTextProvider, mockRegistrationManager);

    // getExtensions() throws a RegistryException of type PROXY
    try {//w w w .  jav  a 2 s  .c o m
        manager.getExtensions();
    } catch (RegistryException e) {
        assertEquals(RegistryException.TYPE.PROXY, e.getType());
    }
}