Example usage for java.net SocketException getMessage

List of usage examples for java.net SocketException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.axis2.description.AxisEndpoint.java

public String calculateEndpointURL(String hostIP) {
    if (transportInDescName != null && parent != null) {
        AxisConfiguration axisConfiguration = getAxisConfiguration();
        if (axisConfiguration != null) {
            try {
                String serviceName = ((AxisService) parent).getName();
                TransportInDescription in = axisConfiguration.getTransportIn(transportInDescName);
                TransportListener listener = in.getReceiver();
                String ip;// w w w .j  a v a 2 s .  c  o m

                if (hostIP != null) {
                    ip = hostIP;
                } else {
                    ip = Utils.getIpAddress(axisConfiguration);
                }

                // we should pass [serviceName].[endpointName] instead of
                // [endpointName]
                String sDOTe = serviceName + "." + name;
                EndpointReference[] eprsForService = listener.getEPRsForService(sDOTe, ip);
                // we consider only the first address return by the listener
                if (eprsForService != null && eprsForService.length > 0) {
                    return eprsForService[0].getAddress();
                }
            } catch (SocketException e) {
                logger.warn(e.getMessage(), e);
            } catch (AxisFault e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

    return null;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an HTTP connection to a provided website and returns the data back
 * to the requestor./*w  w  w .  jav a  2  s .co  m*/
 *
 * @param hostName - The fully qualified URL for the host desired. MUST be
 *     prefixed with http/https:// as necessary
 * @param methodType - GET or POST, depending on what is necessary
 * @return A object containing the response data
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType)
        throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException";

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

    RequestConfig requestConfig = null;
    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = null;
    CloseableHttpResponse httpResponse = null;

    final HttpClientParams httpParams = new HttpClientParams();
    final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig();
    final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig();

    if (DEBUG) {
        DEBUGGER.debug("HttpClient: {}", httpClient);
        DEBUGGER.debug("HttpClientParams: {}", httpParams);
        DEBUGGER.debug("HTTPConfig: {}", httpConfig);
        DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
    }
    try {
        final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost())
                .setPort(hostName.getPort()).build();

        if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) {
            System.setProperty("javax.net.ssl.trustStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile());
            System.setProperty("javax.net.ssl.trustStorePassword",
                    PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) {
            System.setProperty("javax.net.ssl.keyStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile());
            System.setProperty("javax.net.ssl.keyStorePassword",
                    PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (proxyConfig.isProxyServiceRequired()) {
            if (DEBUG) {
                DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
            }

            if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) {
                throw new UtilityException(
                        "Configuration states proxy usage is required, but no proxy is configured.");
            }

            if (proxyConfig.isProxyAuthRequired()) {
                List<String> authList = new ArrayList<String>();
                authList.add(AuthPolicy.BASIC);
                authList.add(AuthPolicy.DIGEST);
                authList.add(AuthPolicy.NTLM);

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

                requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(
                                (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setContentCompressionEnabled(Boolean.TRUE)
                        .setProxy(new HttpHost(proxyConfig.getProxyServerName(),
                                proxyConfig.getProxyServerPort()))
                        .setProxyPreferredAuthSchemes(authList).build();

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

                String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(),
                        proxyConfig.getProxyPwdSalt(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getIterations(),
                        secBean.getConfigData().getSecurityConfig().getKeyBits(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                        appBean.getConfigData().getSystemConfig().getEncoding());

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

                if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd));
                } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM,
                        proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd,
                                    InetAddress.getLocalHost().getHostName(),
                                    proxyConfig.getProxyAuthDomain()));
                }

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

        synchronized (new Object()) {
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            if (StringUtils.equalsIgnoreCase(methodType, "POST")) {
                HttpPost httpMethod = new HttpPost(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            } else {
                HttpGet httpMethod = new HttpGet(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

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

            if (responseCode != 200) {
                ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode);

                throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode);
            }

            return httpResponse.getEntity().toString();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (URISyntaxException usx) {
        throw new UtilityException(usx.getMessage(), usx);
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException iox) {
            } // dont do anything with it
        }
    }
}

From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java

@Override
public int getSocketTimeout() {
    int timeout = -1;
    LOGGER.trace("Getting socket timeout");
    if (socket != null) {
        try {//w  w w.j  a  v a2 s  .co m
            timeout = sslSocket.getSoTimeout();
        } catch (SocketException e) {
            LOGGER.warn("Error trying to get socket timeout: " + e.getMessage(), e);
        }
    } else {
        LOGGER.debug("Socket is null; no socket timeout");
    }
    return timeout;
}

From source file:com.mirth.connect.connectors.tcp.protocols.DefaultProtocol.java

public byte[] read(InputStream is) throws IOException {
    String charset = _tcpConnector.getCharsetEncoding();
    UtilReader myReader = new UtilReader(is, charset);

    int c = 0;/*  ww w.j a  va  2  s.  c o m*/
    try {
        c = myReader.read();
    } catch (SocketException e) {
        logger.info(
                "SocketException on read() attempt.  Socket appears to have been closed: " + e.getMessage());
        // Throw the exception so the socket can always be recycled.
        throw e;
    } catch (SocketTimeoutException ste) {
        logger.info("SocketTimeoutException on read() attempt.  Socket appears to have been closed: "
                + ste.getMessage());
        /*
         * Throw the exception so the listener can know it was a timeout and
         * decide whether or not to recycle the connection.
         */
        throw ste;
    }

    // trying to read when there is no data (stream may have been closed at
    // other end)
    if (c == -1) {
        logger.info("End of input stream reached.");
        return null;
    }

    while (c != -1) {
        myReader.append((char) c);
        try {
            c = myReader.read();
        } catch (Exception e) {
            c = -1;
        }
    }

    return myReader.getBytes();
}

From source file:com.grendelscan.proxy.ssl.TunneledSSLConnection.java

@Override
public void setSocketTimeout(int timeout) {
    LOGGER.debug("Setting socket timeout to " + timeout);
    assertOpen();//from  w w  w .  j  av  a2s. c o  m
    try {
        socket.setSoTimeout(timeout);
        sslSocket.setSoTimeout(timeout);
    } catch (SocketException e) {
        LOGGER.warn("Error trying to set socket timeout to " + timeout + ": " + e.getMessage(), e);
    }
}

From source file:org.cerberus.launchcampaign.checkcampaign.CheckCampaignStatus.java

/**
 * Check all 5 seconds the status of campaign's execution. 
 * @param checkCampaign call method checkCampaign() all 5 seconds with parameter {@link ResultCIDto}.  
 *                   {@link ResultCIDto} contains all information of execution of campaing at the instant t
 * @param result call method result() when campaign execution is finish.
 *             {@link ResultCIDto} contains all information of execution at finish time
 * @throws Exception // www .j a  va2 s  .  c om
 */
public void execute(final CheckCampaignEvent checkCampaign, final ResultEvent result, final LogEvent logEvent)
        throws Exception {
    final ScheduledThreadPoolExecutor sch = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    final AtomicReference<Exception> exceptionOnThread = new AtomicReference<Exception>();

    sch.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            try {
                URL resultURL = new URL(urlCerberus + "/" + Constantes.URL_RESULT_CI + "?tag=" + tagCerberus);
                ResultCIDto resultDto = new ObjectMapper().readValue(resultURL, ResultCIDto.class);

                // condition to finish task
                if (!"PE".equals(resultDto.getResult())) {
                    result.result(resultDto);
                    sch.shutdown(); // when campaign is finish, we shutdown the schedule thread
                }

                if (!checkCampaign.checkCampaign(resultDto)) {
                    sch.shutdown();
                }
            } catch (SocketException e) {
                // do nothing during network problem. Wait the timeout to shutdown, and notify the error to logEvent
                logEvent.log("", e.getMessage() + "\n" + ExceptionUtils.getStackTrace(e));
            } catch (Exception e) {
                exceptionOnThread.set(e);
                sch.shutdown();
            }
        }
    }, 0, this.timeToRefreshCampaignStatus, TimeUnit.SECONDS);

    sch.awaitTermination(this.timeoutForCampaignExecution, TimeUnit.SECONDS);

    // pass exeption of thread to called method
    if (exceptionOnThread.get() != null) {
        throw exceptionOnThread.get();
    }
}

From source file:org.openhab.binding.russound.internal.discovery.RioSystemDiscovery.java

/**
 * Starts the scan. For each network interface (that is up and not a loopback), all addresses will be iterated
 * and checked for something open on port 9621. If that port is open, a russound controller "type" command will be
 * issued. If the response is a correct pattern, we assume it's a rio system device and will emit a
 * {{@link #thingDiscovered(DiscoveryResult)}
 *///  w  ww . j a va 2s .  c o m
@Override
protected void startScan() {
    final List<NetworkInterface> interfaces;
    try {
        interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
    } catch (SocketException e1) {
        logger.debug("Exception getting network interfaces: {}", e1.getMessage(), e1);
        return;
    }

    nbrNetworkInterfacesScanning = interfaces.size();
    executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 10);

    for (final NetworkInterface networkInterface : interfaces) {
        try {
            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                continue;
            }
        } catch (SocketException e) {
            continue;
        }

        for (Iterator<InterfaceAddress> it = networkInterface.getInterfaceAddresses().iterator(); it
                .hasNext();) {
            final InterfaceAddress interfaceAddress = it.next();

            // don't bother with ipv6 addresses (russound doesn't support)
            if (interfaceAddress.getAddress() instanceof Inet6Address) {
                continue;
            }

            final String subnetRange = interfaceAddress.getAddress().getHostAddress() + "/"
                    + interfaceAddress.getNetworkPrefixLength();

            logger.debug("Scanning subnet: {}", subnetRange);
            final SubnetUtils utils = new SubnetUtils(subnetRange);

            final String[] addresses = utils.getInfo().getAllAddresses();

            for (final String address : addresses) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        scanAddress(address);
                    }
                });
            }
        }
    }

    // Finishes the scan and cleans up
    stopScan();
}

