Search in sources :

Example 51 with UnknownHostException

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

the class TcpIOStream method open.

@Override
public boolean open() {
    if (m_host == null || m_port < 0) {
        logger.error("tcp connection to hub not properly configured!");
        return (false);
    }
    try {
        m_socket = new Socket(m_host, m_port);
        m_in = m_socket.getInputStream();
        m_out = m_socket.getOutputStream();
    } catch (UnknownHostException e) {
        logger.error("unknown host name: {}", m_host, e);
        return (false);
    } catch (IOException e) {
        logger.error("cannot open connection to {} port {}: ", m_host, m_port, e);
        return (false);
    }
    return true;
}
Also used : UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) Socket(java.net.Socket)

Example 52 with UnknownHostException

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

the class NtpBinding method getTime.

/**
     * Queries the given timeserver <code>hostname</code> and returns the time
     * in milliseconds.
     *
     * @param hostname the timeserver to query
     * @return the time in milliseconds or the current time of the system if an
     *         error occurs.
     */
protected static long getTime(String hostname) {
    try {
        NTPUDPClient timeClient = new NTPUDPClient();
        timeClient.setDefaultTimeout(NTP_TIMEOUT);
        InetAddress inetAddress = InetAddress.getByName(hostname);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        return timeInfo.getReturnTime();
    } catch (UnknownHostException uhe) {
        logger.warn("the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead", hostname);
    } catch (IOException ioe) {
        logger.warn("couldn't establish network connection [host '{}'] -> returning current sytem time instead", hostname);
    }
    return System.currentTimeMillis();
}
Also used : NTPUDPClient(org.apache.commons.net.ntp.NTPUDPClient) UnknownHostException(java.net.UnknownHostException) TimeInfo(org.apache.commons.net.ntp.TimeInfo) IOException(java.io.IOException) InetAddress(java.net.InetAddress)

Example 53 with UnknownHostException

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

the class KNXConnection method connectByIp.

private static KNXNetworkLink connectByIp(int ipConnectionType, String localIp, String ip, int port) throws KNXException, UnknownHostException, InterruptedException {
    InetSocketAddress localEndPoint = null;
    if (StringUtils.isNotBlank(localIp)) {
        localEndPoint = new InetSocketAddress(localIp, 0);
    } else {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            localEndPoint = new InetSocketAddress(localHost, 0);
        } catch (UnknownHostException uhe) {
            sLogger.warn("Couldn't find an IP address for this host. Please check the .hosts configuration or use the 'localIp' parameter to configure a valid IP address.");
        }
    }
    return new KNXNetworkLinkIP(ipConnectionType, localEndPoint, new InetSocketAddress(ip, port), sUseNAT, new TPSettings(new IndividualAddress(sLocalSourceAddr), true));
}
Also used : UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) TPSettings(tuwien.auto.calimero.link.medium.TPSettings) KNXNetworkLinkIP(tuwien.auto.calimero.link.KNXNetworkLinkIP) IndividualAddress(tuwien.auto.calimero.IndividualAddress) InetAddress(java.net.InetAddress)

Example 54 with UnknownHostException

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

the class IRtransGenericBindingProvider method getInetSocketAddresses.

/**
     * {@inheritDoc}
     */
@Override
public List<InetSocketAddress> getInetSocketAddresses(String itemName) {
    List<InetSocketAddress> theList = new ArrayList<InetSocketAddress>();
    for (Command command : getAllCommands(itemName)) {
        InetSocketAddress anAddress = null;
        try {
            anAddress = new InetSocketAddress(InetAddress.getByName(getHost(itemName, command)), getPort(itemName, command));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        theList.add(anAddress);
    }
    return theList;
}
Also used : UnknownHostException(java.net.UnknownHostException) Command(org.openhab.core.types.Command) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList)

Example 55 with UnknownHostException

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

the class MaxCubeBinding method execute.

/**
     * {@inheritDoc}
     */
