Search in sources :

Example 66 with SocketException

use of java.net.SocketException in project Smack by igniterealtime.

the class STUNResolverTest method testICEPriority.

/**
     * Test priority generated by STUN lib
     *
     * @throws Exception
     */
public void testICEPriority() throws Exception {
    String first = "";
    for (int i = 0; i < 100; i++) {
        ICENegociator cc = new ICENegociator((short) 1);
        // gather candidates
        cc.gatherCandidateAddresses();
        // priorize candidates
        cc.prioritizeCandidates();
        for (Candidate candidate : cc.getSortedCandidates()) {
            short nicNum = 0;
            try {
                Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
                short tempNic = 0;
                NetworkInterface nic = NetworkInterface.getByInetAddress(candidate.getAddress().getInetAddress());
                while (nics.hasMoreElements()) {
                    NetworkInterface checkNIC = nics.nextElement();
                    if (checkNIC.equals(nic)) {
                        nicNum = tempNic;
                        break;
                    }
                    i++;
                }
            } catch (SocketException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                TransportCandidate transportCandidate = new ICECandidate(candidate.getAddress().getInetAddress().getHostAddress(), 1, nicNum, "1", candidate.getPort(), "1", candidate.getPriority(), ICECandidate.Type.prflx);
                transportCandidate.setLocalIp(candidate.getBase().getAddress().getInetAddress().getHostAddress());
                System.out.println("C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority());
            } catch (UtilityException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            } catch (UnknownHostException e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
        Candidate candidate = cc.getSortedCandidates().get(0);
        String temp = "C: " + candidate.getAddress().getInetAddress() + "|" + candidate.getBase().getAddress().getInetAddress() + " p:" + candidate.getPriority();
        if (first.equals(""))
            first = temp;
        assertEquals(first, temp);
        first = temp;
    }
}
Also used : Candidate(de.javawi.jstun.test.demo.ice.Candidate) SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) ICENegociator(de.javawi.jstun.test.demo.ice.ICENegociator) NetworkInterface(java.net.NetworkInterface) UtilityException(de.javawi.jstun.util.UtilityException)

Example 67 with SocketException

use of java.net.SocketException in project openkit-android by OpenKit.

the class AsyncHttpRequest method makeRequestWithRetries.

private void makeRequestWithRetries() throws ConnectException {
    // This is an additional layer of retry logic lifted from droid-fu
    // See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        try {
            makeRequest();
            return;
        } catch (UnknownHostException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketException e) {
            // Added to detect host unreachable
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "can't resolve host");
            }
            return;
        } catch (SocketTimeoutException e) {
            if (responseHandler != null) {
                responseHandler.sendFailureMessage(e, "socket time out");
            }
            return;
        } catch (IOException e) {
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        } catch (NullPointerException e) {
            // there's a bug in HttpClient 4.0.x that on some occasions causes
            // DefaultRequestExecutor to throw an NPE, see
            // http://code.google.com/p/android/issues/detail?id=5255
            cause = new IOException("NPE in HttpClient" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
        }
    }
    // no retries left, crap out with exception
    ConnectException ex = new ConnectException();
    ex.initCause(cause);
    throw ex;
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) HttpRequestRetryHandler(org.apache.http.client.HttpRequestRetryHandler) ConnectException(java.net.ConnectException)

Example 68 with SocketException

use of java.net.SocketException in project FastDev4Android by jiangqqlmj.

the class IoUtils method getInputStreamFromUrl.