From source file:org.rifidi.emulator.io.comm.ip.udp.UDPCommunicationTest.java

/**
 * Tests turning on the UDPCommunication while it is off.
 * //ww w. ja v a 2  s.c  om
 *  
 */
public void testTurnOnWhenOff() {

    /* Data to send */
    byte[] dataToSend = message.getBytes();

    /* Error code -- gets modified if exceptions occur. */
    boolean error = false;

    /* Attempt to connect to the specified IP/Port using UDP */
    this.udpComm.turnOn();

    /* Allow server socket to fully start */
    synchronized (this) {
        try {
            this.wait(1000);
        } catch (InterruptedException e2) {
            /* Do nothing */
        }
        this.notifyAll();
    }

    /* Make a client */
    DatagramSocket clientSocket = null;
    try {
        clientSocket = new DatagramSocket(this.udpComm.getRemotePort());
    } catch (SocketException e) {
        logger.debug(this.getName() + ": " + e.getMessage());
        error = true;
    }

    /* Send out a packet of data */
    try {
        this.udpComm.getSendBuffer().addToBuffer(dataToSend);
    } catch (DataBufferInterruptedException dbie) {
        logger.debug(this.getName() + ": " + dbie.getMessage());
        error = true;
    }

    /* Receive the packet of data */
    if (clientSocket != null) {
        /* Set a timeout for receiving data */
        try {
            clientSocket.setSoTimeout(1000);
        } catch (SocketException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Make a new packet to hold the received data */
        DatagramPacket dataPacket = new DatagramPacket(new byte[1024], 1024);

        /* Attempt to receive the data */
        try {
            clientSocket.receive(dataPacket);
        } catch (IOException e) {
            logger.debug(this.getName() + ": " + e.getMessage());
            error = true;
        }

        /* Check that the data was received succesfully */
        if (!error) {
            logger.debug("Client received: " + new String(dataPacket.getData()));
        } else {
            logger.debug(this.getName() + ": client did not receive message.");
            error = true;
        }

        clientSocket.disconnect();

        clientSocket.close();
        clientSocket = null;

    }

    /* Check to see if any errors happened. */
    assertFalse(error);

}

From source file:com.jzboy.couchdb.http.CouchHttpClient.java

private JsonNode execRequest(HttpRequestBase req, int retry) throws IOException, CouchDBException {
    int attemptsLeft = retry;
    CouchResponse res = null;//from ww  w . j  a  va2  s  . co  m
    while (res == null && attemptsLeft > 0) {
        try {
            res = httpclient.execute(req, new CouchResponseHandler());
        } catch (java.net.SocketException se) {
            logger.debug("Got {} on update attempt #{} on {}",
                    new Object[] { se.getMessage(), (3 - attemptsLeft + 1), req.getURI() });
            attemptsLeft--;
        }
    }
    if (res == null)
        throw new CouchDBException(
                String.format("Operation failed after %d attempts: %s", retry, req.getURI()));
    throwOnError(res);
    return res.getBodyAsJson();
}

From source file:com.l2jfree.gameserver.geoeditorcon.GeoEditorThread.java

public void sendPing() {
    if (!isConnected())
        return;/*  w w  w .ja va2s . c  om*/
    try {
        synchronized (_out) {
            writeC(0x01); // length 1 byte!
            writeC(0x02); // Cmd = ping (dummy packet for connection test);
            _out.flush();
        }
    } catch (SocketException e) {
        _log.warn("GeoEditor disconnected. ", e);
        _working = false;
    } catch (Exception e) {
        _log.error(e.getMessage(), e);
        try {
            _geSocket.close();
        } catch (Exception ex) {
        }
        _working = false;
    }
}