Example usage for java.net SocketException SocketException

List of usage examples for java.net SocketException SocketException

Introduction

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

Prototype

public SocketException(String msg) 

Source Link

Document

Constructs a new SocketException with the specified detail message.

Usage

From source file:org.jnode.net.ipv4.tcp.TCPProtocol.java

/**
 * @see org.jnode.net.TransportLayer#getDatagramSocketImplFactory()
 *//* www . j a  v  a 2s .  com*/
public DatagramSocketImplFactory getDatagramSocketImplFactory() throws SocketException {
    throw new SocketException("TCP is socket based");
}

From source file:org.alfresco.repo.webdav.GetMethodTest.java

@Test
public void readByteRangeContentDoesNotLogSocketExceptions() throws IOException, WebDAVServerException {
    // getContentService() during range request
    when(davHelper.getServiceRegistry()).thenReturn(serviceRegistry);
    when(serviceRegistry.getContentService()).thenReturn(contentService);

    req.addHeader("Range", "bytes=500-1500");
    getMethod.parseRequestHeaders();// www . j a  v  a  2 s . c  o m
    SocketException sockEx = new SocketException("Client aborted connection");
    IOException ioEx = new IOException("Wrapping the socket exception.", sockEx);

    // Somewhere along the line a client disconnect will happen (IOException)
    when(resp.getOutputStream()).thenThrow(ioEx);

    try {
        getMethod.readContent(fileInfo, reader);
        fail("Exception should have been thrown.");
    } catch (WebDAVServerException e) {
        verify(logger, never()).error(anyString(), same(ioEx));
        verify(logger).debug(anyString(), same(ioEx));
        assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getHttpStatusCode());
        assertNull(e.getCause()); // Avoids logging stacking trace
    }
}

From source file:org.apache.solr.client.solrj.impl.CloudSolrClientCacheTest.java

public void testCaching() throws Exception {
    String collName = "gettingstarted";
    Set<String> livenodes = new HashSet<>();
    Map<String, ClusterState.CollectionRef> refs = new HashMap<>();
    Map<String, DocCollection> colls = new HashMap<>();

    class Ref extends ClusterState.CollectionRef {
        private String c;

        public Ref(String c) {
            super(null);
            this.c = c;
        }//  www  .  j  a v  a 2s .c  o  m

        @Override
        public boolean isLazilyLoaded() {
            return true;
        }

        @Override
        public DocCollection get() {
            gets.incrementAndGet();
            return colls.get(c);
        }
    }
    Map<String, Function> responses = new HashMap<>();
    NamedList okResponse = new NamedList();
    okResponse.add("responseHeader", new NamedList<>(Collections.singletonMap("status", 0)));

    LBHttpSolrClient mockLbclient = getMockLbHttpSolrClient(responses);
    AtomicInteger lbhttpRequestCount = new AtomicInteger();
    try (CloudSolrClient cloudClient = new CloudSolrClientBuilder(getStateProvider(livenodes, refs))
            .withLBHttpSolrClient(mockLbclient).build()) {
        livenodes.addAll(ImmutableSet.of("192.168.1.108:7574_solr", "192.168.1.108:8983_solr"));
        ClusterState cs = ClusterState.load(1, coll1State.getBytes(UTF_8), Collections.emptySet(),
                "/collections/gettingstarted/state.json");
        refs.put(collName, new Ref(collName));
        colls.put(collName, cs.getCollectionOrNull(collName));
        responses.put("request", o -> {
            int i = lbhttpRequestCount.incrementAndGet();
            if (i == 1)
                return new ConnectException("TEST");
            if (i == 2)
                return new SocketException("TEST");
            if (i == 3)
                return new NoHttpResponseException("TEST");
            return okResponse;
        });
        UpdateRequest update = new UpdateRequest().add("id", "123", "desc", "Something 0");

        cloudClient.request(update, collName);
        assertEquals(2, refs.get(collName).getCount());
    }

}

From source file:com.clustercontrol.poller.impl.UdpTransportMappingImpl.java

/**
 * Starts the listener thread that accepts incoming messages. The thread is
 * started in daemon mode and thus it will not block application terminated.
 * Nevertheless, the {@link #close()} method should be called to stop the
 * listen thread gracefully and free associated ressources.
 *
 * @throws IOException/*from   ww w  . ja  v a 2s.c  om*/
 */
