Search in sources :

Example 56 with UnknownHostException

use of java.net.UnknownHostException in project openhab1-addons by openhab.

the class LightwaveRfBinding method activate.

/**
     * Called by the SCR to activate the component with its configuration read
     * from CAS
     *
     * @param bundleContext
     *            BundleContext of the Bundle that defines this component
     * @param configuration
     *            Configuration properties for this component obtained from the
     *            ConfigAdmin service
     */
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    String ipString = (String) configuration.get("ip");
    if (StringUtils.isNotBlank(ipString)) {
        LIGHTWAVE_IP = ipString;
    }
    String recieverPortsString = (String) configuration.get("receiveport");
    if (StringUtils.isNotBlank(recieverPortsString)) {
        LIGHTWAVE_PORTS_TO_RECEIVE_ON = Integer.parseInt(recieverPortsString);
    }
    String portTwoString = (String) configuration.get("sendport");
    if (StringUtils.isNotBlank(portTwoString)) {
        LIGHTWAVE_PORT_TO_SEND_TO = Integer.parseInt(portTwoString);
    }
    String sendRegistrationMessageString = (String) configuration.get("registeronstartup");
    if (StringUtils.isNotBlank(sendRegistrationMessageString)) {
        SEND_REGISTER_ON_STARTUP = Boolean.parseBoolean(sendRegistrationMessageString);
    }
    String sendDelayString = (String) configuration.get("senddelay");
    if (StringUtils.isNotBlank(sendDelayString)) {
        TIME_BETWEEN_SENT_MESSAGES_MS = Integer.parseInt(sendDelayString);
    }
    String okTimeoutString = (String) configuration.get("okTimeout");
    if (StringUtils.isNotBlank(okTimeoutString)) {
        TIMEOUT_FOR_OK_MESSAGES_MS = Integer.parseInt(okTimeoutString);
    }
    logger.info("LightwaveBinding: IP[{}]", LIGHTWAVE_IP);
    logger.info("LightwaveBinding: ReceivePort[{}]", LIGHTWAVE_PORTS_TO_RECEIVE_ON);
    logger.info("LightwaveBinding: Send Port[{}]", LIGHTWAVE_PORT_TO_SEND_TO);
    logger.info("LightwaveBinding: Register On Startup[{}]", SEND_REGISTER_ON_STARTUP);
    logger.info("LightwaveBinding: Send Delay [{}]", TIME_BETWEEN_SENT_MESSAGES_MS);
    logger.info("LightwaveBinding: Timeout for Ok Messages [{}]", TIMEOUT_FOR_OK_MESSAGES_MS);
    messageConvertor = new LightwaverfConvertor();
    try {
        wifiLink = new LightwaveRfWifiLink(LIGHTWAVE_IP, LIGHTWAVE_PORT_TO_SEND_TO, LIGHTWAVE_PORTS_TO_RECEIVE_ON, messageConvertor, TIME_BETWEEN_SENT_MESSAGES_MS, TIMEOUT_FOR_OK_MESSAGES_MS);
        wifiLink.addListener(this);
        wifiLink.start();
        if (SEND_REGISTER_ON_STARTUP) {
            wifiLink.sendLightwaveCommand(messageConvertor.getRegistrationCommand());
        }
        // Now the sender is started and we have sent the registration
        // message
        // start the Heat Poller
        heatPoller = new LightwaveRfHeatPoller(wifiLink, messageConvertor);
        // bindingChanged method
        for (LightwaveRfBindingProvider provider : providers) {
            Collection<String> itemNames = provider.getItemNames();
            registerHeatingPollers(provider, itemNames);
        }
    } catch (UnknownHostException e) {
        logger.error("Error creating LightwaveRFSender", e);
    } catch (SocketException e) {
        logger.error("Error creating LightwaveRFSender/Receiver", e);
    }
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) LightwaveRfBindingProvider(org.openhab.binding.lightwaverf.LightwaveRfBindingProvider)

Example 57 with UnknownHostException

use of java.net.UnknownHostException in project XobotOS by xamarin.

the class DataCallState method setLinkProperties.

