Example usage for java.net NetworkInterface getInetAddresses

List of usage examples for java.net NetworkInterface getInetAddresses

Introduction

In this page you can find the example usage for java.net NetworkInterface getInetAddresses.

Prototype

public Enumeration<InetAddress> getInetAddresses() 

Source Link

Document

Get an Enumeration with all or a subset of the InetAddresses bound to this network interface.

Usage

From source file:org.apache.solr.cloud.ZkController.java

private String normalizeHostName(String host) throws IOException {

    if (host == null || host.length() == 0) {
        String hostaddress;//ww w  .j ava 2s .c  o m
        try {
            hostaddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            hostaddress = "127.0.0.1"; // cannot resolve system hostname, fall through
        }
        // Re-get the IP again for "127.0.0.1", the other case we trust the hosts
        // file is right.
        if ("127.0.0.1".equals(hostaddress)) {
            Enumeration<NetworkInterface> netInterfaces = null;
            try {
                netInterfaces = NetworkInterface.getNetworkInterfaces();
                while (netInterfaces.hasMoreElements()) {
                    NetworkInterface ni = netInterfaces.nextElement();
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        InetAddress ip = ips.nextElement();
                        if (ip.isSiteLocalAddress()) {
                            hostaddress = ip.getHostAddress();
                        }
                    }
                }
            } catch (Exception e) {
                SolrException.log(log, "Error while looking for a better host name than 127.0.0.1", e);
            }
        }
        host = hostaddress;
    } else {
        if (URLUtil.hasScheme(host)) {
            host = URLUtil.removeScheme(host);
        }
    }

    return host;
}

From source file:org.panbox.desktop.common.gui.PanboxClientGUI.java

private DefaultComboBoxModel<Object> generateNetworkInterfacesModel() {
    DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<>();
    try {/* w w w  .  j  a v a 2 s  .  c  o  m*/
        List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nic : nics) {
            List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
            if (addrs.size() > 0 && !nic.isLoopback() && nic.isUp()) {
                model.addElement(nic);
            }
        }
    } catch (SocketException e) {
        logger.warn(
                "An exception occurred while iterating over available network interfaces. Will return unfinished list: ",
                e);
    }
    return model;
}

From source file:org.panbox.desktop.common.gui.PanboxClientGUI.java

private DefaultComboBoxModel<Object> generateNetworkAddressModel(NetworkInterface nic) {
    DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<>();
    List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
    for (InetAddress addr : addrs) {
        if (addr instanceof Inet4Address) { // ignore IPv6 addresses!!!
            model.addElement(addr);/*from   w ww  .  ja v  a  2s  . c o  m*/
        }
    }
    return model;
}

From source file:com.max2idea.android.limbo.main.LimboActivity.java

public static String getLocalIpAddress() {
    try {/*  w  w  w .ja  v  a2s .c o  m*/
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().contains(".")) {
                    Log.v("Internal ip", inetAddress.getHostAddress().toString());
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e("Internal IP", ex.toString());
    }
    return null;
}

From source file:org.alfresco.filesys.config.ServerConfigurationBean.java

/**
 * Process the CIFS server configuration
 *//* w ww  .j a v  a2  s.  c  om*/