public synchronized void listen() throws IOException {
    if (listener != null) {
        throw new SocketException("Port already listening");
    }
    ensureSocket();
    listenerThread = new ListenThread();
    listener = SNMP4JSettings.getThreadFactory().createWorkerThread(
            "DefaultUDPTransportMapping_" + getAddress() + "-" + threadSerial, listenerThread, true);
    if (threadSerial == Integer.MAX_VALUE) {
        threadSerial = 0;
    } else {
        threadSerial++;
    }
    listener.run();
}

From source file:sos.net.SOSFTPS.java

public void connect(String ftpHost, int ftpPort1) throws SocketException, IOException {
    initProxy();//ww  w  .  j av  a2s.c o  m
    if (isConnected() == false) {
        this.setSocketFactory(new SOSSSLSocketFactory(getProxyHost(), getProxyPort(), getSecurityProtocol()));
        //         this.setSocketFactory(new SOSSSLSocketFactory());
        try {
            super.connect(ftpHost, ftpPort1);
        } catch (NullPointerException e) {
            throw new SocketException(
                    "Connect failed! Probably HTTP proxy in use or the entered ftps port is invalid: "
                            + e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new SocketException("Connect failed, reason: " + e.toString());
        }
        this.sendCommand("PBSZ 0");
        this.sendCommand("PROT P");
        this.enterLocalPassiveMode();
    }
}

From source file:org.esa.nest.util.ftpUtils.java

public FTPError retrieveFile(final String remotePath, final File localFile, final Long fileSize)
        throws Exception {
    BufferedOutputStream fos = null;
    InputStream fis = null;/*from w  ww.j  a  v a  2 s.c o  m*/
    try {
        System.out.println("ftp retrieving " + remotePath);

        fis = ftpClient.retrieveFileStream(remotePath);
        if (fis == null) {
            final int code = ftpClient.getReplyCode();
            System.out.println("error code:" + code + " on " + remotePath);
            if (code == 550)
                return FTPError.FILE_NOT_FOUND;
            else
                return FTPError.READ_ERROR;
        }

        final File parentFolder = localFile.getParentFile();
        if (!parentFolder.exists()) {
            parentFolder.mkdirs();
        }
        fos = new BufferedOutputStream(new FileOutputStream(localFile.getAbsolutePath()));

        final StatusProgressMonitor status = new StatusProgressMonitor(fileSize,
                "Downloading " + localFile.getName() + "... ");
        status.setAllowStdOut(false);

        final int size = 4096;//32768;
        final byte[] buf = new byte[size];
        int n;
        int total = 0;
        while ((n = fis.read(buf, 0, size)) > -1) {
            fos.write(buf, 0, n);
            if (fileSize != null) {
                total += n;
                status.worked(total);
            } else {
                status.working();
            }
        }
        status.done();

        ftpClient.completePendingCommand();
        return FTPError.OK;

    } catch (SocketException e) {
        System.out.println(e.getMessage());
        connect();
        throw new SocketException(e.getMessage() + "\nPlease verify that FTP is not blocked by your firewall.");
    } catch (Exception e) {
        System.out.println(e.getMessage());
        connect();
        return FTPError.READ_ERROR;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.comcast.cats.telnet.TelnetConnection.java

/**
 * Connect to the telnet client with a password.
 *
 * @param isEnterRequired//w  w  w  . j  a v a2  s .  c  om
 *            : sometime an ENTER key maybe required to reach the prompt.
 *
 * @param password
 * @param passwordPromptString
 *            : the prompt that asks for a password : usually something like
 *            "Enter Password :"
 * @return true if connected successfully
 * @throws SocketException
 * @throws IOException
 */
public synchronized Boolean connectWithPassword(String password, String passwordPromptString,
        Boolean isEnterRequired) throws SocketException, IOException {
    if (!isConnected && password != null && passwordPromptString != null) {
        try {
            telnetClient.connect(getHost(), getPort());
            logger.info("connected to telnet host " + host + " port " + port);
        } catch (SocketException e) {
            logger.warn("Could not connect to telnetSession " + e.getMessage());
            throw new SocketException(e.getMessage());
        }

        is = telnetClient.getInputStream();
        os = new PrintStream(telnetClient.getOutputStream());

        if (isEnterRequired) {
            os.println();
        }

        String passwordPrompt = readUntil(passwordPromptString);
        logger.debug("passwordPrompt " + passwordPrompt);
        if (passwordPrompt != null) {
            write(password);
            isConnected = true;
            lastActiveTime = new Date();
        } else {
            logger.info("Prompt string could not be reached");
            disconnect();
        }

    }
    return isConnected;
}

From source file:ch.cyberduck.core.pool.DefaultSessionPoolTest.java

@Test
public void testCheckReconnectSocketFailure() throws Exception {
    final AtomicBoolean interrupt = new AtomicBoolean();
    final Host bookmark = new Host(new TestProtocol());
    final TestLoginConnectionService connect = new TestLoginConnectionService() {
        @Override/*w  w  w  . j  a va2 s  . c  om*/
        public boolean check(final Session<?> session, final Cache<Path> cache, final CancelCallback callback)
                throws BackgroundException {
            return true;
        }
    };
    final DefaultSessionPool pool = new DefaultSessionPool(connect,
            new DefaultVaultRegistry(new DisabledPasswordCallback()), PathCache.empty(),
            new DisabledTranscriptListener(), bookmark,
            new GenericObjectPool<Session>(new PooledSessionFactory(connect, new DisabledX509TrustManager(),
                    new DefaultX509KeyManager(), PathCache.empty(), bookmark,
                    new DefaultVaultRegistry(new DisabledPasswordCallback())) {
                @Override
                public Session create() {
                    return new NullSession(bookmark) {
                        @Override
                        public void interrupt() throws BackgroundException {
                            interrupt.set(true);
                            super.interrupt();
                        }
                    };
                }
            }));
    final Session<?> session = pool.borrow(BackgroundActionState.running);
    pool.release(session, new BackgroundException("m", new SocketException("m")));
    assertTrue(interrupt.get());
}

From source file:org.restcomm.sbc.media.MediaZone.java

public void setLocalProxy(String proxyHost) throws UnknownHostException, SocketException {
    this.proxyHost = proxyHost;

    proxyAddress = new InetSocketAddress(proxyHost, proxyPort);

    try {// ww  w  .  j  av  a 2s  .c  o m
        channel = DatagramChannel.open();
        channel.bind(proxyAddress);
    } catch (IOException e) {
        throw new SocketException(e.getMessage());
    }

    socket = channel.socket();

    if (LOG.isTraceEnabled()) {
        LOG.trace("Opened socket " + proxyAddress.toString() + " for " + this.toPrint());
    }

    if (!canMux) {
        rtcpProxyAddress = new InetSocketAddress(proxyHost, proxyPort + 1);

        try {
            rtcpChannel = DatagramChannel.open();
            rtcpChannel.bind(rtcpProxyAddress);
        } catch (IOException e) {
            throw new SocketException(e.getMessage());
        }

        rtcpSocket = rtcpChannel.socket();

        if (LOG.isTraceEnabled()) {
            LOG.trace("Opened socket " + rtcpProxyAddress.toString() + " for " + this.toPrint());
        }
    }

}

From source file:org.esa.snap.core.dataop.downloadable.FtpDownloader.java

public FTPError retrieveFile(final String remotePath, final File localFile, final Long fileSize)
        throws Exception {
    BufferedOutputStream fos = null;
    InputStream fis = null;/*from w w  w.  j  a  v  a  2s  . co  m*/
    try {
        SystemUtils.LOG.info("ftp retrieving " + remotePath);

        fis = ftpClient.retrieveFileStream(remotePath);
        if (fis == null) {
            final int code = ftpClient.getReplyCode();
            SystemUtils.LOG.severe("error code:" + code + " on " + remotePath);
            if (code == 550)
                return FTPError.FILE_NOT_FOUND;
            else
                return FTPError.READ_ERROR;
        }

        final File parentFolder = localFile.getParentFile();
        if (!parentFolder.exists()) {
            parentFolder.mkdirs();
        }
        fos = new BufferedOutputStream(new FileOutputStream(localFile.getAbsolutePath()));

        progressListenerList.fireProcessStarted("Downloading " + localFile.getName() + "... ", 0,
                fileSize.intValue());

        final int size = 4096;
        final byte[] buf = new byte[size];
        int n;
        int total = 0;
        while ((n = fis.read(buf, 0, size)) > -1) {
            fos.write(buf, 0, n);
            if (fileSize != null) {
                total += n;
                progressListenerList.fireProcessInProgress(total);
            }
        }
        progressListenerList.fireProcessEnded(true);

        ftpClient.completePendingCommand();
        return FTPError.OK;

    } catch (SocketException e) {
        SystemUtils.LOG.severe(e.getMessage());
        connect();
        throw new SocketException(e.getMessage() + "\nPlease verify that FTP is not blocked by your firewall.");
    } catch (Exception e) {
        SystemUtils.LOG.severe(e.getMessage());
        connect();
        return FTPError.READ_ERROR;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            SystemUtils.LOG.severe("Unable to close input stream " + e.getMessage());
        }
    }
}