public SetupResult setLinkProperties(LinkProperties linkProperties, boolean okToUseSystemPropertyDns) {
    SetupResult result;
    // a failure we'll clear again at the bottom of this code.
    if (linkProperties == null)
        linkProperties = new LinkProperties();
    else
        linkProperties.clear();
    if (status == FailCause.NONE.getErrorCode()) {
        String propertyPrefix = "net." + ifname + ".";
        try {
            // set interface name
            linkProperties.setInterfaceName(ifname);
            // set link addresses
            if (addresses != null && addresses.length > 0) {
                for (String addr : addresses) {
                    LinkAddress la;
                    int addrPrefixLen;
                    String[] ap = addr.split("/");
                    if (ap.length == 2) {
                        addr = ap[0];
                        addrPrefixLen = Integer.parseInt(ap[1]);
                    } else {
                        addrPrefixLen = 0;
                    }
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(addr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric ip addr=" + addr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        if (addrPrefixLen == 0) {
                            // Assume point to point
                            addrPrefixLen = (ia instanceof Inet4Address) ? 32 : 128;
                        }
                        if (DBG)
                            Log.d(LOG_TAG, "addr/pl=" + addr + "/" + addrPrefixLen);
                        la = new LinkAddress(ia, addrPrefixLen);
                        linkProperties.addLinkAddress(la);
                    }
                }
            } else {
                throw new UnknownHostException("no address for ifname=" + ifname);
            }
            // set dns servers
            if (dnses != null && dnses.length > 0) {
                for (String addr : dnses) {
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(addr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric dns addr=" + addr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        linkProperties.addDns(ia);
                    }
                }
            } else if (okToUseSystemPropertyDns) {
                String[] dnsServers = new String[2];
                dnsServers[0] = SystemProperties.get(propertyPrefix + "dns1");
                dnsServers[1] = SystemProperties.get(propertyPrefix + "dns2");
                for (String dnsAddr : dnsServers) {
                    InetAddress ia;
                    try {
                        ia = NetworkUtils.numericToInetAddress(dnsAddr);
                    } catch (IllegalArgumentException e) {
                        throw new UnknownHostException("Non-numeric dns addr=" + dnsAddr);
                    }
                    if (!ia.isAnyLocalAddress()) {
                        linkProperties.addDns(ia);
                    }
                }
            } else {
                throw new UnknownHostException("Empty dns response and no system default dns");
            }
            // set gateways
            if ((gateways == null) || (gateways.length == 0)) {
                String sysGateways = SystemProperties.get(propertyPrefix + "gw");
                if (sysGateways != null) {
                    gateways = sysGateways.split(" ");
                } else {
                    gateways = new String[0];
                }
            }
            for (String addr : gateways) {
                InetAddress ia;
                try {
                    ia = NetworkUtils.numericToInetAddress(addr);
                } catch (IllegalArgumentException e) {
                    throw new UnknownHostException("Non-numeric gateway addr=" + addr);
                }
                if (!ia.isAnyLocalAddress()) {
                    linkProperties.addRoute(new RouteInfo(ia));
                }
            }
            result = SetupResult.SUCCESS;
        } catch (UnknownHostException e) {
            Log.d(LOG_TAG, "setLinkProperties: UnknownHostException " + e);
            e.printStackTrace();
            result = SetupResult.ERR_UnacceptableParameter;
        }
    } else {
        if (version < 4) {
            result = SetupResult.ERR_GetLastErrorFromRil;
        } else {
            result = SetupResult.ERR_RilError;
        }
    }
    // An error occurred so clear properties
    if (result != SetupResult.SUCCESS) {
        if (DBG) {
            Log.d(LOG_TAG, "setLinkProperties: error clearing LinkProperties " + "status=" + status + " result=" + result);
        }
        linkProperties.clear();
    }
    return result;
}
Also used : LinkAddress(android.net.LinkAddress) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) RouteInfo(android.net.RouteInfo) LinkProperties(android.net.LinkProperties) InetAddress(java.net.InetAddress)

Example 58 with UnknownHostException

use of java.net.UnknownHostException in project XobotOS by xamarin.

the class SIPTransactionStack method createRawMessageChannel.