public static InputStream getInputStreamFromUrl(String url, RequestCallBack requestCallBack) {
    if (url == null || !url.contains("http://")) {
        Log.e("listlogic", "列表下载地址异常");
        return null;
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestStart();
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestLoading();
    }
    URI encodedUri = null;
    HttpGet httpGet = null;
    try {
        encodedUri = new URI(url);
        httpGet = new HttpGet(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpGet = new HttpGet(encodedUrl);
        e.printStackTrace();
    }
    // 创建httpclient对象
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    try {
        try {
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (httpResponse != null) {
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                // 请求数据
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    inputStream = httpEntity.getContent();
                    byte[] bytes = getByteArrayFromInputstream(inputStream);
                    if (bytes != null) {
                        InputStream inputStream2 = new ByteArrayInputStream(bytes);
                        if (requestCallBack != null) {
                            requestCallBack.onRequestSuccess(inputStream2);
                        }
                        return inputStream2;
                    }
                }
            } else {
                httpGet.abort();
                if (requestCallBack != null) {
                    requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
                }
            }
        } else {
            httpGet.abort();
            if (requestCallBack != null) {
                requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } catch (IOException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCallBack != null) {
            requestCallBack.onCancel();
        }
    }
    return null;
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient)

Example 69 with SocketException

use of java.net.SocketException in project jmxtrans by jmxtrans.

the class TCollectorUDPWriterTests method testSocketException.

/**
	 * Test a socket exception when creating the DatagramSocket.
	 */
@Test
public void testSocketException() throws Exception {
    // Prepare
    SocketException sockExc = new SocketException("X-SOCK-EXC-X");
    PowerMockito.whenNew(DatagramSocket.class).withNoArguments().thenThrow(sockExc);
    try {
        // Execute
        this.writer.start();
        Assert.fail("LifecycleException missing");
    } catch (LifecycleException lcExc) {
        // Verify
        Assert.assertSame(sockExc, lcExc.getCause());
        Mockito.verify(this.mockLog).error(contains("create a datagram socket"), eq(sockExc));
    }
}
Also used : SocketException(java.net.SocketException) LifecycleException(com.googlecode.jmxtrans.exceptions.LifecycleException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 70 with SocketException

use of java.net.SocketException in project Smack by igniterealtime.

the class BasicResolver method resolve.

/**
     * Resolve the IP address.
     * <p/>
     * The BasicResolver takes the IP addresses of the interfaces and uses the
     * first non-loopback, non-linklocal and non-sitelocal address.
     * @throws NotConnectedException 
     * @throws InterruptedException 
     */
@Override
public synchronized void resolve(JingleSession session) throws XMPPException, NotConnectedException, InterruptedException {
    setResolveInit();
    clearCandidates();
    Enumeration<NetworkInterface> ifaces = null;
    try {
        ifaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOGGER.log(Level.WARNING, "exception", e);
    }
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
        while (iaddresses.hasMoreElements()) {
            InetAddress iaddress = iaddresses.nextElement();
            if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress() && !iaddress.isSiteLocalAddress()) {
                TransportCandidate tr = new TransportCandidate.Fixed(iaddress.getHostAddress() != null ? iaddress.getHostAddress() : iaddress.getHostName(), getFreePort());
                tr.setLocalIp(iaddress.getHostAddress() != null ? iaddress.getHostAddress() : iaddress.getHostName());
                addCandidate(tr);
                setResolveEnd();
                return;
            }
        }
    }
    try {
        ifaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        LOGGER.log(Level.WARNING, "exception", e);
    }
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
        while (iaddresses.hasMoreElements()) {
            InetAddress iaddress = iaddresses.nextElement();
            if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress()) {
                TransportCandidate tr = new TransportCandidate.Fixed(iaddress.getHostAddress() != null ? iaddress.getHostAddress() : iaddress.getHostName(), getFreePort());
                tr.setLocalIp(iaddress.getHostAddress() != null ? iaddress.getHostAddress() : iaddress.getHostName());
                addCandidate(tr);
                setResolveEnd();
                return;
            }
        }
    }
    try {
        TransportCandidate tr = new TransportCandidate.Fixed(InetAddress.getLocalHost().getHostAddress() != null ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getHostName(), getFreePort());
        tr.setLocalIp(InetAddress.getLocalHost().getHostAddress() != null ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getHostName());
        addCandidate(tr);
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "exception", e);
    }
    setResolveEnd();
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress) SocketException(java.net.SocketException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) XMPPException(org.jivesoftware.smack.XMPPException)

Aggregations

SocketException (java.net.SocketException)523 IOException (java.io.IOException)189 InetAddress (java.net.InetAddress)127 NetworkInterface (java.net.NetworkInterface)110 Socket (java.net.Socket)100 UnknownHostException (java.net.UnknownHostException)93 ServerSocket (java.net.ServerSocket)82 DatagramSocket (java.net.DatagramSocket)78 SocketTimeoutException (java.net.SocketTimeoutException)77 InetSocketAddress (java.net.InetSocketAddress)62 Test (org.junit.Test)50 ConnectException (java.net.ConnectException)39 DatagramPacket (java.net.DatagramPacket)38 ArrayList (java.util.ArrayList)35 BindException (java.net.BindException)31 Inet4Address (java.net.Inet4Address)24 SocketAddress (java.net.SocketAddress)24 InterruptedIOException (java.io.InterruptedIOException)23 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)23 SmallTest (android.test.suitebuilder.annotation.SmallTest)20