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:eu.stratosphere.pact.test.util.minicluster.NepheleMiniCluster.java

private static NetworkInterface getNetworkInterface() throws SocketException {
    final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        if (!nic.isLoopback() && !nic.isPointToPoint())
            return nic;
    }//w  w  w. j a  v a  2  s  .  c o  m

    throw new SocketException("Cannot find network interface which is not a loopback interface.");
}

From source file:io.confluent.rest.SslTest.java

@Test(expected = SocketException.class)
public void testHttpsWithAuthAndNoClientCert() throws Exception {
    Properties props = new Properties();
    String uri = "https://localhost:8080";
    props.put(RestConfig.LISTENERS_CONFIG, uri);
    configServerKeystore(props);/*from w  w  w. j  a va2 s  . c  o  m*/
    configServerTruststore(props);
    enableSslClientAuth(props);
    TestRestConfig config = new TestRestConfig(props);
    SslTestApplication app = new SslTestApplication(config);
    try {
        app.start();
        try {
            makeGetRequest(uri + "/test");
        } catch (SSLHandshakeException she) {
            // JDK7 will throw the SHE, but JDK8 will throw the SE. This catch allows this code
            // to run on JDK7 and JDK8.
            throw new SocketException(she.toString());
        }
    } finally {
        app.stop();
    }
}

From source file:org.apache.hama.pipes.PipesApplication.java

/**
 * Start the child process to handle the task for us.
 * /*from   w w w  . j  a  v  a 2s.  co  m*/
 * @param peer the current peer including the task's configuration
 * @throws InterruptedException
 * @throws IOException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void start(BSPPeer<K1, V1, K2, V2, M> peer) throws IOException, InterruptedException {

    Map<String, String> env = setupEnvironment(peer.getConfiguration());
    List<String> cmd = setupCommand(peer.getConfiguration());

    // wrap the command in a stdout/stderr capture
    TaskAttemptID taskid = peer.getTaskId();
    File stdout = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDOUT);
    File stderr = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDERR);

    // Get the desired maximum length of task's logs.
    long logLength = TaskLog.getTaskLogLength(peer.getConfiguration());

    if (!streamingEnabled) {
        cmd = TaskLog.captureOutAndError(null, cmd, stdout, stderr, logLength);
    } else {
        // use tee in streaming to get the output to file
        cmd = TaskLog.captureOutAndErrorTee(null, cmd, stdout, stderr, logLength);
    }

    /* Check if Parent folders for STDOUT exist */
    checkParentFile(stdout);
    LOG.debug("STDOUT: " + stdout.getAbsolutePath());
    /* Check if Parent folders for STDERR exist */
    checkParentFile(stderr);
    LOG.debug("STDERR: " + stderr.getAbsolutePath());

    LOG.debug("DEBUG: cmd: " + cmd);
    process = runClient(cmd, env); // fork c++ binary

    try {
        if (streamingEnabled) {
            downlink = new StreamingProtocol(peer, process.getOutputStream(), process.getInputStream());
        } else {
            LOG.debug("DEBUG: waiting for Client at " + serverSocket.getLocalSocketAddress());
            serverSocket.setSoTimeout(SERVER_SOCKET_TIMEOUT);
            clientSocket = serverSocket.accept();
            LOG.debug("DEBUG: Client connected! - start BinaryProtocol!");

            downlink = new BinaryProtocol<K1, V1, K2, V2, M>(peer, clientSocket.getOutputStream(),
                    clientSocket.getInputStream());
        }

        downlink.start();

    } catch (SocketException e) {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(stderr)));

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            LOG.error("PipesApp Error: " + inputLine);
        }
        br.close();

        throw new SocketException("Timout: Client pipes application did not connect!");
    }
}

From source file:com.qwazr.server.configuration.ServerConfiguration.java

private static String findPublicAddress(final String addressPattern, final String listenAddress)
        throws SocketException {
    if (StringUtils.isEmpty(addressPattern))
        return StringUtils.isEmpty(listenAddress) || DEFAULT_LISTEN_ADDRESS.equals(listenAddress)
                ? getLocalHostAddress()/*  www .j  av  a  2 s.  c om*/
                : listenAddress;
    final ArrayList<String> list = new ArrayList<>();
    findMatchingAddress(addressPattern, list);
    if (list.isEmpty())
        throw new SocketException("Failed in finding a matching public IP address. Pattern: " + addressPattern);
    if (list.size() > 1)
        LOGGER.warning(() -> "Several matching IP adresses where found (" + list.size() + ')');
    return list.get(0);
}

From source file:edu.si.services.beans.cameratrap.UnifiedCameraTrapIngestRoutesTest.java