/**
     * Creates a new MessageChannel for a given Hop.
     *
     * @param sourceIpAddress - Ip address of the source of this message.
     *
     * @param sourcePort - source port of the message channel to be created.
     *
     * @param nextHop Hop to create a MessageChannel to.
     *
     * @return A MessageChannel to the specified Hop, or null if no MessageProcessors support
     *         contacting that Hop.
     *
     * @throws UnknownHostException If the host in the Hop doesn't exist.
     */
public MessageChannel createRawMessageChannel(String sourceIpAddress, int sourcePort, Hop nextHop) throws UnknownHostException {
    Host targetHost;
    HostPort targetHostPort;
    Iterator processorIterator;
    MessageProcessor nextProcessor;
    MessageChannel newChannel;
    // Create the host/port of the target hop
    targetHost = new Host();
    targetHost.setHostname(nextHop.getHost());
    targetHostPort = new HostPort();
    targetHostPort.setHost(targetHost);
    targetHostPort.setPort(nextHop.getPort());
    // Search each processor for the correct transport
    newChannel = null;
    processorIterator = messageProcessors.iterator();
    while (processorIterator.hasNext() && newChannel == null) {
        nextProcessor = (MessageProcessor) processorIterator.next();
        // transport is found,
        if (nextHop.getTransport().equalsIgnoreCase(nextProcessor.getTransport()) && sourceIpAddress.equals(nextProcessor.getIpAddress().getHostAddress()) && sourcePort == nextProcessor.getPort()) {
            try {
                // Create a channel to the target
                // host/port
                newChannel = nextProcessor.createMessageChannel(targetHostPort);
            } catch (UnknownHostException ex) {
                if (stackLogger.isLoggingEnabled())
                    stackLogger.logException(ex);
                throw ex;
            } catch (IOException e) {
                if (stackLogger.isLoggingEnabled())
                    stackLogger.logException(e);
            // Ignore channel creation error -
            // try next processor
            }
        }
    }
    // Return the newly-created channel
    return newChannel;
}
Also used : UnknownHostException(java.net.UnknownHostException) HostPort(gov.nist.core.HostPort) Iterator(java.util.Iterator) Host(gov.nist.core.Host) IOException(java.io.IOException)

Example 59 with UnknownHostException

use of java.net.UnknownHostException in project XobotOS by xamarin.

the class PlainDatagramSocketImpl method connect.

@Override
public void connect(InetAddress inetAddr, int port) throws SocketException {
    // Throws on failure.
    IoBridge.connect(fd, inetAddr, port);
    try {
        connectedAddress = InetAddress.getByAddress(inetAddr.getAddress());
    } catch (UnknownHostException e) {
        // here if the address is not resolvable
        throw new SocketException("Host is unresolved: " + inetAddr.getHostName());
    }
    connectedPort = port;
    isNativeConnected = true;
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException)

Example 60 with UnknownHostException

use of java.net.UnknownHostException in project NoHttp by yanzhenjie.

the class Downloader method download.