protected void processCIFSServerConfig() {
    // If the configuration section is not valid then CIFS is disabled

    if (cifsConfigBean == null) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Check if the server has been disabled
    if (!cifsConfigBean.getServerEnabled()) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Before we go any further, let's make sure there's a compatible authenticator in the authentication chain.
    ICifsAuthenticator authenticator = cifsConfigBean.getAuthenticator();
    if (authenticator == null
            || authenticator instanceof ActivateableBean && !((ActivateableBean) authenticator).isActive()) {
        logger.error("No enabled CIFS authenticator found in authentication chain. CIFS Server disabled");
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Create the CIFS server configuration section

    CIFSConfigSection cifsConfig = new CIFSConfigSection(this);

    try {
        // Check if native code calls should be disabled on Windows
        if (cifsConfigBean.getDisableNativeCode()) {
            // Disable native code calls so that the JNI DLL is not required

            cifsConfig.setNativeCodeDisabled(true);
            m_disableNativeCode = true;

            // Warning

            logger.warn("CIFS server native calls disabled, JNI code will not be used");
        }

        // Get the network broadcast address
        //
        // Note: We need to set this first as the call to getLocalDomainName() may use a NetBIOS
        // name lookup, so the broadcast mask must be set before then.

        String broadcastAddess = cifsConfigBean.getBroadcastAddress();
        if (broadcastAddess != null && broadcastAddess.length() > 0) {

            // Check if the broadcast mask is a valid numeric IP address

            if (IPAddress.isNumericAddress(broadcastAddess) == false) {
                throw new AlfrescoRuntimeException("CIFS Invalid broadcast mask, must be n.n.n.n format");
            }

            // Set the network broadcast mask

            cifsConfig.setBroadcastMask(broadcastAddess);
        }

        // Get the terminal server address

        List<String> terminalServerList = cifsConfigBean.getTerminalServerList();
        if (terminalServerList != null && terminalServerList.size() > 0) {
            // Check if the terminal server address is a valid numeric IP address
            for (String terminalServerAddress : terminalServerList) {
                if (IPAddress.isNumericAddress(terminalServerAddress) == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid terminal server address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setTerminalServerList(terminalServerList);
        }

        // Get the load balancer address

        List<String> loadBalancerList = cifsConfigBean.getLoadBalancerList();
        if (loadBalancerList != null && loadBalancerList.size() > 0) {
            // Check if the load balancer address is a valid numeric IP address
            for (String loadBalancerAddress : loadBalancerList) {
                if (IPAddress.isNumericAddress(loadBalancerAddress) == false)
                    throw new AlfrescoRuntimeException("Invalid load balancer address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setLoadBalancerList(loadBalancerList);
        }

        // Get the host configuration

        String hostName = cifsConfigBean.getServerName();
        if (hostName == null || hostName.length() == 0) {
            throw new AlfrescoRuntimeException("CIFS Host name not specified or invalid");
        }

        // Get the local server name

        String srvName = getLocalServerName(true);

        // Check if the host name contains the local name token

        int pos = hostName.indexOf(TokenLocalName);
        if (pos != -1) {
            // Rebuild the host name substituting the token with the local server name

            StringBuilder hostStr = new StringBuilder();

            hostStr.append(hostName.substring(0, pos));
            hostStr.append(srvName);

            pos += TokenLocalName.length();
            if (pos < hostName.length()) {
                hostStr.append(hostName.substring(pos));
            }

            hostName = hostStr.toString();
        }

        // Make sure the CIFS server name does not match the local server name

        if (hostName.toUpperCase().equals(srvName.toUpperCase())
                && getPlatformType() == Platform.Type.WINDOWS) {
            throw new AlfrescoRuntimeException("CIFS server name must be unique");
        }

        // Check if the host name is longer than 15 characters. NetBIOS only allows a maximum of 16 characters in
        // the
        // server name with the last character reserved for the service type.

        if (hostName.length() > 15) {
            // Truncate the CIFS server name

            hostName = hostName.substring(0, 15);

            // Output a warning

            logger.warn("CIFS server name is longer than 15 characters, truncated to " + hostName);
        }

        // Set the CIFS server name

        cifsConfig.setServerName(hostName.toUpperCase());
        setServerName(hostName.toUpperCase());

        // Get the domain/workgroup name

        String domain = cifsConfigBean.getDomainName();
        if (domain != null && domain.length() > 0) {
            // Set the domain/workgroup name

            cifsConfig.setDomainName(domain.toUpperCase());
        } else {
            // Get the local domain/workgroup name

            String localDomain = getLocalDomainName();

            if (localDomain == null && (getPlatformType() != Platform.Type.WINDOWS || isNativeCodeDisabled())) {
                // Use a default domain/workgroup name

                localDomain = "WORKGROUP";

                // Output a warning
                logger.warn("CIFS, Unable to get local domain/workgroup name, using default of " + localDomain
                        + ". This may be due to firewall settings or incorrect <broadcast> setting)");
            }

            // Set the local domain/workgroup that the CIFS server belongs to

            cifsConfig.setDomainName(localDomain);
        }

        // Check for a server comment

        String comment = cifsConfigBean.getServerComment();
        if (comment != null && comment.length() > 0) {
            cifsConfig.setComment(comment);
        }

        // Set the maximum virtual circuits per session

        if (cifsConfigBean.getMaximumVirtualCircuits() < VirtualCircuitList.MinCircuits
                || cifsConfigBean.getMaximumVirtualCircuits() > VirtualCircuitList.MaxCircuits)
            throw new AlfrescoRuntimeException("Invalid virtual circuits value, valid range is "
                    + VirtualCircuitList.MinCircuits + " - " + VirtualCircuitList.MaxCircuits);
        else
            cifsConfig.setMaximumVirtualCircuits(cifsConfigBean.getMaximumVirtualCircuits());

        // Check for a bind address

        // Check if the network adapter name has been specified
        String bindToAdapter = cifsConfigBean.getBindToAdapter();
        String bindTo;

        if (bindToAdapter != null && bindToAdapter.length() > 0) {

            // Get the IP address for the adapter

            InetAddress bindAddr = parseAdapterName(bindToAdapter);

            // Set the bind address for the server

            cifsConfig.setSMBBindAddress(bindAddr);
        } else if ((bindTo = cifsConfigBean.getBindToAddress()) != null && bindTo.length() > 0
                && !bindTo.equals(BIND_TO_IGNORE)) {

            // Validate the bind address
            try {
                // Check the bind address

                InetAddress bindAddr = InetAddress.getByName(bindTo);

                // Set the bind address for the server

                cifsConfig.setSMBBindAddress(bindAddr);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("CIFS Unable to bind to address :" + bindTo, ex);
            }
        }

        // Get the authenticator

        if (authenticator != null) {
            cifsConfig.setAuthenticator(authenticator);
        } else {
            throw new AlfrescoRuntimeException("CIFS authenticator not specified");
        }

        // Check if the host announcer has been disabled

        if (!cifsConfigBean.getHostAccouncerEnabled()) {
            // Switch off the host announcer

            cifsConfig.setHostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("CIFS Host announcements not enabled");
        } else {
            // Check for an announcement interval

            Integer interval = cifsConfigBean.getHostAccounceInterval();
            if (interval != null) {
                cifsConfig.setHostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null) {
                throw new AlfrescoRuntimeException(
                        "CIFS Domain name must be specified if host announcement is enabled");
            }

            // Enable host announcement

            cifsConfig.setHostAnnouncer(true);
        }

        // Check if NetBIOS SMB is enabled
        NetBIOSSMBConfigBean netBIOSSMBConfigBean = cifsConfigBean.getNetBIOSSMB();
        if (netBIOSSMBConfigBean != null) {
            // Check if NetBIOS over TCP/IP is enabled for the current platform

            String platformsStr = netBIOSSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null && platformsStr.length() > 0) {
                // Parse the list of platforms that NetBIOS over TCP/IP is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the NetBIOS SMB support, if enabled for this platform

            cifsConfig.setNetBIOSSMB(platformOK);

            // Parse/check NetBIOS settings, if enabled

            if (cifsConfig.hasNetBIOSSMB()) {
                // Check if the broadcast mask has been specified

                if (cifsConfig.getBroadcastMask() == null) {
                    throw new AlfrescoRuntimeException("CIFS Network broadcast mask not specified");
                }

                // Check for a bind address

                String bindto = netBIOSSMBConfigBean.getBindTo();
                if (bindto != null && bindto.length() > 0 && !bindto.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(bindto);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new AlfrescoRuntimeException("CIFS Invalid NetBIOS bind address:" + bindto, ex);
                    }
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                } else {
                    // Get a list of all the local addresses

                    InetAddress[] addrs = null;

                    try {
                        // Get the local server IP address list

                        addrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
                    } catch (UnknownHostException ex) {
                        logger.error("CIFS Failed to get local address list", ex);
                    }

                    // Check the address list for one or more valid local addresses filtering out the loopback
                    // address

                    int addrCnt = 0;

                    if (addrs != null) {
                        for (int i = 0; i < addrs.length; i++) {

                            // Check for a valid address, filter out '127.0.0.1' and '0.0.0.0' addresses

                            if (addrs[i].getHostAddress().equals("127.0.0.1") == false
                                    && addrs[i].getHostAddress().equals("0.0.0.0") == false)
                                addrCnt++;
                        }
                    }

                    // Check if any addresses were found

                    if (addrCnt == 0) {
                        // Enumerate the network adapter list

                        Enumeration<NetworkInterface> niEnum = null;

                        try {
                            niEnum = NetworkInterface.getNetworkInterfaces();
                        } catch (SocketException ex) {
                        }

                        if (niEnum != null) {
                            while (niEnum.hasMoreElements()) {
                                // Get the current network interface

                                NetworkInterface ni = niEnum.nextElement();

                                // Enumerate the addresses for the network adapter

                                Enumeration<InetAddress> niAddrs = ni.getInetAddresses();
                                if (niAddrs != null) {
                                    // Check for any valid addresses

                                    while (niAddrs.hasMoreElements()) {
                                        InetAddress curAddr = niAddrs.nextElement();

                                        if (curAddr.getHostAddress().equals("127.0.0.1") == false
                                                && curAddr.getHostAddress().equals("0.0.0.0") == false)
                                            addrCnt++;
                                    }
                                }
                            }

                            // DEBUG

                            if (addrCnt > 0 && logger.isDebugEnabled())
                                logger.debug("Found valid IP address from interface list");
                        }

                        // Check if we found any valid network addresses

                        if (addrCnt == 0) {
                            // Log the available IP addresses

                            if (logger.isDebugEnabled()) {
                                logger.debug("Local address list dump :-");
                                if (addrs != null) {
                                    for (int i = 0; i < addrs.length; i++)
                                        logger.debug("  Address: " + addrs[i]);
                                } else {
                                    logger.debug("  No addresses");
                                }
                            }

                            // Throw an exception to stop the CIFS/NetBIOS name server from starting

                            throw new AlfrescoRuntimeException(
                                    "Failed to get IP address(es) for the local server, check hosts file and/or DNS setup");
                        }
                    }
                }

                // Check if the session port has been specified

                Integer portNum = netBIOSSMBConfigBean.getSessionPort();
                if (portNum != null) {
                    cifsConfig.setSessionPort(portNum);
                    if (cifsConfig.getSessionPort() <= 0 || cifsConfig.getSessionPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS session port out of valid range");
                }

                // Check if the name port has been specified

                portNum = netBIOSSMBConfigBean.getNamePort();
                if (portNum != null) {
                    cifsConfig.setNameServerPort(portNum);
                    if (cifsConfig.getNameServerPort() <= 0 || cifsConfig.getNameServerPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS name port out of valid range");
                }

                // Check if the datagram port has been specified

                portNum = netBIOSSMBConfigBean.getDatagramPort();
                if (portNum != null) {
                    cifsConfig.setDatagramPort(portNum);
                    if (cifsConfig.getDatagramPort() <= 0 || cifsConfig.getDatagramPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS datagram port out of valid range");
                }

                // Check for a bind address

                String attr = netBIOSSMBConfigBean.getBindTo();
                if (attr != null && attr.length() > 0 && !attr.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(attr);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new InvalidConfigurationException(ex.toString());
                    }
                }

                // Check for a bind address using the adapter name

                else if ((attr = netBIOSSMBConfigBean.getAdapter()) != null && attr.length() > 0) {

                    // Get the bind address via the network adapter name

                    InetAddress bindAddr = parseAdapterName(attr);
                    cifsConfig.setNetBIOSBindAddress(bindAddr);
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                }

            }
        } else {

            // Disable NetBIOS SMB support

            cifsConfig.setNetBIOSSMB(false);
        }

        // Check if TCP/IP SMB is enabled

        TcpipSMBConfigBean tcpipSMBConfigBean = cifsConfigBean.getTcpipSMB();
        if (tcpipSMBConfigBean != null) {

            // Check if native SMB is enabled for the current platform

            String platformsStr = tcpipSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null) {
                // Parse the list of platforms that native SMB is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the TCP/IP SMB support, if enabled for this platform

            cifsConfig.setTcpipSMB(platformOK);

            // Check if the port has been specified

            Integer portNum = tcpipSMBConfigBean.getPort();
            if (portNum != null) {
                cifsConfig.setTcpipSMBPort(portNum);
                if (cifsConfig.getTcpipSMBPort() <= 0 || cifsConfig.getTcpipSMBPort() >= 65535)
                    throw new AlfrescoRuntimeException("TCP/IP SMB port out of valid range");
            }

            // Check if IPv6 support should be enabled

            if (tcpipSMBConfigBean.getIpv6Enabled()) {
                try {
                    // Use the IPv6 bind all address

                    cifsConfig.setSMBBindAddress(InetAddress.getByName("::"));

                    // DEBUG

                    if (logger.isInfoEnabled()) {
                        logger.info("Enabled CIFS IPv6 bind address for native SMB");

                    }
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException(
                            "CIFS Failed to enable IPv6 bind address, " + ex.getMessage());
                }
            }

        } else {

            // Disable TCP/IP SMB support

            cifsConfig.setTcpipSMB(false);
        }

        // Check if Win32 NetBIOS is enabled

        Win32NetBIOSConfigBean win32NetBIOSConfigBean = cifsConfigBean.getWin32NetBIOS();
        if (win32NetBIOSConfigBean != null) {

            // Check if the Win32 NetBIOS server name has been specified

            String win32Name = win32NetBIOSConfigBean.getName();
            if (win32Name != null && win32Name.length() > 0) {

                // Validate the name

                if (win32Name.length() > 16)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS name, " + win32Name);

                // Set the Win32 NetBIOS file server name

                cifsConfig.setWin32NetBIOSName(win32Name);
            }

            // Check if the Win32 NetBIOS LANA has been specified

            String lanaStr = win32NetBIOSConfigBean.getLana();
            if (lanaStr != null && lanaStr.length() > 0) {
                // Check if the LANA has been specified as an IP address or adapter name

                int lana = -1;

                if (IPAddress.isNumericAddress(lanaStr)) {

                    // Convert the IP address to a LANA id

                    lana = Win32NetBIOS.getLANAForIPAddress(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert IP address " + lanaStr + " to a LANA");
                } else if (lanaStr.length() > 1 && Character.isLetter(lanaStr.charAt(0))) {

                    // Convert the network adapter to a LANA id

                    lana = Win32NetBIOS.getLANAForAdapterName(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert network adapter " + lanaStr + " to a LANA");
                } else {

                    try {
                        lana = Integer.parseInt(lanaStr);
                    } catch (NumberFormatException ex) {
                        throw new AlfrescoRuntimeException("Invalid win32 NetBIOS LANA specified");
                    }
                }

                // LANA should be in the range 0-255

                if (lana < 0 || lana > 255)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS LANA number, " + lana);

                // Set the LANA number

                cifsConfig.setWin32LANA(lana);
            }

            // Check if the native NetBIOS interface has been specified, either 'winsock' or 'netbios'

            String nativeAPI = win32NetBIOSConfigBean.getApi();
            if (nativeAPI != null && nativeAPI.length() > 0) {
                // Validate the API type

                boolean useWinsock = true;

                if (nativeAPI.equalsIgnoreCase("netbios"))
                    useWinsock = false;
                else if (nativeAPI.equalsIgnoreCase("winsock") == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid NetBIOS API type, spefify 'winsock' or 'netbios'");

                // Set the NetBIOS API to use

                cifsConfig.setWin32WinsockNetBIOS(useWinsock);
            }

            // Force the older NetBIOS API code to be used on 64Bit Windows

            if (cifsConfig.useWinsockNetBIOS() == true && X64.isWindows64()) {
                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Using older Netbios() API code");

                // Use the older NetBIOS API code

                cifsConfig.setWin32WinsockNetBIOS(false);
            }

            // Check if the current operating system is supported by the Win32
            // NetBIOS handler

            String osName = System.getProperty("os.name");
            if (osName.startsWith("Windows") && (osName.endsWith("95") == false
                    && osName.endsWith("98") == false && osName.endsWith("ME") == false)
                    && isNativeCodeDisabled() == false) {

                // Call the Win32NetBIOS native code to make sure it is initialized

                if (Win32NetBIOS.LanaEnumerate() != null) {
                    // Enable Win32 NetBIOS

                    cifsConfig.setWin32NetBIOS(true);
                } else {
                    logger.warn("No NetBIOS LANAs available");
                }
            } else {

                // Win32 NetBIOS not supported on the current operating system

                cifsConfig.setWin32NetBIOS(false);
            }
        } else {

            // Disable Win32 NetBIOS

            cifsConfig.setWin32NetBIOS(false);
        }

        // Check if the Win32 host announcer has been disabled

        if (!cifsConfigBean.getWin32HostAnnouncerEnabled()) {
            // Switch off the Win32 host announcer

            cifsConfig.setWin32HostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("Win32 host announcements not enabled");
        } else {
            // Check for an announcement interval
            Integer interval = cifsConfigBean.getWin32HostAnnounceInterval();
            if (interval != null) {
                cifsConfig.setWin32HostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null)
                throw new AlfrescoRuntimeException(
                        "Domain name must be specified if host announcement is enabled");

            // Enable Win32 NetBIOS host announcement

            cifsConfig.setWin32HostAnnouncer(true);
        }

        // Check if NetBIOS and/or TCP/IP SMB have been enabled

        if (cifsConfig.hasNetBIOSSMB() == false && cifsConfig.hasTcpipSMB() == false
                && cifsConfig.hasWin32NetBIOS() == false)
            throw new AlfrescoRuntimeException("NetBIOS SMB, TCP/IP SMB or Win32 NetBIOS must be enabled");

        // Check if WINS servers are configured

        WINSConfigBean winsConfigBean = cifsConfigBean.getWINSConfig();

        if (winsConfigBean != null && !winsConfigBean.isAutoDetectEnabled()) {

            // Get the primary WINS server

            String priWins = winsConfigBean.getPrimary();

            if (priWins == null || priWins.length() == 0)
                throw new AlfrescoRuntimeException("No primary WINS server configured");

            // Validate the WINS server address

            InetAddress primaryWINS = null;

            try {
                primaryWINS = InetAddress.getByName(priWins);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("Invalid primary WINS server address, " + priWins);
            }

            // Check if a secondary WINS server has been specified

            String secWins = winsConfigBean.getSecondary();
            InetAddress secondaryWINS = null;

            if (secWins != null && secWins.length() > 0) {

                // Validate the secondary WINS server address

                try {
                    secondaryWINS = InetAddress.getByName(secWins);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid secondary WINS server address, " + secWins);
                }
            }

            // Set the WINS server address(es)

            cifsConfig.setPrimaryWINSServer(primaryWINS);
            if (secondaryWINS != null)
                cifsConfig.setSecondaryWINSServer(secondaryWINS);

            // Pass the setting to the NetBIOS session class

            NetBIOSSession.setDefaultWINSServer(primaryWINS);
        }

        // Check if WINS is configured, if we are running on Windows and socket based NetBIOS is enabled

        else if (cifsConfig.hasNetBIOSSMB() && getPlatformType() == Platform.Type.WINDOWS
                && !isNativeCodeDisabled()) {
            // Get the WINS server list

            String winsServers = Win32NetBIOS.getWINSServerList();

            if (winsServers != null) {
                // Use the first WINS server address for now

                StringTokenizer tokens = new StringTokenizer(winsServers, ",");
                String addr = tokens.nextToken();

                try {
                    // Convert to a network address and check if the WINS server is accessible

                    InetAddress winsAddr = InetAddress.getByName(addr);

                    Socket winsSocket = new Socket();
                    InetSocketAddress sockAddr = new InetSocketAddress(winsAddr, RFCNetBIOSProtocol.NAME_PORT);

                    winsSocket.connect(sockAddr, 3000);
                    winsSocket.close();

                    // Set the primary WINS server address

                    cifsConfig.setPrimaryWINSServer(winsAddr);

                    // Debug

                    if (logger.isDebugEnabled())
                        logger.debug("Configuring to use WINS server " + addr);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid auto WINS server address, " + addr);
                } catch (IOException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Failed to connect to auto WINS server " + addr);
                }
            }
        }

        // Check for session debug flags

        String flags = cifsConfigBean.getSessionDebugFlags();

        int sessDbg = 0;

        if (flags != null && flags.length() > 0) {

            // Parse the flags

            flags = flags.toUpperCase();
            StringTokenizer token = new StringTokenizer(flags, ",");

            while (token.hasMoreTokens()) {
                // Get the current debug flag token

                String dbg = token.nextToken().trim();

                // Find the debug flag name

                int idx = 0;

                while (idx < m_sessDbgStr.length && m_sessDbgStr[idx].equalsIgnoreCase(dbg) == false)
                    idx++;

                if (idx > m_sessDbgStr.length)
                    throw new AlfrescoRuntimeException("Invalid session debug flag, " + dbg);

                // Set the debug flag

                sessDbg += 1 << idx;
            }
        }

        // Set the session debug flags

        cifsConfig.setSessionDebugFlags(sessDbg);

        // Check if NIO based socket code should be disabled

        if (cifsConfigBean.getDisableNIO()) {

            // Disable NIO based code

            cifsConfig.setDisableNIOCode(true);

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("NIO based code disabled for CIFS server");
        }

        // Check if a session timeout is configured

        Integer tmo = cifsConfigBean.getSessionTimeout();
        if (tmo != null) {

            // Validate the session timeout value

            cifsConfigBean.validateSessionTimeout(tmo);

            // Convert the session timeout to milliseconds

            cifsConfig.setSocketTimeout(tmo * 1000);
        }
    } catch (InvalidConfigurationException ex) {
        throw new AlfrescoRuntimeException(ex.getMessage());
    }
}

From source file:cgeo.geocaching.cgBase.java

public static String getLocalIpAddress() {
    try {//from w w  w .  j  ava2 s.  c o  m
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                .hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException e) {
        // nothing
    }

    return null;
}

From source file:net.fenyo.gnetwatch.GUI.GUI.java

private void appendNetworkInterfaces() {
    try {/* w  w w . ja  v  a  2s. c  om*/
        // should be localized
        String str = "<HR/><B>Local network interfaces</B>";
        str += "<TABLE BORDER='0' BGCOLOR='black' cellspacing='1' cellpadding='1'>";
        for (final Enumeration nifs = NetworkInterface.getNetworkInterfaces(); nifs.hasMoreElements();) {
            final NetworkInterface nif = (NetworkInterface) nifs.nextElement();
            str += "<TR><TD bgcolor='lightyellow' align='right'><B>" + htmlFace("interface name")
                    + "</B></TD><TD bgcolor='lightyellow'><B>" + htmlFace(nif.getName()) + "</B></TD></TR>";
            str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("display name")
                    + "</TD><TD bgcolor='lightyellow'>" + htmlFace(nif.getDisplayName()) + "</TD></TR>";
            for (final Enumeration addrs = nif.getInetAddresses(); addrs.hasMoreElements();) {
                final InetAddress addr = (InetAddress) addrs.nextElement();
                if (Inet4Address.class.isInstance(addr))
                    str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("IPv4 address")
                            + "</TD><TD bgcolor='lightyellow'>" + htmlFace(addr.getHostAddress())
                            + "</TD></TR>";
                if (Inet6Address.class.isInstance(addr))
                    str += "<TR><TD bgcolor='lightyellow' align='right'>" + htmlFace("IPv6 address")
                            + "</TD><TD bgcolor='lightyellow'>" + htmlFace(addr.getHostAddress())
                            + "</TD></TR>";
            }
        }
        str += "</TABLE>";
        appendConsole(str);
    } catch (final SocketException ex) {
        log.error("Exception", ex);
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java

private static InetAddress getLocalAddress() {
    Enumeration<NetworkInterface> ifaces = null;
    try {//from   w w w .  j  av a2 s .  c o m
        ifaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        log.error("Failed to get host address", e);
    }
    if (ifaces != null) {
        while (ifaces.hasMoreElements()) {
            NetworkInterface iface = ifaces.nextElement();
            Enumeration<InetAddress> addresses = iface.getInetAddresses();

            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
                    return addr;
                }
            }
        }
    }

    return null;
}

From source file:net.fenyo.gnetwatch.GUI.GUI.java

/**
 * Instanciates the GUI objects./* ww w . j  av  a  2s. c  o  m*/
 * GUI thread.
 * @param none.
 * @return void.
 */
private void createGUI() throws UnknownHostException, SocketException, AlgorithmException {
    final GUI gui = this;

    synchronized (sync_tree) {

        display = new Display();
        shell = new Shell(display);
        shell.setText(getConfig().getString("version"));

        // Shell Layout
        layout = new GridLayout();
        layout.numColumns = 1;
        layout.marginHeight = 2;
        layout.marginWidth = 2;
        layout.verticalSpacing = 1;
        shell.setLayout(layout);
        // shell.setBackground(display.getSystemColor(SWT.COLOR_BLUE));

        // Menu
        menu_bar = new Menu(shell, SWT.BAR);
        shell.setMenuBar(menu_bar);

        // Menu "File"
        menu_file = new Menu(shell, SWT.DROP_DOWN);
        menu_item_file = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_file.setText(getConfig().getString("menu_file"));
        menu_item_file.setMenu(menu_file);

        // Menu "file": MenuItem "Merge events now"
        menu_item_merge_now = new MenuItem(menu_file, SWT.PUSH);
        menu_item_merge_now.setText(getConfig().getString("menu_merge_events_now"));
        menu_item_merge_now.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                background.getMergeQueue().informCycle();
            }
        });

        new MenuItem(menu_file, SWT.SEPARATOR);

        // Menu "file": MenuItem "Exit"
        menu_item_exit = new MenuItem(menu_file, SWT.PUSH);
        menu_item_exit.setText(getConfig().getString("menu_exit"));
        menu_item_exit.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                gui.exitApplication();
            }
        });
        menu_item_exit.setImage(new Image(display, "pictures/exit.png"));

        // Menu "Discover"
        final Menu menu_discover = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_discover = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_discover.setText(getConfig().getString("menu_discover"));
        menu_item_discover.setMenu(menu_discover);

        // Menu "Discover": MenuItem "Start" and "Stop"
        final MenuItem menu_item_discover_start = new MenuItem(menu_discover, SWT.PUSH);
        final MenuItem menu_item_discover_stop = new MenuItem(menu_discover, SWT.PUSH);
        menu_item_discover_start.setText(getConfig().getString("menu_start"));
        menu_item_discover_start.setImage(new Image(display, "pictures/exec.png"));
        menu_item_discover_stop.setText(getConfig().getString("menu_stop"));
        menu_item_discover_stop.setImage(new Image(display, "pictures/fileclose.png"));
        menu_item_discover_stop.setEnabled(false);
        menu_item_discover_start.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_discover_start.setEnabled(false);
                item_discover_start.setEnabled(false);
                main.startDiscover();
                menu_item_discover_stop.setEnabled(true);
                item_discover_stop.setEnabled(true);
            }
        });
        menu_item_discover_stop.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_discover_start.setEnabled(true);
                item_discover_start.setEnabled(true);
                main.stopDiscover();
                menu_item_discover_stop.setEnabled(false);
                item_discover_stop.setEnabled(false);
            }
        });

        // Menu "Tree"
        final Menu menu_tree = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_tree = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_tree.setText(getConfig().getString("menu_tree"));
        menu_item_tree.setMenu(menu_tree);

        // Menu "Tree": MenuItem "Expand"
        final MenuItem menu_item_expand = new MenuItem(menu_tree, SWT.PUSH);
        menu_item_expand.setText(getConfig().getString("expand"));
        menu_item_expand.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    tree.getSelection()[0].setExpanded(true);
            }
        });

        // Menu "Tree": MenuItem "Merge"
        final MenuItem menu_item_merge = new MenuItem(menu_tree, SWT.PUSH);
        menu_item_merge.setText(getConfig().getString("collapse"));
        menu_item_merge.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    tree.getSelection()[0].setExpanded(false);
            }
        });

        new MenuItem(menu_tree, SWT.SEPARATOR);

        // Menu "Tree": MenuItem "Expand All"
        final MenuItem menu_item_expand_all = new MenuItem(menu_tree, SWT.PUSH);
        menu_item_expand_all.setText(getConfig().getString("menu_expand_all"));
        menu_item_expand_all.setImage(new Image(display, "pictures/show_table_column.png"));
        menu_item_expand_all.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    expandAll(tree.getSelection()[0]);
            }
        });

        // Menu "Tree": MenuItem "Merge All"
        final MenuItem menu_item_merge_all = new MenuItem(menu_tree, SWT.PUSH);
        menu_item_merge_all.setText(getConfig().getString("menu_collapse_all"));
        menu_item_merge_all.setImage(new Image(display, "pictures/hide_table_column.png"));
        menu_item_merge_all.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    mergeAll(tree.getSelection()[0]);
            }
        });

        // Menu "Target"
        final Menu menu_target = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_target = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_target.setText(getConfig().getString("menu_target"));
        menu_item_target.setMenu(menu_target);

        // Menu "Target": MenuItem "Set Credentials"
        menu_item_credentials = new MenuItem(menu_target, SWT.PUSH);
        menu_item_credentials.setText(getConfig().getString("menu_set_credentials"));
        menu_item_credentials.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                final SNMPQuerier querier;

                synchronized (sync_tree) {
                    if (tree.getSelectionCount() == 1
                            && (/* isSelectionPersistent() || */ isSelectionTransient())) {
                        final VisualElement target = (VisualElement) tree.getSelection()[0]
                                .getData(VisualElement.class.toString());

                        if (target != null && (TargetIPv4.class.isInstance(target)
                                || TargetIPv6.class.isInstance(target))) {
                            if (TargetIPv4.class.isInstance(target))
                                querier = ((TargetIPv4) target).getSNMPQuerier();
                            else
                                querier = ((TargetIPv6) target).getSNMPQuerier();
                        } else
                            return;
                    } else
                        return;
                }

                final int version = querier.getVersion();
                final int sec = querier.getSec();
                final int port_src = querier.getRetries();
                final int timeout = querier.getTimeout();
                final int port = querier.getPort();
                final String community = querier.getCommunity();
                final String username = querier.getUsername();
                final String password_auth = querier.getPasswordAuth();
                final String password_priv = querier.getPasswordPriv();
                final int pdu_max_size = querier.getPDUMaxSize();

                final DialogCredentials dialog = new DialogCredentials(gui, shell);
                dialog.setVersion(version);
                dialog.setSec(sec);
                dialog.setRetries(port_src);
                dialog.setTimeout(timeout);
                dialog.setPort(port);
                dialog.setCommunity(community);
                dialog.setUsername(username);
                dialog.setPasswordAuth(password_auth);
                dialog.setPasswordPriv(password_priv);
                dialog.setPDUMaxSize(pdu_max_size);

                dialog.open();

                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(querier);
                            if (dialog.getVersion() != version)
                                querier.setVersion(dialog.getVersion());
                            if (dialog.getSec() != sec)
                                querier.setSec(dialog.getSec());
                            if (dialog.getRetries() != port_src)
                                querier.setRetries(dialog.getRetries());
                            if (dialog.getTimeout() != timeout)
                                querier.setTimeout(dialog.getTimeout());
                            if (dialog.getPort() != port)
                                querier.setPort(dialog.getPort());
                            if (dialog.getCommunity() != community)
                                querier.setCommunity(dialog.getCommunity());
                            if (dialog.getUsername() != username)
                                querier.setUsername(dialog.getUsername());
                            if (dialog.getPasswordAuth() != password_auth)
                                querier.setPasswordAuth(dialog.getPasswordAuth());
                            if (dialog.getPasswordPriv() != password_priv)
                                querier.setPasswordPriv(dialog.getPasswordPriv());
                            if (dialog.getPDUMaxSize() != pdu_max_size)
                                querier.setPDUMaxSize(dialog.getPDUMaxSize());
                            querier.update();
                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }
            }
        });

        // Menu "Target": MenuItem "Set IP options"
        menu_item_ip_options = new MenuItem(menu_target, SWT.PUSH);
        menu_item_ip_options.setText(getConfig().getString("menu_set_ip_options"));
        menu_item_ip_options.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                final IPQuerier querier;

                synchronized (sync_tree) {
                    if (tree.getSelectionCount() == 1
                            && (/* isSelectionPersistent() || */ isSelectionTransient())) {
                        final VisualElement target = (VisualElement) tree.getSelection()[0]
                                .getData(VisualElement.class.toString());

                        if (target != null && (TargetIPv4.class.isInstance(target)
                                || TargetIPv6.class.isInstance(target))) {
                            if (TargetIPv4.class.isInstance(target))
                                querier = ((TargetIPv4) target).getIPQuerier();
                            else
                                querier = ((TargetIPv6) target).getIPQuerier();
                        } else
                            return;
                    } else
                        return;
                }

                final int tos = querier.getTos();
                final int port_src = querier.getPortSrc();
                final int port_dst = querier.getPortDst();
                final int pdu_max_size = querier.getPDUMaxSize();

                final DialogIPOptions dialog = new DialogIPOptions(gui, shell);

                dialog.setTOS(tos);
                dialog.setPortSrc(port_src);
                dialog.setPortDst(port_dst);
                dialog.setPDUMaxSize(pdu_max_size);

                dialog.open();

                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(querier);
                            if (dialog.getTOS() != tos)
                                querier.setTos(dialog.getTOS());
                            if (dialog.getPortSrc() != port_src)
                                querier.setPortSrc(dialog.getPortSrc());
                            if (dialog.getPortDst() != port_dst)
                                querier.setPortDst(dialog.getPortDst());
                            if (dialog.getPDUMaxSize() != pdu_max_size)
                                querier.setPDUMaxSize(dialog.getPDUMaxSize());
                            querier.update();
                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }
            }
        });

        // Menu "Target": MenuItem "Set HTTP/FTP options"
        menu_item_http_options = new MenuItem(menu_target, SWT.PUSH);
        menu_item_http_options.setText(getConfig().getString("menu_set_http_options"));
        menu_item_http_options.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                final IPQuerier querier;

                synchronized (sync_tree) {
                    if (tree.getSelectionCount() == 1
                            && (/* isSelectionPersistent() || */ isSelectionTransient())) {
                        final VisualElement target = (VisualElement) tree.getSelection()[0]
                                .getData(VisualElement.class.toString());

                        if (target != null && (TargetIPv4.class.isInstance(target)
                                || TargetIPv6.class.isInstance(target))) {
                            if (TargetIPv4.class.isInstance(target))
                                querier = ((TargetIPv4) target).getIPQuerier();
                            else
                                querier = ((TargetIPv6) target).getIPQuerier();
                        } else
                            return;
                    } else
                        return;
                }

                final int nparallel = querier.getNParallel();
                final String proxy_host = querier.getProxyHost();
                final int proxy_port = querier.getProxyPort();
                final String URL = querier.getURL();
                //        final boolean reconnect = querier.getReconnect();
                final boolean use_proxy = querier.getUseProxy();

                final DialogHTTPOptions dialog = new DialogHTTPOptions(gui, shell);

                dialog.setNParallel(nparallel);
                dialog.setProxyHost(proxy_host);
                dialog.setProxyPort(proxy_port);
                dialog.setURL(URL);
                //        dialog.setReconnect(reconnect);
                dialog.setUseProxy(use_proxy);

                dialog.open();

                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            session.update(querier);
                            if (dialog.getNParallel() != nparallel)
                                querier.setNParallel(dialog.getNParallel());
                            if (dialog.getProxyHost() != proxy_host)
                                querier.setProxyHost(dialog.getProxyHost());
                            if (dialog.getProxyPort() != proxy_port)
                                querier.setProxyPort(dialog.getProxyPort());
                            if (dialog.getURL() != URL)
                                querier.setURL(dialog.getURL());
                            //              if (dialog.getReconnect() != reconnect) querier.setReconnect(dialog.getReconnect());
                            if (dialog.getUseProxy() != use_proxy)
                                querier.setUseProxy(dialog.getUseProxy());
                            querier.update();
                            session.getTransaction().commit();
                        } catch (final Exception ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        }
                    }
                }
            }
        });

        // Menu "Target": MenuItem "Set generic options"
        menu_item_generic_options = new MenuItem(menu_target, SWT.PUSH);
        menu_item_generic_options.setText(getConfig().getString("menu_set_generic_options"));
        menu_item_generic_options.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                final GenericQuerier querier;

                synchronized (sync_tree) {
                    if (tree.getSelectionCount() == 1
                            && (/* isSelectionPersistent() || */ isSelectionTransient())) {
                        final VisualElement target = (VisualElement) tree.getSelection()[0]
                                .getData(VisualElement.class.toString());

                        if (target != null && TargetGroup.class.isInstance(target)) {
                            querier = ((TargetGroup) target).getGenericQuerier();
                        } else
                            return;
                    } else
                        return;
                }

                final String title = querier.getTitle();
                final String cmdline = querier.getCommandLine();
                final String workdir = querier.getWorkingDirectory();
                final String filename = querier.getFileName();
                final String unit = querier.getUnit();

                final DialogGeneric dialog = new DialogGeneric(gui, shell);

                dialog.setTitle(title);
                dialog.setCommandLine(cmdline);
                dialog.setWorkdir(workdir);
                dialog.setFilename(filename);
                dialog.setUnit(unit);

                dialog.open();

                if (dialog.isOK())
                    synchronized (synchro) {
                        synchronized (sync_tree) {
                            final Session session = synchro.getSessionFactory().getCurrentSession();
                            session.beginTransaction();

                            try {
                                session.update(querier);
                                if (dialog.getTitle() != title)
                                    querier.setTitle(dialog.getTitle());
                                if (dialog.getCommandLine() != cmdline)
                                    querier.setCommandLine(dialog.getCommandLine());
                                if (dialog.getWorkdir() != workdir)
                                    querier.setWorkingDirectory(dialog.getWorkdir());
                                if (dialog.getFilename() != filename)
                                    querier.setFileName(dialog.getFilename());
                                if (dialog.getUnit() != unit)
                                    querier.setUnit(dialog.getUnit());

                                session.getTransaction().commit();
                            } catch (final Exception ex) {
                                log.error("Exception", ex);
                                session.getTransaction().rollback();
                            }
                        }
                    }
            }
        });

        new MenuItem(menu_target, SWT.SEPARATOR);

        // Menu "Target": MenuItem "Add IPv4 Host"
        menu_item_add_host = new MenuItem(menu_target, SWT.PUSH);
        menu_item_add_host.setText(getConfig().getString("menu_add_ipv4"));
        menu_item_add_host.setImage(new Image(display, "pictures/network_local.png"));
        menu_item_add_host.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                target_host_push.notifyListeners(SWT.Selection, e);
            }
        });

        // Menu "Target": MenuItem "Add IPv6 Host"
        menu_item_add_host6 = new MenuItem(menu_target, SWT.PUSH);
        menu_item_add_host6.setText(getConfig().getString("menu_add_ipv6"));
        menu_item_add_host6.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                target_host6_push.notifyListeners(SWT.Selection, e);
            }
        });

        // Menu "Target": MenuItem "Add Range"
        menu_item_add_range = new MenuItem(menu_target, SWT.PUSH);
        menu_item_add_range.setText(getConfig().getString("menu_add_range"));
        menu_item_add_range.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                target_range_push.notifyListeners(SWT.Selection, e);
            }
        });

        // Menu "Target": MenuItem "Add Network"
        menu_item_add_network = new MenuItem(menu_target, SWT.PUSH);
        menu_item_add_network.setText(getConfig().getString("menu_add_network"));
        menu_item_add_network.setImage(new Image(display, "pictures/network.png"));
        menu_item_add_network.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                target_subnet_push.notifyListeners(SWT.Selection, e);
            }
        });

        // Menu "Target": MenuItem "Add Group"
        menu_item_add_group = new MenuItem(menu_target, SWT.PUSH);
        menu_item_add_group.setText(getConfig().getString("menu_add_group"));
        menu_item_add_group.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                target_group_push.notifyListeners(SWT.Selection, e);
            }
        });

        new MenuItem(menu_target, SWT.SEPARATOR);

        // Menu "Target": MenuItem "Remove Element"
        menu_item_remove_target = new MenuItem(menu_target, SWT.PUSH);
        menu_item_remove_target.setText(getConfig().getString("menu_remove_element"));
        menu_item_remove_target.setImage(new Image(display, "pictures/nomailappt.png"));
        menu_item_remove_target.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeVisualElements(tree.getSelection()[0]);
            }
        });

        // Menu "Action"
        final Menu menu_action = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_action = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_action.setText(getConfig().getString("menu_action"));
        menu_item_action.setMenu(menu_action);

        /*
            // Menu "Action": MenuItem "Sysdescr"
            final MenuItem menu_item_sysdescr = new MenuItem(menu_action, SWT.PUSH);
            menu_item_sysdescr.setText(getConfig().getString("menu_get_system_description"));
            menu_item_sysdescr.setImage(new Image(display, "pictures/yahoo_idle-af.png"));
            menu_item_sysdescr.addSelectionListener(new SelectionListener() {
              public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
              }
                
              public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1) getSysdescr(tree.getSelection()[0]);
                }
            });
        */

        // Menu "Action": MenuItem "Add Ping"
        menu_item_add_ping = new MenuItem(menu_action, SWT.PUSH);
        menu_item_add_ping.setText(getConfig().getString("menu_ping_target"));
        menu_item_add_ping.setImage(new Image(display, "pictures/yahoo_idle-af.png"));
        menu_item_add_ping.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    addPingAll(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Add Generic Process"
        menu_item_add_process = new MenuItem(menu_action, SWT.PUSH);
        menu_item_add_process.setText(getConfig().getString("menu_generic_process"));
        menu_item_add_process.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    addProcessAll(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Add Generic Source"
        menu_item_add_source = new MenuItem(menu_action, SWT.PUSH);
        menu_item_add_source.setText(getConfig().getString("menu_generic_source"));
        menu_item_add_source.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    addSourceAll(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Add Flood"
        menu_item_add_flood = new MenuItem(menu_action, SWT.PUSH);
        menu_item_add_flood.setText(getConfig().getString("menu_flood_target"));
        menu_item_add_flood.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    addFloodAll(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Add Flood"
        menu_item_add_http = new MenuItem(menu_action, SWT.PUSH);
        menu_item_add_http.setText(getConfig().getString("menu_http_target"));
        menu_item_add_http.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    addHTTPAll(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Explore via SNMP"
        menu_item_explore_snmp = new MenuItem(menu_action, SWT.PUSH);
        menu_item_explore_snmp.setText(getConfig().getString("menu_explore_via_snmp"));
        menu_item_explore_snmp.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    exploreSNMP(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Explore via Nmap"
        menu_item_explore_nmap = new MenuItem(menu_action, SWT.PUSH);
        menu_item_explore_nmap.setText(getConfig().getString("menu_explore_via_nmap"));
        menu_item_explore_nmap.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    exploreNmap(tree.getSelection()[0]);
            }
        });

        new MenuItem(menu_action, SWT.SEPARATOR);

        // Menu "Action": MenuItem "Drop Action"
        menu_item_remove_action = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_action.setText(getConfig().getString("menu_drop_action"));
        menu_item_remove_action.setImage(new Image(display, "pictures/button_cancel-af.png"));
        menu_item_remove_action.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeActions(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop Action Ping"
        menu_item_remove_action_ping = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_action_ping.setText(getConfig().getString("menu_drop_action_ping"));
        menu_item_remove_action_ping.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeActionsPing(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop Action Flood"
        menu_item_remove_action_flood = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_action_flood.setText(getConfig().getString("menu_drop_action_flood"));
        menu_item_remove_action_flood.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeActionsFlood(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop Action Explore"
        menu_item_remove_action_explore = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_action_explore.setText(getConfig().getString("menu_drop_action_explore"));
        menu_item_remove_action_explore.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeActionsExplore(tree.getSelection()[0]);
            }
        });

        new MenuItem(menu_action, SWT.SEPARATOR);

        // Menu "Action": MenuItem "Drop View"
        menu_item_remove_view = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_view.setText(getConfig().getString("menu_drop_view"));
        menu_item_remove_view.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeViews(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop View Ping"
        menu_item_remove_view_ping = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_view_ping.setText(getConfig().getString("menu_drop_view_ping"));
        menu_item_remove_view_ping.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeViewsPing(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop View Flood"
        menu_item_remove_view_flood = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_view_flood.setText(getConfig().getString("menu_drop_view_flood"));
        menu_item_remove_view_flood.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeViewsFlood(tree.getSelection()[0]);
            }
        });

        // Menu "Action": MenuItem "Drop View Explore"
        menu_item_remove_view_explore = new MenuItem(menu_action, SWT.PUSH);
        menu_item_remove_view_explore.setText(getConfig().getString("menu_drop_view_explore"));
        menu_item_remove_view_explore.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                if (tree.getSelectionCount() == 1)
                    removeViewsExplore(tree.getSelection()[0]);
            }
        });

        // Menu "View"
        final Menu menu_view = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_view = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_view.setText(getConfig().getString("menu_snmp_info"));
        menu_item_view.setMenu(menu_view);

        // Menu "View": MenuItem "Get SysDescr"
        final MenuItem menu_item_open_view = new MenuItem(menu_view, SWT.PUSH);
        menu_item_open_view.setText(getConfig().getString("menu_get_system_description"));
        menu_item_open_view.setImage(new Image(display, "pictures/multirow.png"));
        menu_item_open_view.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getSysdescr(tree.getSelection()[0]);
            }
        });

        // Menu "View": MenuItem "Get General Information"
        final MenuItem menu_item_get_general_information = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_general_information.setText(getConfig().getString("menu_get_general_information"));
        menu_item_get_general_information.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getGeneralInformation(tree.getSelection()[0]);
            }
        });

        // Menu "View": MenuItem "Get Routing Table"
        final MenuItem menu_item_get_routing_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_routing_table.setText(getConfig().getString("menu_get_routing_table"));
        menu_item_get_routing_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                // if (tree.getSelectionCount() == 1) getRoutingTable(tree.getSelection()[0]);
                if (tree.getSelectionCount() == 1)
                    getGenericTable(tree.getSelection()[0], "route", "1.3.6.1.2.1.4.21.1",
                            new int[] { 9, 1, 11, 2, 7, 8, 10, 3, 4, 5, 6, 12, 13 },
                            new String[] { "proto", "destination", "netmask", "interface", "next hop", "type",
                                    "age", "metric1", "metric2", "metric3", "metric4", "metric5", "info" },
                            new Object[][] {
                                    { 0, "gnetwatch error", "other", "local", "netmgmt", "icmp", "egp", "ggp",
                                            "hello", "rip", "is-is", "es-is", "ciscoIgrp", "bbnSpfIgp", "ospf",
                                            "bgp" },
                                    { 5, "gnetwatch error", "other", "invalid", "direct", "indirect" },
                                    { 3 } });
            }
        });

        // Menu "View": MenuItem "Get Arp Table"
        final MenuItem menu_item_get_arp_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_arp_table.setText(getConfig().getString("menu_get_arp_table"));
        menu_item_get_arp_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getArpTable(tree.getSelection()[0]);
            }
        });

        // Menu "View": MenuItem "Get Interfaces Table"
        final MenuItem menu_item_get_ifs_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_ifs_table.setText(getConfig().getString("menu_get_ifs_table"));
        menu_item_get_ifs_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            // snmptranslate -Td IF-MIB::ifMtu
            // ::= { iso(1) org(3) dod(6) internet(1) mgmt(2) mib-2(1) interfaces(2) ifTable(2) ifEntry(1) 4 }
            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getGenericTable(tree.getSelection()[0], "interface", "1.3.6.1.2.1.2.2.1",
                            // echo {1..22} | sed 's/ /, /g'
                            new int[] { 1, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
                                    21, 22 },
                            // res.txt : dfinition de ifEntry
                            // echo `cat res.txt | grep -v ',' | grep if | sed 's/ */"/' | sed 's/$/"/'` | sed 's/ /, /g'
                            new String[] { "ifIndex", "ifDescr", "ifType", "ifMtu", "ifSpeed", "ifPhysAddress",
                                    "ifAdminStatus", "ifOperStatus", "ifLastChange", "ifInOctets",
                                    "ifInUcastPkts", "ifInNUcastPkts", "ifInDiscards", "ifInErrors",
                                    "ifInUnknownProtos", "ifOutOctets", "ifOutUcastPkts", "ifOutNUcastPkts",
                                    "ifOutDiscards", "ifOutErrors", "ifOutQLen", "ifSpecific" },
                            new Object[][] { { 1 },
                                    // type.txt : dfinition de ifType
                                    // echo `cat type.txt | fgrep '(' | sed 's/ *//' | sed 's/(.*/"/' | sed 's/^/"/'` | sed 's/ /, /g'
                                    // et rajouter "gnetwatch error" au dbut
                                    // if Type ::= { ifEntry 3 }
                                    { 2, "gnetwatch error", "other", "regular1822", "hdh1822", "ddn-x25",
                                            "rfc877-x25", "ethernet-csmacd", "iso88023-csmacd",
                                            "iso88024-tokenBus", "iso88025-tokenRing", "iso88026-man",
                                            "starLan", "proteon-10Mbit", "proteon-80Mbit", "hyperchannel",
                                            "fddi", "lapb", "sdlc", "ds1", "e1", "basicISDN", "primaryISDN",
                                            "propPointToPointSerial", "ppp", "softwareLoopback", "eon",
                                            "ethernet-3Mbit", "nsip", "slip", "ultra", "ds3", "sip",
                                            "frame-relay" },
                                    { 6, "gnetwatch error", "up", "down", "testing" },
                                    { 7, "gnetwatch error", "up", "down", "testing" } });
            }
        });

        // Menu "View": MenuItem "Get .3 Stats Table"
        final MenuItem menu_item_get_dot3stats_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_dot3stats_table.setText(getConfig().getString("menu_get_dot3stats_table"));
        menu_item_get_dot3stats_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            // snmptranslate -m ALL -M"/usr/share/snmp/mibs:$HOME/MIBs/Cisco:$HOME/MIBS/3Com" -Td ETHERLIKE-MIB::dot3StatsDuplexStatus 2> /dev/null
            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getGenericTable(tree.getSelection()[0], "Ethernet", "1.3.6.1.2.1.10.7.2.1",
                            new int[] { 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 16, 18, 19, 20, 21 },
                            // res.txt : dfinition de ifEntry
                            // echo `egrep '^   ' res.txt | grep ',' | sed 's/ */"/' | sed 's/ .*/"/' ` | sed  's/ /, /g'
                            new String[] { "dot3StatsIndex", "ifName", "dot3StatsAlignmentErrors",
                                    "dot3StatsFCSErrors", "dot3StatsSingleCollisionFrames",
                                    "dot3StatsMultipleCollisionFrames", "dot3StatsSQETestErrors",
                                    "dot3StatsDeferredTransmissions", "dot3StatsLateCollisions",
                                    "dot3StatsExcessiveCollisions", "dot3StatsInternalMacTransmitErrors",
                                    "dot3StatsCarrierSenseErrors", "dot3StatsFrameTooLongs",
                                    "dot3StatsInternalMacReceiveErrors", "dot3StatsSymbolErrors",
                                    "dot3StatsDuplexStatus", "dot3StatsRateControlAbility",
                                    "dot3StatsRateControlStatus" },
                            new Object[][] { { 1 },
                                    { 15, "gnetwatch error", "duplex mode unknown", "half-duplex",
                                            "full-duplex" },
                                    { 16, "false", "true" }, { 17, "gnetwatch error", "control off",
                                            "control on", "unknown control mode" }, });
            }
        });

        new MenuItem(menu_view, SWT.SEPARATOR);

        // Menu "View": MenuItem "Get VLAN Table"
        final MenuItem menu_item_get_vlan_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_vlan_table.setText(getConfig().getString("menu_get_vlan_table"));
        menu_item_get_vlan_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getGenericTable(tree.getSelection()[0], "VLANs", "1.3.6.1.4.1.9.9.46.1.3.1.1",
                            new int[] { 18, 4, 2 }, new String[] { "vlan ID", "vlan name", "vlan state" },
                            new Object[][] { { 0, "#idx" }, { 2, "gnetwatch error", "operational", "suspended",
                                    "mtuTooBigForDevice", "mtuTooBigForTrunk" } });
            }
        });

        // Menu "View": MenuItem "Mac2If"
        final MenuItem menu_item_get_mac2if_table = new MenuItem(menu_view, SWT.PUSH);
        menu_item_get_mac2if_table.setText(getConfig().getString("menu_mac2if_table"));
        menu_item_get_mac2if_table.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                widgetSelected(e);
            }

            public void widgetSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1)
                    getMACTable(tree.getSelection()[0]);
            }
        });

        /*
        // Menu "View": MenuItem getConfig().getString("menu_open_graph")
        final MenuItem menu_item_open_graph = new MenuItem(menu_view, SWT.PUSH);
        menu_item_open_graph.setText(getConfig().getString("menu_open_graph"));
        menu_item_open_graph.setImage(new Image(display, "pictures/oscilloscope-af.png"));
        menu_item_open_graph.addListener(SWT.Selection, new Listener() {
          public void handleEvent(final Event e) {
            log.debug("open graph");
          }
        });
                
        // Menu "View": MenuItem getConfig().getString("menu_close_view")
        final MenuItem menu_item_close_view = new MenuItem(menu_view, SWT.PUSH);
        menu_item_close_view.setText(getConfig().getString("menu_close_view"));
        menu_item_close_view.setImage(new Image(display, "pictures/multirow-af-cross.png"));
        menu_item_close_view.addListener(SWT.Selection, new Listener() {
          public void handleEvent(final Event e) {
            log.debug("close view");
          }
        });
        */

        // Menu "Status"
        final Menu menu_status = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_status = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_status.setText(getConfig().getString("menu_status"));
        menu_item_status.setMenu(menu_status);

        // Menu "Status": MenuItem "Local interfaces"
        final MenuItem menu_item_local_interfaces = new MenuItem(menu_status, SWT.PUSH);
        menu_item_local_interfaces.setText(getConfig().getString("menu_local_interfaces"));
        menu_item_local_interfaces.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                appendNetworkInterfaces();
            }
        });

        // Menu "Status": MenuItem "Database statistics"
        final MenuItem menu_item_database_statistics = new MenuItem(menu_status, SWT.PUSH);
        menu_item_database_statistics.setText(getConfig().getString("menu_database_statistics"));
        menu_item_database_statistics.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                appendDatabaseStatistics();
            }
        });

        // Menu "Window"
        final Menu menu_window = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_window = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_window.setText(getConfig().getString("menu_window"));
        menu_item_window.setMenu(menu_window);

        // Menu "Window": MenuItem "Hide left panel"
        menu_item_hide = new MenuItem(menu_window, SWT.PUSH);
        menu_item_hide.setText(getConfig().getString("menu_hide"));
        menu_item_hide.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_hide.setEnabled(false);
                menu_item_show.setEnabled(true);
                groups_composite_grid_data.exclude = true;
                groups_composite.setVisible(false);
                horizontal_composite.layout();
            }
        });

        // Menu "Window": MenuItem "Show left panel"
        menu_item_show = new MenuItem(menu_window, SWT.PUSH);
        menu_item_show.setText(getConfig().getString("menu_show"));
        menu_item_show.setEnabled(false);
        menu_item_show.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_hide.setEnabled(true);
                menu_item_show.setEnabled(false);
                groups_composite_grid_data.exclude = false;
                groups_composite.setVisible(true);
                horizontal_composite.layout();
            }
        });

        new MenuItem(menu_window, SWT.SEPARATOR);

        // Menu "Window": MenuItem "Clear information panel"
        menu_item_clear = new MenuItem(menu_window, SWT.PUSH);
        menu_item_clear.setText(getConfig().getString("menu_clear"));
        menu_item_clear.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                clearConsole();
            }
        });

        // Menu "Help"
        final Menu menu_help = new Menu(shell, SWT.DROP_DOWN);
        final MenuItem menu_item_help = new MenuItem(menu_bar, SWT.CASCADE);
        menu_item_help.setText(getConfig().getString("menu_help"));
        menu_item_help.setMenu(menu_help);

        // Menu "Help": MenuItem "Welcome"
        final MenuItem menu_item_welcome = new MenuItem(menu_help, SWT.PUSH);
        menu_item_welcome.setText(getConfig().getString("menu_welcome"));
        menu_item_welcome.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                tab_folder.setSelection(tab_item1);
            }
        });

        // Menu "Help": MenuItem "Help Contents"
        final MenuItem menu_item_help_contents = new MenuItem(menu_help, SWT.PUSH);
        menu_item_help_contents.setText(getConfig().getString("menu_help_contents"));
        menu_item_help_contents.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                tab_folder.setSelection(tab_item2);
            }
        });

        new MenuItem(menu_help, SWT.SEPARATOR);

        // Menu "Help": MenuItem "About"
        final MenuItem menu_item_about = new MenuItem(menu_help, SWT.PUSH);
        menu_item_about.setText(getConfig().getString("menu_about"));
        menu_item_about.setImage(new Image(display, "pictures/info.png"));
        menu_item_about.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                final DialogAbout dialog = new DialogAbout(gui, shell);
                dialog.open();
            }
        });

        /*
        new MenuItem(menu_help, SWT.SEPARATOR);
                
        // Menu "Help": MenuItem "Software Update"
        final MenuItem menu_item_new_version = new MenuItem(menu_help, SWT.PUSH);
        menu_item_new_version.setText(getConfig().getString("menu_software_update"));
        menu_item_new_version.addListener(SWT.Selection, new Listener() {
          public void handleEvent(final Event e) {
            log.debug("new version");
          }
        });
        */

        /*
         * ToolBar
         */
        toolbar = new ToolBar(shell, SWT.FLAT);
        final ToolItem item_exit = new ToolItem(toolbar, SWT.PUSH);
        item_exit.setImage(new Image(display, "pictures/exit.png"));
        item_exit.setToolTipText(getConfig().getString("exit"));
        item_exit.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_exit.notifyListeners(SWT.Selection, e);
            }
        });

        new ToolItem(toolbar, SWT.SEPARATOR);

        item_discover_start = new ToolItem(toolbar, SWT.PUSH);
        item_discover_start.setImage(new Image(display, "pictures/exec.png"));
        item_discover_start.setToolTipText(getConfig().getString("start_sniffer"));
        item_discover_start.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_discover_start.notifyListeners(SWT.Selection, e);
            }
        });

        item_discover_stop = new ToolItem(toolbar, SWT.PUSH);
        item_discover_stop.setImage(new Image(display, "pictures/fileclose.png"));
        item_discover_stop.setToolTipText(getConfig().getString("stop_sniffer"));
        item_discover_stop.setEnabled(false);
        item_discover_stop.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_discover_stop.notifyListeners(SWT.Selection, e);
            }
        });

        new ToolItem(toolbar, SWT.SEPARATOR);

        final ToolItem item_expand_all = new ToolItem(toolbar, SWT.PUSH);
        item_expand_all.setImage(new Image(display, "pictures/show_table_column.png"));
        item_expand_all.setToolTipText(getConfig().getString("expand_all"));
        item_expand_all.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_expand_all.notifyListeners(SWT.Selection, e);
            }
        });

        final ToolItem item_merge_all = new ToolItem(toolbar, SWT.PUSH);
        item_merge_all.setImage(new Image(display, "pictures/hide_table_column.png"));
        item_merge_all.setToolTipText(getConfig().getString("collapse_all"));
        item_merge_all.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_merge_all.notifyListeners(SWT.Selection, e);
            }
        });

        new ToolItem(toolbar, SWT.SEPARATOR);

        item_add_host = new ToolItem(toolbar, SWT.PUSH);
        item_add_host.setImage(new Image(display, "pictures/network_local.png"));
        item_add_host.setToolTipText(getConfig().getString("add_ipv4_host"));
        item_add_host.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_add_host.notifyListeners(SWT.Selection, e);
            }
        });

        item_add_network = new ToolItem(toolbar, SWT.PUSH);
        item_add_network.setImage(new Image(display, "pictures/network.png"));
        item_add_network.setToolTipText(getConfig().getString("add_network"));
        item_add_network.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_add_network.notifyListeners(SWT.Selection, e);
            }
        });

        item_remove_target = new ToolItem(toolbar, SWT.PUSH);
        item_remove_target.setImage(new Image(display, "pictures/nomailappt.png"));
        item_remove_target.setToolTipText(getConfig().getString("remove_element"));
        item_remove_target.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_remove_target.notifyListeners(SWT.Selection, e);
            }
        });

        new ToolItem(toolbar, SWT.SEPARATOR);

        item_add_ping = new ToolItem(toolbar, SWT.PUSH);
        item_add_ping.setImage(new Image(display, "pictures/yahoo_idle-af.png"));
        item_add_ping.setToolTipText("ping");
        item_add_ping.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_add_ping.notifyListeners(SWT.Selection, e);
            }
        });

        item_remove_action = new ToolItem(toolbar, SWT.PUSH);
        item_remove_action.setImage(new Image(display, "pictures/button_cancel-af.png"));
        item_remove_action.setToolTipText(getConfig().getString("drop_action"));
        item_remove_action.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_remove_action.notifyListeners(SWT.Selection, e);
            }
        });

        /*
            new ToolItem(toolbar, SWT.SEPARATOR);
                
            final ToolItem item_open_view = new ToolItem(toolbar, SWT.PUSH);
            item_open_view.setImage(new Image(display, "pictures/multirow.png"));
            item_open_view.setToolTipText("open view");
            item_open_view.addListener(SWT.Selection, new Listener() {
              public void handleEvent(final Event e) {
                menu_item_open_view.notifyListeners(SWT.Selection, e);
              }
            });
        */

        /*
        final ToolItem item_open_graph = new ToolItem(toolbar, SWT.PUSH);
        item_open_graph.setImage(new Image(display, "pictures/oscilloscope-af.png"));
        item_open_graph.setToolTipText("open graph");
        item_open_graph.addListener(SWT.Selection, new Listener() {
          public void handleEvent(final Event e) {
            menu_item_open_graph.notifyListeners(SWT.Selection, e);
          }
        });
                
        final ToolItem item_close_view = new ToolItem(toolbar, SWT.PUSH);
        item_close_view.setImage(new Image(display, "pictures/multirow-af-cross.png"));
        item_close_view.setToolTipText("close view");
        item_close_view.addListener(SWT.Selection, new Listener() {
          public void handleEvent(final Event e) {
            menu_item_close_view.notifyListeners(SWT.Selection, e);
          }
        });
        */

        new ToolItem(toolbar, SWT.SEPARATOR);

        ToolItem item_about = new ToolItem(toolbar, SWT.PUSH);
        item_about.setImage(new Image(display, "pictures/info.png"));
        item_about.setToolTipText(getConfig().getString("help"));
        item_about.addListener(SWT.Selection, new Listener() {
            public void handleEvent(final Event e) {
                menu_item_about.notifyListeners(SWT.Selection, e);
            }
        });

        // GridData
        toolbar_grid_data = new GridData(GridData.FILL_HORIZONTAL);
        toolbar.setLayoutData(toolbar_grid_data);

        // vertical Sash for Composite and text console
        vertical_sash = new SashForm(shell, SWT.VERTICAL);
        vertical_sash_grid_data = new GridData(GridData.FILL_BOTH);
        vertical_sash.setLayoutData(vertical_sash_grid_data);
        // vertical_sash.setBackground(display.getSystemColor(SWT.COLOR_RED));

        // horizontal Composite
        horizontal_composite = new Composite(vertical_sash, SWT.FLAT);
        // composite.setBackground(display.getSystemColor(SWT.COLOR_RED));
        horizontal_composite_layout = new GridLayout();
        horizontal_composite_layout.numColumns = 2;
        horizontal_composite_layout.marginHeight = 0;
        horizontal_composite_layout.marginWidth = 0;
        horizontal_composite.setLayout(horizontal_composite_layout);

        // text console
        text_console = new Browser(vertical_sash, SWT.BORDER | SWT.FILL);
        appendConsole(htmlFace("GNetWatch - &copy; 2006, 2007, 2008<BR/>"));
        text_console.addProgressListener(new ProgressListener() {
            public void changed(ProgressEvent e) {
            }

            public void completed(ProgressEvent e) {
                // il faudrait mettre une valeur max plutt que a...
                if (text_console_do_not_go_on_top > 0)
                    text_console_do_not_go_on_top--;
                else
                    text_console.execute("window.scroll(0,1000000);");
            }
        });

        // set vertical_sash relative weights
        vertical_sash.setWeights(new int[] { 4, 1 });

        // Composite for groups at left
        groups_composite = new Composite(horizontal_composite, SWT.FLAT);
        groups_composite_layout = new RowLayout(SWT.VERTICAL);
        groups_composite_layout.fill = true;
        groups_composite_layout.marginTop = 0;
        groups_composite_layout.marginBottom = 0;
        groups_composite.setLayout(groups_composite_layout);
        groups_composite_grid_data = new GridData(GridData.FILL_VERTICAL);
        groups_composite.setLayoutData(groups_composite_grid_data);

        // Group for subnet targets

        group_target_subnet = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_target_subnet_layout = new GridLayout();
        group_target_subnet_layout.numColumns = 2;
        group_target_subnet.setLayout(group_target_subnet_layout);
        group_target_subnet.setText(getConfig().getString("create_network_target"));

        label1 = new Label(group_target_subnet, SWT.SHADOW_IN);
        label1.setText(getConfig().getString("address"));
        label1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_subnet_address = new Text(group_target_subnet, SWT.READ_ONLY | SWT.SINGLE);
        target_subnet_address.setLayoutData(new GridData(
                GridData.HORIZONTAL_ALIGN_END /*| GridData.GRAB_HORIZONTAL*/ | GridData.FILL_VERTICAL));
        target_subnet_address.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_subnet_address.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
        new IpAddressEditor(getConfig(), target_subnet_address);

        label2 = new Label(group_target_subnet, SWT.SHADOW_IN);
        label2.setText(getConfig().getString("netmask"));
        label2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_subnet_mask = new Text(group_target_subnet, SWT.READ_ONLY | SWT.SINGLE);
        target_subnet_mask.setLayoutData(new GridData(
                GridData.HORIZONTAL_ALIGN_END /*| GridData.GRAB_HORIZONTAL*/ | GridData.FILL_VERTICAL));
        target_subnet_mask.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_subnet_mask.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_subnet_mask.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
        new IpAddressEditor(getConfig(), target_subnet_mask);

        new Label(group_target_subnet, SWT.SHADOW_NONE);

        target_subnet_push = new Button(group_target_subnet, SWT.PUSH);
        target_subnet_push.setText(getConfig().getString("add_subnet"));
        target_subnet_push.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        target_subnet_push.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            addTargetAtCurrentPosition(new TargetIPv4Subnet("added by GUI",
                                    GenericTools.stringToInet4Address(target_subnet_address.getText()),
                                    GenericTools.stringToInet4Address(target_subnet_mask.getText())));
                            target_subnet_address.setText("000.000.000.000");
                            target_subnet_mask.setText("000.000.000.000");
                            session.getTransaction().commit();
                        } catch (final UnknownHostException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        } catch (final AlgorithmException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                            System.exit(1);
                        }
                    }
                }
            }

            public void widgetSelected(SelectionEvent e) {
                widgetDefaultSelected(e);
            }
        });

        // Group for range targets

        group_target_range = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_target_range_layout = new GridLayout();
        group_target_range_layout.numColumns = 2;
        group_target_range.setLayout(group_target_range_layout);
        group_target_range.setText(getConfig().getString("create_range_target"));

        label3 = new Label(group_target_range, SWT.SHADOW_IN);
        label3.setText(getConfig().getString("first_address"));
        label3.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_range_begin = new Text(group_target_range, SWT.READ_ONLY | SWT.SINGLE);
        target_range_begin.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_VERTICAL));
        target_range_begin.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_range_begin.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
        new IpAddressEditor(getConfig(), target_range_begin);

        label4 = new Label(group_target_range, SWT.SHADOW_IN);
        label4.setText(getConfig().getString("last_address"));
        label4.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_range_end = new Text(group_target_range, SWT.READ_ONLY | SWT.SINGLE);
        target_range_end.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_VERTICAL));
        target_range_end.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_range_end.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
        new IpAddressEditor(getConfig(), target_range_end);

        new Label(group_target_range, SWT.SHADOW_NONE);

        target_range_push = new Button(group_target_range, SWT.PUSH);
        target_range_push.setText(getConfig().getString("add_range"));
        target_range_push.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        target_range_push.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            addTargetAtCurrentPosition(new TargetIPv4Range("added by GUI",
                                    GenericTools.stringToInet4Address(target_range_begin.getText()),
                                    GenericTools.stringToInet4Address(target_range_end.getText())));
                            target_range_begin.setText("000.000.000.000");
                            target_range_end.setText("000.000.000.000");
                            session.getTransaction().commit();
                        } catch (final UnknownHostException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        } catch (final AlgorithmException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                            System.exit(1);
                        }
                    }
                }
            }

            public void widgetSelected(SelectionEvent e) {
                widgetDefaultSelected(e);
            }
        });

        // Group for host targets

        group_target_host = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_target_host_layout = new GridLayout();
        group_target_host_layout.numColumns = 2;
        group_target_host.setLayout(group_target_host_layout);
        group_target_host.setText(getConfig().getString("create_ipv4_target"));

        label5 = new Label(group_target_host, SWT.SHADOW_IN);
        label5.setText(getConfig().getString("host_address"));
        label5.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_host_value = new Text(group_target_host, SWT.READ_ONLY | SWT.SINGLE);
        target_host_value.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_VERTICAL));
        target_host_value.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_host_value.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
        new IpAddressEditor(getConfig(), target_host_value);

        new Label(group_target_host, SWT.SHADOW_NONE);

        target_host_push = new Button(group_target_host, SWT.PUSH);
        target_host_push.setText(getConfig().getString("add_ipv4_host"));
        target_host_push.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        target_host_push.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                synchronized (synchro) {
                    synchronized (sync_tree) {
                        final Session session = synchro.getSessionFactory().getCurrentSession();
                        session.beginTransaction();
                        try {
                            final TargetIPv4 foo = new TargetIPv4("added by GUI",
                                    GenericTools.stringToInet4Address(target_host_value.getText()),
                                    snmp_manager);
                            if (addTargetAtCurrentPosition(foo) == true)
                                foo.checkSNMPAwareness();
                            target_host_value.setText("000.000.000.000");
                            session.getTransaction().commit();
                        } catch (final UnknownHostException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                        } catch (final AlgorithmException ex) {
                            log.error("Exception", ex);
                            session.getTransaction().rollback();
                            System.exit(1);
                        }
                    }
                }
            }

            public void widgetSelected(SelectionEvent e) {
                widgetDefaultSelected(e);
            }
        });

        target_host_push.addControlListener(new ControlListener() {
            public void controlMoved(final ControlEvent e) {
            }

            public void controlResized(final ControlEvent e) {
                final GC gc = new GC(target_host_value);
                gc.setFont(target_host_value.getFont());
                ((GridData) (target_group_value.getLayoutData())).widthHint = gc
                        .stringExtent(target_host_value.getText()).x;
                ((GridData) (target_host6_value.getLayoutData())).widthHint = gc
                        .stringExtent(target_host_value.getText()).x;
                shell.changed(new Control[] { target_group_value, target_host6_value });
            }
        });

        // Group for IPv6 targets

        group_target_host6 = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_target_host6_layout = new GridLayout();
        group_target_host6_layout.numColumns = 2;
        group_target_host6.setLayout(group_target_host6_layout);
        group_target_host6.setText(getConfig().getString("create_ipv6_target"));

        label7 = new Label(group_target_host6, SWT.SHADOW_IN);
        label7.setText(getConfig().getString("ipv6_address"));
        label7.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_host6_value = new Text(group_target_host6, SWT.SINGLE);
        target_host6_value.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_VERTICAL));
        target_host6_value.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_host6_value.setForeground(display.getSystemColor(SWT.COLOR_WHITE));

        new Label(group_target_host6, SWT.SHADOW_NONE);

        target_host6_push = new Button(group_target_host6, SWT.PUSH);
        target_host6_push.setText(getConfig().getString("add_ipv6_host"));
        target_host6_push.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        target_host6_push.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                try {
                    final Inet6Address address = GenericTools
                            .stringToInet6Address(target_host6_value.getText());
                    if (address == null) {
                        final MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                        dialog.setText(getConfig().getString("gnetwatch_error"));
                        dialog.setMessage(getConfig().getString("cannot_parse_ipv6"));
                        dialog.open();
                        return;
                    }
                    synchronized (synchro) {
                        synchronized (sync_tree) {
                            final Session session = synchro.getSessionFactory().getCurrentSession();
                            session.beginTransaction();
                            try {
                                final TargetIPv6 foo = new TargetIPv6("added by GUI", address, snmp_manager);
                                if (addTargetAtCurrentPosition(foo) == true)
                                    foo.checkSNMPAwareness();
                                target_host6_value.setText("");
                                session.getTransaction().commit();
                            } catch (Exception ex) {
                                session.getTransaction().rollback();
                                throw ex;
                            }
                        }
                    }
                } catch (final UnknownHostException ex) {
                    log.error("Exception", ex);
                    final MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                    dialog.setText("GNetWatch - Error");
                    dialog.setMessage(getConfig().getString("cannot_parse_ipv6"));
                    dialog.open();
                } catch (final AlgorithmException ex) {
                    log.error("Exception", ex);
                    System.exit(1);
                } catch (final Exception ex) {
                    log.error("Exception", ex);
                }
            }

            public void widgetSelected(final SelectionEvent e) {
                widgetDefaultSelected(e);
            }
        });

        // Group for group targets

        group_target_group = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_target_group_layout = new GridLayout();
        group_target_group_layout.numColumns = 2;
        group_target_group.setLayout(group_target_group_layout);
        group_target_group.setText(getConfig().getString("create_group_target"));

        label6 = new Label(group_target_group, SWT.SHADOW_IN);
        label6.setText(getConfig().getString("group_name"));
        label6.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        target_group_value = new Text(group_target_group, SWT.SINGLE);
        target_group_value.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END | GridData.FILL_VERTICAL));
        target_group_value.setBackground(new Color(display, bglevel, bglevel, bglevel));
        target_group_value.setForeground(display.getSystemColor(SWT.COLOR_WHITE));

        new Label(group_target_group, SWT.SHADOW_NONE);

        target_group_push = new Button(group_target_group, SWT.PUSH);
        target_group_push.setText(getConfig().getString("add_group"));
        target_group_push.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
        target_group_push.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                try {
                    if (target_group_value.getText() != "")
                        synchronized (synchro) {
                            synchronized (sync_tree) {
                                final Session session = synchro.getSessionFactory().getCurrentSession();
                                session.beginTransaction();
                                try {
                                    addTargetAtCurrentPosition(
                                            new TargetGroup("added by GUI", target_group_value.getText()));
                                    session.getTransaction().commit();
                                } catch (Exception ex) {
                                    session.getTransaction().rollback();
                                    throw ex;
                                }
                            }
                        }
                    else {
                        final MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                        dialog.setText(getConfig().getString("gnetwatch_error"));
                        dialog.setMessage(getConfig().getString("cannot_add_group"));
                        dialog.open();
                    }
                    target_group_value.setText("");
                } catch (final AlgorithmException ex) {
                    log.error("Exception", ex);
                    System.exit(1);
                } catch (final Exception ex) {
                    log.error("Exception", ex);
                }
            }

            public void widgetSelected(final SelectionEvent e) {
                widgetDefaultSelected(e);
            }
        });

        // vertical space (hint to be sure left groups are visible at launch time)
        new Label(groups_composite, SWT.SHADOW_ETCHED_IN);

        // group container for data

        /*
        group_data = new Group(groups_composite, SWT.SHADOW_ETCHED_IN);
        group_data.setText("Data");
        group_data_layout = new GridLayout();
        group_data_layout.numColumns = 2;
        group_data.setLayout(group_target_subnet_layout);
        */

        // Sash for Tree and Label
        horizontal_sash = new SashForm(horizontal_composite, SWT.HORIZONTAL);
        horizontal_sash_grid_data = new GridData(GridData.FILL_BOTH);
        horizontal_sash.setLayoutData(horizontal_sash_grid_data);

        // Tree
        tree = new Tree(horizontal_sash, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
        tree.addSelectionListener(new SelectionListener() {
            public void widgetDefaultSelected(SelectionEvent e) {
                if (tree.getSelectionCount() == 1) {
                    TreeItem current_item = tree.getSelection()[0];
                    if (current_item != null) {
                        synchronized (synchro) {
                            synchronized (sync_tree) {
                                final VisualElement visual_element = (VisualElement) current_item
                                        .getData(VisualElement.class.toString());
                                if (visual_element != null)
                                    visual_element.informSelected();
                            }
                        }
                        widgetSelected(e);
                    }
                }
            }

            public void widgetSelected(SelectionEvent e) {
                gui.updateEnableState();
                if (tree.getSelectionCount() == 1) {
                    TreeItem current_item = tree.getSelection()[0];
                    if (current_item != null) {
                        synchronized (sync_tree) {
                            final VisualElement visual_element = (VisualElement) current_item
                                    .getData(VisualElement.class.toString());

                            if (visual_element.getProgress() != -1)
                                setProgress(visual_element.getProgress());

                            if (previous_selection != null)
                                previous_selection.unselected();
                            visual_element.selected();
                            previous_selection = visual_element;

                            setEnableMenuItemOptions(TargetIPv4.class.isInstance(visual_element)
                                    || TargetIPv6.class.isInstance(visual_element));

                            if (ActionFlood.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_action.setEnabled(true);
                                item_remove_action.setEnabled(true);
                                menu_item_remove_action_flood.setEnabled(true);
                            } else if (ActionPing.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_action.setEnabled(true);
                                item_remove_action.setEnabled(true);
                                menu_item_remove_action_ping.setEnabled(true);
                            } else if (ActionSNMP.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_action.setEnabled(true);
                                item_remove_action.setEnabled(true);
                                menu_item_remove_action_explore.setEnabled(true);
                            } else if (ActionHTTP.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_action.setEnabled(true);
                                item_remove_action.setEnabled(true);
                            } else if (ActionNmap.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_action.setEnabled(true);
                                item_remove_action.setEnabled(true);
                            } else if (ReachableView.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_target.setEnabled(true);
                                item_remove_target.setEnabled(true);
                                menu_item_remove_view.setEnabled(true);
                                menu_item_remove_view_ping.setEnabled(true);
                            } else if (FloodView.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_target.setEnabled(true);
                                item_remove_target.setEnabled(true);
                                menu_item_remove_view.setEnabled(true);
                                menu_item_remove_view_flood.setEnabled(true);
                            } else if (HTTPView.class.isInstance(visual_element)
                                    || HTTPPagesView.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_target.setEnabled(true);
                                item_remove_target.setEnabled(true);
                                menu_item_remove_view.setEnabled(true);
                            } else if (BytesReceivedView.class.isInstance(visual_element)
                                    || BytesSentView.class.isInstance(visual_element)) {
                                setEnableMenuAndTool(false);
                                menu_item_remove_target.setEnabled(true);
                                item_remove_target.setEnabled(true);
                                menu_item_remove_view.setEnabled(true);
                                menu_item_remove_view_explore.setEnabled(true);
                            } else {
                                // visual_element is neither a view nor an action
                                setEnableMenuAndTool(true);

                                if (visual_element.getChildren().size() == 0) {
                                    // no children
                                    menu_item_remove_action.setEnabled(false);
                                    item_remove_action.setEnabled(false);
                                    menu_item_remove_action_ping.setEnabled(false);
                                    menu_item_remove_action_flood.setEnabled(false);
                                    menu_item_remove_action_explore.setEnabled(false);
                                    menu_item_remove_view.setEnabled(false);
                                    menu_item_remove_view_ping.setEnabled(false);
                                    menu_item_remove_view_flood.setEnabled(false);
                                    menu_item_remove_view_explore.setEnabled(false);
                                }
                            }

                            if (net.fenyo.gnetwatch.actions.Action.class.isInstance(visual_element)) {
                                setEnableGroupTargetSubnet(false);
                                setEnableGroupTargetRange(false);
                                setEnableGroupTargetHost(false);
                                setEnableGroupTargetGroup(false);
                            } else if (Target.class.isInstance(visual_element)) {
                                try {
                                    boolean foo;

                                    final TargetGroup target_group = new TargetGroup("", "");
                                    target_group.initialize(gui);
                                    foo = target_group.canAddTarget(visual_element)
                                            && visual_element.canManageThisChild(target_group);
                                    setEnableGroupTargetGroup(foo);

                                    // No name service is checked for the validity of the address.
                                    final Inet4Address bar = (Inet4Address) Inet4Address.getByAddress("bar",
                                            new byte[] { 0, 0, 0, 0 });

                                    final TargetIPv4 target_ipv4 = new TargetIPv4("", bar, null);
                                    target_ipv4.initialize(gui);
                                    foo = target_ipv4.canAddTarget(visual_element)
                                            && visual_element.canManageThisChild(target_ipv4);
                                    setEnableGroupTargetHost(foo);

                                    final TargetIPv4Range target_ipv4_range = new TargetIPv4Range("", bar, bar);
                                    target_ipv4_range.initialize(gui);
                                    foo = target_ipv4_range.canAddTarget(visual_element)
                                            && visual_element.canManageThisChild(target_ipv4_range);
                                    setEnableGroupTargetRange(foo);

                                    final TargetIPv4Subnet target_ipv4_subnet = new TargetIPv4Subnet("", bar,
                                            bar);
                                    target_ipv4_subnet.initialize(gui);
                                    foo = target_ipv4_subnet.canAddTarget(visual_element)
                                            && visual_element.canManageThisChild(target_ipv4_subnet);
                                    setEnableGroupTargetSubnet(foo);
                                } catch (final AlgorithmException ex) {
                                    log.error("Exception", ex);
                                } catch (final UnknownHostException ex) {
                                    log.error("Exception", ex);
                                }
                            } else if (net.fenyo.gnetwatch.activities.Queue.class.isInstance(visual_element)) {
                                setEnableGroupTargetSubnet(false);
                                setEnableGroupTargetRange(false);
                                setEnableGroupTargetHost(false);
                                setEnableGroupTargetGroup(false);
                            } else if (DataView.class.isInstance(visual_element)) {
                                setEnableGroupTargetSubnet(false);
                                setEnableGroupTargetRange(false);
                                setEnableGroupTargetHost(false);
                                setEnableGroupTargetGroup(false);
                            } else if (visual_element.equals(visual_transient)) {
                                setEnableGroupTargetSubnet(false);
                                setEnableGroupTargetRange(false);
                                setEnableGroupTargetHost(false);
                                setEnableGroupTargetGroup(false);
                            } else {
                                setEnableGroupTargetSubnet(false);
                                setEnableGroupTargetRange(false);
                                setEnableGroupTargetHost(false);
                                setEnableGroupTargetGroup(false);
                            }
                        }
                    }
                }

            }
        });
        tree.setHeaderVisible(true);
        tree_column1 = new TreeColumn(tree, SWT.LEFT);
        tree_column1.setText(getConfig().getString("items"));
        tree_column1.setWidth(150);
        tree_column2 = new TreeColumn(tree, SWT.LEFT);
        tree_column2.setText("Type");
        tree_column2.setWidth(80);
        tree_column3 = new TreeColumn(tree, SWT.RIGHT);
        tree_column3.setText("Description");
        tree_column3.setWidth(100);

        // Tree images
        image_folder = new Image(display, "pictures/folder_violet.png");
        image_oscillo = new Image(display, "pictures/oscilloscope-af.png");
        image_multirow = new Image(display, "pictures/multirow.png");
        image_exec = new Image(display, "pictures/exec.png");
        image_watch = new Image(display, "pictures/yahoo_idle-af.png");
        image_host = new Image(display, "pictures/network_local.png");
        image_host6 = new Image(display, "pictures/network_local-6-af.png");
        image_interface = new Image(display, "pictures/memory.png");
        image_queue = new Image(display, "pictures/jabber_group.png");
        image_network = new Image(display, "pictures/network.png");
        image_host_snmp = new Image(display, "pictures/network_local_snmp.png");
        image_host6_snmp = new Image(display, "pictures/network_local-6-af-snmp.png");

        visual_root = new VisualElement();
        visual_root.setParent(this, tree);
        visual_root.setItem(config.getString("collected_data"));

        visual_queues = new VisualElement();
        visual_queues.setParent(this, tree);
        visual_queues.setItem(config.getString("queues"));

    } // release sync_tree

    // create initial objects only if they do not exist in the database
    synchronized (synchro) {
        synchronized (sync_tree) {
            final Session session = synchro.getSessionFactory().getCurrentSession();
            try {
                session.beginTransaction();
            } catch (final org.hibernate.exception.JDBCConnectionException ex) {
                // c'est ici que a se termine quand on ouvre deux fois sur la mme database maintenue par un fichier par HSQLDB
                final MessageBox dialog = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                //  traduire
                dialog.setText("GNetWatch Fatal Error");
                dialog.setMessage(ex.toString() + " - caused by: " + ex.getCause().toString());
                dialog.open();
                session.getTransaction().rollback();
                System.exit(0);
            }

            try {

                final java.util.List results = session.createQuery("from VisualElement as el where el.item = ?")
                        .setString(0, config.getString("targets")).list();
                if (results.size() > 1)
                    log.error("database contains multiple root targets");

                if (results.size() > 0) {
                    visual_transient = (VisualElement) results.get(0);
                    visual_transient.initialize(this);
                    visual_transient.duplicateTreeItemOnce(visual_root.getTreeItems());
                    visual_transient.addParent(visual_root);

                    // recursive initialization of every visual element stored in the database
                    initFromSynchro(visual_transient);

                } else {

                    visual_transient = new VisualElement();
                    visual_transient.setParent(this, visual_root);
                    visual_transient.setItem(config.getString("targets"));
                    session.save(visual_transient);
                }

                for (final VisualElement foo : visual_transient.getChildren()) {
                    if (foo.getItem().equals(config.getString("local_host")))
                        visual_thishost = (TargetGroup) foo;
                    if (foo.getItem().equals(config.getString("every_host")))
                        visual_transient_all = (TargetGroup) foo;
                    if (foo.getItem().equals(config.getString("every_network")))
                        visual_transient_networks = (TargetGroup) foo;
                    if (foo.getItem().equals(config.getString("user_defined")))
                        user_defined = (TargetGroup) foo;
                }

                if (visual_thishost == null) {
                    visual_thishost = new TargetGroup("added by GUI", config.getString("local_host"));
                    visual_thishost.setParent(this, visual_transient);
                    session.save(visual_thishost);
                }

                if (visual_transient_all == null) {
                    visual_transient_all = new TargetGroup("added by GUI", config.getString("every_host"));
                    visual_transient_all.setParent(this, visual_transient);
                    session.save(visual_transient_all);
                }

                if (getConfig().getProperty("enableeverynetworks") != null
                        && getConfig().getProperty("enableeverynetworks").equals("true")) {

                    if (visual_transient_networks == null) {
                        visual_transient_networks = new TargetGroup("added by GUI",
                                config.getString("every_network"));
                        visual_transient_networks.setParent(this, visual_transient);
                        session.save(visual_transient_networks);
                    }

                }

                if (user_defined == null) {
                    user_defined = new TargetGroup("added by GUI", config.getString("user_defined"));
                    user_defined.setParent(this, visual_transient);
                    session.save(user_defined);
                }

                // create localhost
                for (final Enumeration nifs = NetworkInterface.getNetworkInterfaces(); nifs
                        .hasMoreElements();) {
                    final NetworkInterface nif = (NetworkInterface) nifs.nextElement();
                    for (final Enumeration addrs = nif.getInetAddresses(); addrs.hasMoreElements();) {
                        final InetAddress addr = (InetAddress) addrs.nextElement();

                        // localhost has IPv4 addresses
                        if (Inet4Address.class.isInstance(addr)) {
                            final TargetIPv4 foo = new TargetIPv4("transient localhost", (Inet4Address) addr,
                                    snmp_manager);
                            if (foo == getCanonicalInstance(foo)) {
                                session.save(foo);
                                if (foo.addTarget(this, visual_thishost) == true)
                                    foo.checkSNMPAwareness();
                            }
                        }

                        // localhost has IPv6 addresses
                        if (Inet6Address.class.isInstance(addr)) {
                            final TargetIPv6 foo = new TargetIPv6("transient localhost", (Inet6Address) addr,
                                    snmp_manager);
                            if (foo == getCanonicalInstance(foo)) {
                                session.save(foo);
                                if (foo.addTarget(this, visual_thishost) == true)
                                    foo.checkSNMPAwareness();
                            }
                        }
                    }

                    // recursively initialize SNMPQuerier instances
                    initSNMPQueriers(visual_transient);

                    // recursively wakeup actions
                    wakeupActions(visual_transient);
                }

                session.getTransaction().commit();
            } catch (final Exception ex) {
                log.error("Exception", ex);
            }
        }
    }

    synchronized (sync_tree) {

        // CTabFolder
        tab_folder = new CTabFolder(horizontal_sash, SWT.BORDER);
        tab_folder.setSimple(false);

        tab_item1 = new CTabItem(tab_folder, SWT.None);
        tab_item1.setText(getConfig().getString("about_the_author"));
        final Browser browser = new Browser(tab_folder, SWT.BORDER | SWT.MULTI);
        browser.setUrl("http://www.fenyo.net");
        //   browser.setText("<HTML><BODY BGCOLOR='red'><H1>Data</H1>target: <B>127.0.0.1</B></BODY></HTML>");
        tab_item1.setControl(browser);

        tab_item2 = new CTabItem(tab_folder, SWT.None);
        tab_item2.setText("Documentation");
        final Browser browser2 = new Browser(tab_folder, SWT.BORDER | SWT.MULTI);
        browser2.setUrl("http://gnetwatch.sourceforge.net/docs");
        tab_item2.setControl(browser2);

        // StyledText
        status = new StyledText(shell, SWT.BORDER);
        status_grid_data = new GridData(GridData.FILL_HORIZONTAL);
        status.setLayoutData(status_grid_data);
        status.setEditable(false);
        status.setEnabled(false);
        status.setText("Loading...");
        status.setBackground(shell.getBackground());

        // ProgressBar
        progress_bar = new ProgressBar(shell, SWT.SMOOTH);
        progress_bar.setBounds(10, 10, 200, 32);
        progress_bar.setSelection(0);
        progress_bar_grid_data = new GridData(GridData.FILL_HORIZONTAL);
        progress_bar.setLayoutData(progress_bar_grid_data);

        // instanciate queues

        final String[] queue_names = background.getQueues().keySet().toArray(new String[] {});
        Arrays.sort(queue_names);
        for (final String queue_name : queue_names)
            background.getQueues().get(queue_name).setParent(this, visual_queues);

        // set initial selections
        menu_item_credentials.setEnabled(false);
        menu_item_ip_options.setEnabled(false);
        menu_item_http_options.setEnabled(false);
        setEnableGroupTargetSubnet(false);
        setEnableGroupTargetRange(false);
        setEnableGroupTargetHost(false);
        setEnableGroupTargetGroup(false);

    } // release sync_tree

    tree.setBackground(getBackgroundColor());

    // display documentation at startup
    tab_folder.setSelection(tab_item2);

    // final operations
    shell.pack();
    shell.open();

    visual_root.expandTreeItems(true);
    visual_queues.expandTreeItems(true);
    visual_transient.expandTreeItems(true);
    tree.setSelection(visual_root.getTreeItems().get(0));
    tree.setFocus();

    synchronized (GUI_created) {
        GUI_created[0] = true;
        GUI_created.notifyAll();
    }

    // list network interfaces at startup
    text_console_do_not_go_on_top = 1;
    appendNetworkInterfaces();

    awtGUI = new AwtGUI(config);
    awtGUI.createAwtGUI();
}

From source file:com.ah.be.admin.restoredb.RestoreAdmin.java

private static String getEth0Ip() throws SocketException, UnknownHostException {
    String eth0Ip = null;/*from  www . ja  v  a  2 s  .  c o  m*/

    overloop: for (Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
            .getNetworkInterfaces(); networkInterfaces.hasMoreElements();) {
        NetworkInterface networkInterface = networkInterfaces.nextElement();
        String networkInterfaceName = networkInterface.getName();

        if ("eth0".equalsIgnoreCase(networkInterfaceName)) {
            Enumeration<InetAddress> eth0Addresses = networkInterface.getInetAddresses();

            while (eth0Addresses.hasMoreElements()) {
                InetAddress eth0Address = eth0Addresses.nextElement();

                if (eth0Address instanceof Inet4Address) {
                    eth0Ip = eth0Address.getHostAddress();
                    break overloop;
                }
            }
        }
    }

    if (eth0Ip == null) {
        InetAddress localAddress = InetAddress.getLocalHost();

        if (localAddress instanceof Inet4Address) {
            eth0Ip = localAddress.getHostAddress();
        }
    }

    return eth0Ip;
}