@Test
public void testFitsSocketException() throws Exception {

    Integer minSocketExRedelivery = Integer.valueOf(getExtra().getProperty("min.socketEx.redeliveries"));

    MockEndpoint mockResult = getMockEndpoint("mock:result");
    mockResult.expectedMinimumMessageCount(1);
    mockResult.setAssertPeriod(1500);/*from ww  w  .ja  v a2s.c om*/

    MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);
    mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(SocketException.class);
    mockError.expectedHeaderReceived("redeliveryCount", minSocketExRedelivery);
    mockResult.setAssertPeriod(1500);

    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("direct:addFITSDataStream");
        }
    });

    context.getRouteDefinition("UnifiedCameraTrapAddFITSDataStream").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    //processor used to replace sql query to test onException and retries
                    final Processor processor = new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            in.setHeader("redeliveryCount",
                                    in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class));
                            throw new SocketException("Simulating java.net.SocketException: Connection reset");
                        }
                    };

                    weaveById("fitsServiceException").after().to("mock:error");
                    weaveById("fitsHttpRequest").replace().process(processor);
                    weaveById("fitsAddDatastream").replace()
                            .log(LoggingLevel.INFO, "Skipping Fedora addDatastream!!!").to("mock:result");

                }
            });

    Exchange exchange = new DefaultExchange(context);
    exchange.getIn().setHeader("CamelFileAbsolutePath",
            KARAF_HOME + "/UnifiedManifest-TestFiles/scbi_unified_stripped_p125d18981/d18981s1i1.JPG");

    template.send("direct:start", exchange);

    assertMockEndpointsSatisfied();
}

From source file:com.moilioncircle.redis.replicator.RedisSocketReplicator.java

private void connect() throws IOException {
    if (!connected.compareAndSet(false, true))
        return;//from w  w  w .  j  a v  a  2s  .  co m

    socket = new Socket();
    socket.setReuseAddress(true);
    socket.setKeepAlive(true);
    socket.setTcpNoDelay(true);
    socket.setSoLinger(true, 0);
    if (configuration.getReadTimeout() > 0) {
        socket.setSoTimeout(configuration.getReadTimeout());
    }
    if (configuration.getReceiveBufferSize() > 0) {
        socket.setReceiveBufferSize(configuration.getReceiveBufferSize());
    }
    if (configuration.getSendBufferSize() > 0) {
        socket.setSendBufferSize(configuration.getSendBufferSize());
    }
    socket.connect(new InetSocketAddress(host, port), configuration.getConnectionTimeout());
    if (configuration.isSsl()) {
        SSLSocketFactory sslSocketFactory = configuration.getSslSocketFactory();
        socket = sslSocketFactory.createSocket(socket, host, port, true);

        if (configuration.getSslParameters() != null) {
            ((SSLSocket) socket).setSSLParameters(configuration.getSslParameters());
        }

        if (configuration.getHostnameVerifier() != null
                && !configuration.getHostnameVerifier().verify(host, ((SSLSocket) socket).getSession())) {
            throw new SocketException("the connection to " + host + " failed ssl/tls hostname verification.");
        }
    }
    outputStream = new RedisOutputStream(socket.getOutputStream());
    inputStream = new RedisInputStream(socket.getInputStream(), configuration.getBufferSize());
    replyParser = new ReplyParser(inputStream);
}

From source file:us.paulevans.basicxslt.Utils.java

/**
 * Method to determine if inputted xml file is valid and well-formed.
 * @param saXmlFile/*from  w w  w  . j  av  a2s .c o m*/
 * @throws Exception If saXmlFile is invalid or not well-formed.
 */