@Override
public synchronized void execute() {
    if (ip == null) {
        logger.debug("Update prior to completion of interface IP configuration");
        return;
    }
    try {
        String raw = null;
        if (maxRequestsPerConnection > 0 && requestCount >= maxRequestsPerConnection) {
            logger.debug("maxRequestsPerConnection reached, reconnecting.");
            socket.close();
            this.socketConnect();
        }
        if (socket == null) {
            this.socketConnect();
        } else {
            /*
                 * if the connection is already open (this happens in exclusive mode), just send a "l:\r\n" to get the
                 * latest live informations
                 * note that "L:\r\n" or "l:\n" would not work.
                 */
            logger.debug("Sending state request #" + this.requestCount + " to Maxcube");
            writer.write("l:" + '\r' + '\n');
            writer.flush();
            requestCount++;
        }
        boolean cont = true;
        while (cont) {
            raw = reader.readLine();
            if (raw == null) {
                cont = false;
                continue;
            }
            Message message = null;
            try {
                this.messageProcessor.addReceivedLine(raw);
                if (this.messageProcessor.isMessageAvailable()) {
                    message = this.messageProcessor.pull();
                } else {
                    continue;
                }
                message.debug(logger);
                if (message != null) {
                    message.debug(logger);
                    if (message.getType() == MessageType.M) {
                        M_Message msg = (M_Message) message;
                        for (DeviceInformation di : msg.devices) {
                            Configuration c = null;
                            for (Configuration conf : configurations) {
                                if (conf.getSerialNumber().equalsIgnoreCase(di.getSerialNumber())) {
                                    c = conf;
                                    break;
                                }
                            }
                            if (c != null) {
                                configurations.remove(c);
                            }
                            c = Configuration.create(di);
                            configurations.add(c);
                            c.setRoomId(di.getRoomId());
                        }
                    } else if (message.getType() == MessageType.C) {
                        Configuration c = null;
                        for (Configuration conf : configurations) {
                            if (conf.getSerialNumber().equalsIgnoreCase(((C_Message) message).getSerialNumber())) {
                                c = conf;
                                break;
                            }
                        }
                        if (c == null) {
                            configurations.add(Configuration.create(message));
                        } else {
                            c.setValues((C_Message) message);
                        }
                    } else if (message.getType() == MessageType.S) {
                        sMessageProcessing((S_Message) message);
                        cont = false;
                    } else if (message.getType() == MessageType.L) {
                        ((L_Message) message).updateDevices(devices, configurations);
                        logger.debug("{} devices found.", devices.size());
                        // the L message is the last one, while the reader
                        // would hang trying to read a new line and
                        // eventually the
                        // cube will fail to establish
                        // new connections for some time
                        cont = false;
                    }
                }
            } catch (IncorrectMultilineIndexException ex) {
                logger.info("Incorrect MAX!Cube multiline message detected. Stopping processing and continue with next Line.");
                this.messageProcessor.reset();
            } catch (NoMessageAvailableException ex) {
                logger.info("Could not process MAX!Cube message. Stopping processing and continue with next Line.");
                this.messageProcessor.reset();
            } catch (IncompleteMessageException ex) {
                logger.info("Error while parsing MAX!Cube multiline message. Stopping processing, and continue with next Line.");
                this.messageProcessor.reset();
            } catch (UnprocessableMessageException ex) {
                logger.info("Error while parsing MAX!Cube message. Stopping processing, and continue with next Line.");
                this.messageProcessor.reset();
            } catch (UnsupportedMessageTypeException ex) {
                logger.info("Unsupported MAX!Cube message detected. Ignoring and continue with next Line.");
                this.messageProcessor.reset();
            } catch (MessageIsWaitingException ex) {
                logger.info("There was an unhandled message waiting. Ignoring and continue with next Line.");
                this.messageProcessor.reset();
            } catch (Exception e) {
                logger.info("Failed to process message received by MAX! protocol.");
                logger.debug(Utils.getStackTrace(e));
                this.messageProcessor.reset();
            }
        }
        if (!exclusive) {
            socketClose();
        }
        for (MaxCubeBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                String serialNumber = provider.getSerialNumber(itemName);
                Device device = findDevice(serialNumber, devices);
                if (device == null) {
                    logger.info("Cannot find MAX!cube device with serial number '{}'", serialNumber);
                    logAvailableMaxDevices();
                    continue;
                }
                // all devices have a battery state, so this is type-independent
                if (provider.getBindingType(itemName) == BindingType.BATTERY) {
                    if (device.battery().isChargeUpdated()) {
                        eventPublisher.postUpdate(itemName, device.battery().getCharge());
                    }
                } else if (provider.getBindingType(itemName) == BindingType.CONNECTION_ERROR) {
                    if (device.isErrorUpdated()) {
                        OnOffType connectionError = device.isError() ? OnOffType.ON : OnOffType.OFF;
                        eventPublisher.postUpdate(itemName, connectionError);
                    }
                } else {
                    switch(device.getType()) {
                        case HeatingThermostatPlus:
                        case HeatingThermostat:
                            if (provider.getBindingType(itemName) == BindingType.VALVE && ((HeatingThermostat) device).isValvePositionUpdated()) {
                                eventPublisher.postUpdate(itemName, ((HeatingThermostat) device).getValvePosition());
                                break;
                            }
                        // omitted break, fall through
                        case // and also HeatingThermostat
                        WallMountedThermostat:
                            if (provider.getBindingType(itemName) == BindingType.MODE && ((HeatingThermostat) device).isModeUpdated()) {
                                eventPublisher.postUpdate(itemName, ((HeatingThermostat) device).getModeString());
                            } else if (provider.getBindingType(itemName) == BindingType.ACTUAL && ((HeatingThermostat) device).isTemperatureActualUpdated()) {
                                eventPublisher.postUpdate(itemName, ((HeatingThermostat) device).getTemperatureActual());
                            } else if (((HeatingThermostat) device).isTemperatureSetpointUpdated() && provider.getBindingType(itemName) == null) {
                                eventPublisher.postUpdate(itemName, ((HeatingThermostat) device).getTemperatureSetpoint());
                            }
                            break;
                        case ShutterContact:
                            if (((ShutterContact) device).isShutterStateUpdated()) {
                                eventPublisher.postUpdate(itemName, ((ShutterContact) device).getShutterState());
                            }
                            break;
                        default:
                    }
                }
            }
        }
    } catch (UnknownHostException e) {
        logger.info("Host error occurred while connecting to MAX! Cube lan gateway '{}': {}", ip, e.getMessage());
        socketClose();
    } catch (IOException e) {
        logger.info("IO error occurred while connecting to MAX! Cube lan gateway '{}': {}", ip, e.getMessage());
        // reconnect on next execution
        socketClose();
    } catch (Exception e) {
        logger.info("Error occurred while connecting to MAX! Cube lan gateway '{}': {}", ip, e.getMessage());
        logger.info(Utils.getStackTrace(e));
        // reconnect on next execution
        socketClose();
    }
}
Also used : MaxCubeBindingProvider(org.openhab.binding.maxcube.MaxCubeBindingProvider) ShutterContact(org.openhab.binding.maxcube.internal.message.ShutterContact) S_Message(org.openhab.binding.maxcube.internal.message.S_Message) M_Message(org.openhab.binding.maxcube.internal.message.M_Message) C_Message(org.openhab.binding.maxcube.internal.message.C_Message) L_Message(org.openhab.binding.maxcube.internal.message.L_Message) Message(org.openhab.binding.maxcube.internal.message.Message) Configuration(org.openhab.binding.maxcube.internal.message.Configuration) UnknownHostException(java.net.UnknownHostException) Device(org.openhab.binding.maxcube.internal.message.Device) HeatingThermostat(org.openhab.binding.maxcube.internal.message.HeatingThermostat) IncompleteMessageException(org.openhab.binding.maxcube.internal.exceptions.IncompleteMessageException) IOException(java.io.IOException) NoMessageAvailableException(org.openhab.binding.maxcube.internal.exceptions.NoMessageAvailableException) UnprocessableMessageException(org.openhab.binding.maxcube.internal.exceptions.UnprocessableMessageException) IncompleteMessageException(org.openhab.binding.maxcube.internal.exceptions.IncompleteMessageException) UnprocessableMessageException(org.openhab.binding.maxcube.internal.exceptions.UnprocessableMessageException) UnsupportedMessageTypeException(org.openhab.binding.maxcube.internal.exceptions.UnsupportedMessageTypeException) ConfigurationException(org.osgi.service.cm.ConfigurationException) MessageIsWaitingException(org.openhab.binding.maxcube.internal.exceptions.MessageIsWaitingException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NoMessageAvailableException(org.openhab.binding.maxcube.internal.exceptions.NoMessageAvailableException) IncorrectMultilineIndexException(org.openhab.binding.maxcube.internal.exceptions.IncorrectMultilineIndexException) OnOffType(org.openhab.core.library.types.OnOffType) C_Message(org.openhab.binding.maxcube.internal.message.C_Message) IncorrectMultilineIndexException(org.openhab.binding.maxcube.internal.exceptions.IncorrectMultilineIndexException) M_Message(org.openhab.binding.maxcube.internal.message.M_Message) MessageIsWaitingException(org.openhab.binding.maxcube.internal.exceptions.MessageIsWaitingException) DeviceInformation(org.openhab.binding.maxcube.internal.message.DeviceInformation) UnsupportedMessageTypeException(org.openhab.binding.maxcube.internal.exceptions.UnsupportedMessageTypeException)

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