public void download(int what, DownloadRequest downloadRequest, DownloadListener downloadListener) {
    validateParam(downloadRequest, downloadListener);
    Connection connection = null;
    RandomAccessFile randomAccessFile = null;
    String savePathDir = downloadRequest.getFileDir();
    String fileName = downloadRequest.getFileName();
    try {
        if (TextUtils.isEmpty(savePathDir))
            savePathDir = NoHttp.getContext().getFilesDir().getAbsolutePath();
        validateDevice(savePathDir);
        if (// auto named.
        TextUtils.isEmpty(fileName))
            fileName = Long.toString(System.currentTimeMillis());
        File tempFile = new File(savePathDir, fileName + ".nohttp");
        // 断点开始处。
        long rangeSize = handleRange(tempFile, downloadRequest);
        // 连接服务器。
        connection = mHttpConnection.getConnection(downloadRequest);
        Exception exception = connection.exception();
        if (exception != null)
            throw exception;
        Logger.i("----------Response Start----------");
        Headers responseHeaders = connection.responseHeaders();
        int responseCode = responseHeaders.getResponseCode();
        // getList filename from server.
        if (downloadRequest.autoNameByHead()) {
            String contentDisposition = responseHeaders.getContentDisposition();
            if (!TextUtils.isEmpty(contentDisposition)) {
                fileName = HeaderUtil.parseHeadValue(contentDisposition, "filename", null);
                if (!TextUtils.isEmpty(fileName)) {
                    try {
                        fileName = URLDecoder.decode(fileName, downloadRequest.getParamsEncoding());
                    } catch (UnsupportedEncodingException e) {
                    // Do nothing.
                    }
                    if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                        fileName = fileName.substring(1, fileName.length() - 1);
                    }
                }
            }
            // From url.
            if (TextUtils.isEmpty(fileName)) {
                String tempUrl = downloadRequest.url();
                String[] slash = tempUrl.split("/");
                fileName = slash[slash.length - 1];
                int paramIndex = fileName.indexOf("?");
                if (paramIndex > 0) {
                    fileName = fileName.substring(0, paramIndex);
                }
            }
        }
        InputStream serverStream = connection.serverStream();
        if (responseCode >= 400) {
            ServerError error = new ServerError("Download failed, the server response code is " + responseCode + ": " + downloadRequest.url());
            error.setErrorBody(IOUtils.toString(serverStream));
            throw error;
        } else {
            long contentLength;
            // 文件总大小
            if (responseCode == 206) {
                // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]。
                // Sample:Accept-Range:bytes 1024-2047/2048。
                String range = responseHeaders.getContentRange();
                try {
                    // 截取'/'之后的总大小。
                    contentLength = Long.parseLong(range.substring(range.indexOf('/') + 1));
                } catch (Throwable e) {
                    throw new ServerError("ResponseCode is 206, but content-Range error in Server HTTP header " + "information: " + range + ".");
                }
            } else if (responseCode == 304) {
                int httpContentLength = responseHeaders.getContentLength();
                downloadListener.onStart(what, true, httpContentLength, responseHeaders, httpContentLength);
                downloadListener.onProgress(what, 100, httpContentLength, 0);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, savePathDir + File.separator + fileName);
                return;
            } else {
                // such as: 200.
                // 服务器不支持Range。
                rangeSize = 0L;
                // 直接下载。
                contentLength = responseHeaders.getContentLength();
            }
            // 验证文件已经存在。
            File lastFile = new File(savePathDir, fileName);
            if (lastFile.exists()) {
                if (downloadRequest.isDeleteOld())
                    IOUtils.delFileOrFolder(lastFile);
                else {
                    downloadListener.onStart(what, true, lastFile.length(), responseHeaders, lastFile.length());
                    downloadListener.onProgress(what, 100, lastFile.length(), 0);
                    Logger.d("-------Download finish-------");
                    downloadListener.onFinish(what, lastFile.getAbsolutePath());
                    return;
                }
            }
            if (IOUtils.getDirSize(savePathDir) < contentLength)
                throw new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded file:" + " " + savePathDir + ".");
            // 需要重新下载,生成临时文件。
            if (responseCode != 206 && !IOUtils.createNewFile(tempFile))
                throw new StorageReadWriteError("SD isn't available, please check SD card and permission: " + "WRITE_EXTERNAL_STORAGE, and you must pay attention to Android6.0 RunTime " + "Permissions: https://github.com/yanzhenjie/AndPermission.");
            if (downloadRequest.isCanceled()) {
                Log.w("NoHttpDownloader", "Download request is canceled.");
                downloadListener.onCancel(what);
                return;
            }
            // 通知开始下载了。
            Logger.d("-------Download start-------");
            downloadListener.onStart(what, rangeSize > 0, rangeSize, responseHeaders, contentLength);
            randomAccessFile = new RandomAccessFile(tempFile, "rws");
            randomAccessFile.seek(rangeSize);
            byte[] buffer = new byte[8096];
            int len;
            // 旧的进度记录,防止重复通知。
            int oldProgress = 0;
            // 追加目前已经下载的进度。
            long count = rangeSize;
            long startTime = System.currentTimeMillis();
            long speedCount = 0;
            long oldSpeed = 0;
            while (((len = serverStream.read(buffer)) != -1)) {
                if (downloadRequest.isCanceled()) {
                    Log.i("NoHttpDownloader", "Download request is canceled.");
                    downloadListener.onCancel(what);
                    break;
                } else {
                    randomAccessFile.write(buffer, 0, len);
                    count += len;
                    speedCount += len;
                    long time = System.currentTimeMillis() - startTime;
                    long speed = speedCount * 1000 / time;
                    boolean speedChanged = oldSpeed != speed && time >= 300;
                    Logger.i("speedCount: " + speedCount + "; time: " + time + "; speed: " + speed + "; changed: " + "" + speedChanged);
                    if (contentLength != 0) {
                        int progress = (int) (count * 100 / contentLength);
                        if (progress != oldProgress && speedChanged) {
                            downloadListener.onProgress(what, progress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (speedChanged) {
                            downloadListener.onProgress(what, oldProgress, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else if (progress != oldProgress) {
                            downloadListener.onProgress(what, progress, count, oldSpeed);
                        }
                        oldProgress = progress;
                    } else if (speedChanged) {
                        downloadListener.onProgress(what, 0, count, speed);
                        speedCount = 0;
                        oldSpeed = speed;
                        startTime = System.currentTimeMillis();
                    } else {
                        downloadListener.onProgress(what, 0, count, oldSpeed);
                    }
                }
            }
            if (!downloadRequest.isCanceled()) {
                //noinspection ResultOfMethodCallIgnored
                tempFile.renameTo(lastFile);
                Logger.d("-------Download finish-------");
                downloadListener.onFinish(what, lastFile.getAbsolutePath());
            }
        }
    } catch (MalformedURLException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new URLError(e.getMessage()));
    } catch (UnknownHostException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new UnKnownHostError(e.getMessage()));
    } catch (SocketTimeoutException e) {
        Logger.e(e);
        downloadListener.onDownloadError(what, new TimeoutError(e.getMessage()));
    } catch (IOException e) {
        Exception newException = e;
        if (!IOUtils.canWrite(savePathDir))
            newException = new StorageReadWriteError("This folder cannot be written to the file: " + savePathDir + ".");
        else if (IOUtils.getDirSize(savePathDir) < 1024)
            newException = new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded " + "file: " + savePathDir + ".");
        Logger.e(newException);
        downloadListener.onDownloadError(what, newException);
    } catch (Exception e) {
        // NetworkError | ServerError | StorageCantWriteError | StorageSpaceNotEnoughError
        if (!NetUtil.isNetworkAvailable())
            e = new NetworkError("The network is not available.");
        Logger.e(e);
        downloadListener.onDownloadError(what, e);
    } finally {
        Logger.i("----------Response End----------");
        IOUtils.closeQuietly(randomAccessFile);
        IOUtils.closeQuietly(connection);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Headers(com.yanzhenjie.nohttp.Headers) URLError(com.yanzhenjie.nohttp.error.URLError) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) ServerError(com.yanzhenjie.nohttp.error.ServerError) StorageReadWriteError(com.yanzhenjie.nohttp.error.StorageReadWriteError) Connection(com.yanzhenjie.nohttp.Connection) HttpConnection(com.yanzhenjie.nohttp.HttpConnection) UnsupportedEncodingException(java.io.UnsupportedEncodingException) StorageSpaceNotEnoughError(com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError) NetworkError(com.yanzhenjie.nohttp.error.NetworkError) TimeoutError(com.yanzhenjie.nohttp.error.TimeoutError) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SocketTimeoutException(java.net.SocketTimeoutException) RandomAccessFile(java.io.RandomAccessFile) UnKnownHostError(com.yanzhenjie.nohttp.error.UnKnownHostError) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Aggregations

UnknownHostException (java.net.UnknownHostException)1736 InetAddress (java.net.InetAddress)726 IOException (java.io.IOException)446 InetSocketAddress (java.net.InetSocketAddress)150 ArrayList (java.util.ArrayList)142 SocketException (java.net.SocketException)135 Test (org.junit.Test)122 Socket (java.net.Socket)93 URL (java.net.URL)77 SocketTimeoutException (java.net.SocketTimeoutException)71 HashMap (java.util.HashMap)71 File (java.io.File)67 MalformedURLException (java.net.MalformedURLException)65 NetworkInterface (java.net.NetworkInterface)58 URI (java.net.URI)55 ConnectException (java.net.ConnectException)54 InputStream (java.io.InputStream)53 Inet4Address (java.net.Inet4Address)52 Inet6Address (java.net.Inet6Address)52 List (java.util.List)51