public void isValidXml(FileContent faXmlFile, boolean aCheckWarning, boolean aCheckError,
        boolean aCheckFatalError) throws SAXNotSupportedException, SAXNotRecognizedException,
        ParserConfigurationException, SAXException, IOException {

    SAXParserFactory factory;

    checkWarning = aCheckWarning;
    checkError = aCheckError;
    checkFatalError = aCheckFatalError;
    factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    try {
        factory.setFeature(VALIDATION_FEATURE, true);
        factory.setFeature(SCHEMA_FEATURE, true);
        SAXParser parser = factory.newSAXParser();
        parser.parse(faXmlFile.getInputStream(), this);
    } catch (UnknownHostException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new UnknownHostException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SocketException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new SocketException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SAXNotSupportedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXNotRecognizedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (ParserConfigurationException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (IOException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    }
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

public Object getOption(int optID) throws SocketException {
    if (optID == SocketOptions.SO_SNDBUF)
        return Integer.valueOf(1024);
    else//from  ww w  . ja  v  a  2 s .c  o m
        throw new SocketException("SSHSocketImpl does not implement getOption for " + optID);
}

From source file:edu.si.services.beans.cameratrap.UnifiedCameraTrapIngestRoutesTest.java

@Test
public void testFitsSocketExceptionAndExecFail() throws Exception {

    Integer minSocketExRedelivery = Integer.valueOf(getExtra().getProperty("min.socketEx.redeliveries"));

    MockEndpoint mockResult = getMockEndpoint("mock:result");
    mockResult.expectedMinimumMessageCount(0); //we should not
    mockResult.setAssertPeriod(1500);/*w w  w .j  a  v a2s .  c  o  m*/

    MockEndpoint mockError = getMockEndpoint("mock:error");
    mockError.expectedMessageCount(1);
    mockError.message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(SocketException.class);
    mockError.expectedHeaderReceived("redeliveryCount", minSocketExRedelivery);
    mockResult.setAssertPeriod(1500);

    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("direct:addFITSDataStream");
        }
    });

    context.getRouteDefinition("UnifiedCameraTrapAddFITSDataStream").adviceWith(context,
            new AdviceWithRouteBuilder() {
                @Override
                public void configure() throws Exception {
                    //processor used to replace sql query to test onException and retries
                    final Processor processor = new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            Message in = exchange.getIn();
                            in.setHeader("redeliveryCount",
                                    in.getHeader(Exchange.REDELIVERY_COUNTER, Integer.class));
                            throw new SocketException("Simulating java.net.SocketException: Connection reset");
                        }
                    };

                    weaveById("fitsServiceException").after().to("mock:error");
                    weaveById("fitsHttpRequest").replace().process(processor);
                    weaveById("fitsAddDatastream").replace()
                            .log(LoggingLevel.INFO, "Skipping Fedora addDatastream!!!").to("mock:result");

                }
            });

    Exchange exchange = new DefaultExchange(context);
    //exchange.getIn().setHeader("CamelFileAbsolutePath", KARAF_HOME + "/UnifiedManifest-TestFiles/scbi_unified_stripped_p125d18981/d18981s1i1.JPG");

    template.send("direct:start", exchange);

    assertMockEndpointsSatisfied();
}

From source file:org.ikasan.connector.ftp.net.FileTransferProtocolClient.java

/**
 * Method that handles the creation and connection for FTP.
 * //from  w ww.java2  s. c om
 * @throws ClientConnectionException if connection attempt fails
 */
private void doConnect() throws ClientConnectionException {

    this.ftpClient = new FTPClient();

    String msg = new String("Attempting connection to [" + remoteHostname + "]."); //$NON-NLS-1$ //$NON-NLS-2$
    logger.debug(msg);
    try {
        /*
         * Summer (Nov 26th 2008): Rather than relying on the FTP client to
         * figure out the system it is connecting to (and hence what parsers
         * it should use) we pass this configuration to the client and force
         * it to use it.
         */
        if ((systemKey != null) && (!"".equals(systemKey))) {
            ftpClient.configure(new FTPClientConfig(systemKey));
        }
        // leave local port unspecified
        int localPort = 0;
        this.ftpClient.setDefaultTimeout(this.connectionTimeout);
        // Keep trying to connect, until successful
        for (int i = 0; i < DEFAULT_MAXIMUM_LOCAL_PORT; i++) {
            try {
                logger.debug("Connecting to remote host [" + this.remoteHostname + ":" + this.remotePort
                        + "] from local host [" + this.localHostname + ":" + localPort + "].");
                // Had to update the  ftpClient.connect method as the localhost was not resolving correctly
                //ftpClient.connect(InetAddress.getByName(this.remoteHostname), this.remotePort, InetAddress.getByName(this.localHostname), localPort);
                ftpClient.connect(InetAddress.getByName(this.remoteHostname), this.remotePort);

                int reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    throw new SocketException("Connection attempt failed with replyCode [" + reply + "]");
                }

                if (active) {
                    this.ftpClient.enterLocalActiveMode();
                } else {
                    this.ftpClient.enterLocalPassiveMode();
                }

                this.ftpClient.setSoTimeout(this.socketTimeout);
                this.ftpClient.setDataTimeout(this.dataTimeout);
                break;
            } catch (BindException be) {
                logger.info("Address is already in use.. will try again.", be);
            }
        }
    } catch (SocketException se) {
        msg = new String(msg + " [Failed]"); //$NON-NLS-1$
        logger.info(msg, se);
        // Clean up after ourselves just in case
        try {
            if (this.ftpClient != null && this.ftpClient.isConnected()) {
                this.ftpClient.disconnect();
            }
        } catch (IOException disconnectException) {
            logger.warn("Could not cleanup after a failed connect, this may leave behind open sockets.",
                    disconnectException);
        }
        throw new ClientConnectionException(msg, se);
    } catch (IOException ie) {
        msg = new String(msg + " [Failed]"); //$NON-NLS-1$
        logger.info(msg, ie);
        // Clean up after ourselves
        try {
            if (this.ftpClient != null && this.ftpClient.isConnected()) {
                this.ftpClient.disconnect();
            }
        } catch (IOException disconnectException) {
            logger.warn("Could not cleanup after a failed connect, this may leave behind open sockets.",
                    disconnectException);
        }
        throw new ClientConnectionException(msg, ie);
    }

    logger.info(
            "Connected to host [" + remoteHostname + "]. " + "Mode [" + (active ? "active" : "passive") + "].");
}