Example usage for java.net InetAddress isAnyLocalAddress

List of usage examples for java.net InetAddress isAnyLocalAddress

Introduction

In this page you can find the example usage for java.net InetAddress isAnyLocalAddress.

Prototype

public boolean isAnyLocalAddress() 

Source Link

Document

Utility routine to check if the InetAddress is a wildcard address.

Usage

From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java

/**
 * Constructs a new instance of this class.
 *//*from   w  ww .  j  ava 2 s  . co m*/
private SsdpHandler() {
    LOG.info("Instantiating SsdpHandler");

    try {
        // Use first IPv4 address that isn't loopback, any, or link local as the server address
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements() && serverAddress == null) {
            NetworkInterface i = interfaces.nextElement();
            Enumeration<InetAddress> addresses = i.getInetAddresses();
            while (addresses.hasMoreElements() && serverAddress == null) {
                InetAddress address = addresses.nextElement();
                if (address instanceof Inet4Address) {
                    if (!address.isAnyLocalAddress() && !address.isLinkLocalAddress()
                            && !address.isLoopbackAddress() && !address.isMulticastAddress()) {
                        serverAddress = address;
                    }
                }
            }
        }

        if (serverAddress == null) {
            LOG.warn("Server address unknown");
        }

        svc = SsdpService.forAllMulticastAvailableNetworkInterfaces(this);
        svc.listen();

        // setup Multicast for Notify messages
        notifySocket = new MulticastSocket();
        notifySocket.setTimeToLive(TTL);
        notifyTimer = new Timer("UPnP Notify Timer", true);
        notifyTimer.scheduleAtFixedRate(new NotifySender(), 5000, MAX_AGE * 1000 / 2);
    } catch (Exception e) {
        LOG.error("SsdpHandler in unknown state due to exception in constructor.", e);
    }
}

From source file:org.apache.hadoop.hdfs.qjournal.server.JournalNodeJournalSyncer.java

/**
 * Checks if the address is local./*  w w w. j a v  a 2  s .c  o  m*/
 */
private boolean isLocalIpAddress(InetAddress addr) {
    if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
        return true;
    try {
        return NetworkInterface.getByInetAddress(addr) != null;
    } catch (SocketException e) {
        return false;
    }
}

From source file:org.cruxframework.crux.tools.codeserver.CodeServer.java

protected void processParameters(Collection<ConsoleParameter> parameters) {
    for (ConsoleParameter parameter : parameters) {
        if (parameter.getName().equals("-moduleName")) {
            moduleName = parameter.getValue();
        } else if (parameter.getName().equals("-noprecompile")) {
            this.noPrecompile = true;
        } else if (parameter.getName().equals("-startHotDeploymentScanner")) {
            this.startHotDeploymentScanner = true;
        } else if (parameter.getName().equals("-startJetty")) {
            this.startJetty = true;
        } else if (parameter.getName().equals("-userAgent")) {
            userAgent = parameter.getValue();
        } else if (parameter.getName().equals("-locale")) {
            locale = parameter.getValue();
        } else if (parameter.getName().equals("-sourceDir")) {
            sourceDir = parameter.getValue();
        } else if (parameter.getName().equals("-bindAddress")) {
            try {
                InetAddress bindAddress = InetAddress.getByName(parameter.getValue());
                if (bindAddress.isAnyLocalAddress()) {
                    this.bindAddress = InetAddress.getLocalHost().getHostAddress();
                } else {
                    this.bindAddress = parameter.getValue();
                }/*from  ww  w . jav a  2s.  c om*/
            } catch (Exception e) {
                //Use default
            }
        } else if (parameter.getName().equals("-port")) {
            port = Integer.parseInt(parameter.getValue());
        } else if (parameter.getName().equals("-notificationServerPort")) {
            notificationServerPort = Integer.parseInt(parameter.getValue());
        } else if (parameter.getName().equals("-workDir")) {
            workDir = parameter.getValue();
        } else if (parameter.getName().equals("-webDir")) {
            webDir = parameter.getValue();
        }
    }
}

From source file:com.cloud.storage.template.HttpTemplateDownloader.java

private Pair<String, Integer> validateUrl(String url) throws IllegalArgumentException {
    try {/*  w w  w .jav a  2 s  .c o m*/
        URI uri = new URI(url);
        if (!uri.getScheme().equalsIgnoreCase("http") && !uri.getScheme().equalsIgnoreCase("https")) {
            throw new IllegalArgumentException("Unsupported scheme for url");
        }
        int port = uri.getPort();
        if (!(port == 80 || port == 443 || port == -1)) {
            throw new IllegalArgumentException("Only ports 80 and 443 are allowed");
        }

        if (port == -1 && uri.getScheme().equalsIgnoreCase("https")) {
            port = 443;
        } else if (port == -1 && uri.getScheme().equalsIgnoreCase("http")) {
            port = 80;
        }

        String host = uri.getHost();
        try {
            InetAddress hostAddr = InetAddress.getByName(host);
            if (hostAddr.isAnyLocalAddress() || hostAddr.isLinkLocalAddress() || hostAddr.isLoopbackAddress()
                    || hostAddr.isMulticastAddress()) {
                throw new IllegalArgumentException("Illegal host specified in url");
            }
            if (hostAddr instanceof Inet6Address) {
                throw new IllegalArgumentException(
                        "IPV6 addresses not supported (" + hostAddr.getHostAddress() + ")");
            }
            return new Pair<String, Integer>(host, port);
        } catch (UnknownHostException uhe) {
            throw new IllegalArgumentException("Unable to resolve " + host);
        }
    } catch (IllegalArgumentException iae) {
        s_logger.warn("Failed uri validation check: " + iae.getMessage());
        throw iae;
    } catch (URISyntaxException use) {
        s_logger.warn("Failed uri syntax check: " + use.getMessage());
        throw new IllegalArgumentException(use.getMessage());
    }
}

From source file:org.apache.pig.shock.SSHSocketImplFactory.java

@Override
protected void bind(InetAddress host, int port) throws IOException {
    if ((host != null && !host.isAnyLocalAddress()) || port != 0) {
        throw new IOException("SSHSocketImpl does not implement bind");
    }//  w  w w.  j  a  va 2  s . com
}

From source file:org.apache.servicemix.http.jetty.JettyContextManager.java

protected String getKey(URL url) {
    String host = url.getHost();/*w  ww.  j  a  va  2s . c  om*/
    try {
        InetAddress addr = InetAddress.getByName(host);
        if (addr.isAnyLocalAddress()) {
            host = InetAddress.getLocalHost().getHostName();
        }
    } catch (UnknownHostException e) {
        //unable to lookup host name, using IP address instead
    }
    return url.getProtocol() + "://" + host + ":" + url.getPort();
}

From source file:org.rhq.plugins.jbossas.JBossASDiscoveryComponent.java

private String getBindingHostname(String bindingAddress) {
    String bindingHostname = null;
    if (bindingAddress != null) {
        try {/* www . j  a v a2 s .  c o m*/
            InetAddress bindAddr = InetAddress.getByName(bindingAddress);
            if (!bindAddr.isAnyLocalAddress()) {
                //if the binding address != 0.0.0.0
                bindingHostname = bindAddr.getHostName();
            }
        } catch (UnknownHostException e) {
            //this should not happen?
            log.warn("Unknown hostname passed in as the binding address for JBoss AS instance: "
                    + bindingAddress);
        }
    }
    return bindingHostname;
}

From source file:org.rhq.plugins.jbossas5.ApplicationServerDiscoveryComponent.java

public String formatServerName(String bindingAddress, String jnpPort, String hostname, String configurationName,
        boolean isRhq) {

    if (isRhq) {/*from www.j a  va2  s.  co  m*/
        return hostname + " RHQ Server";
    } else {
        String hostnameToUse = hostname;

        if (bindingAddress != null) {
            try {
                InetAddress bindAddr = InetAddress.getByName(bindingAddress);
                if (!bindAddr.isAnyLocalAddress()) {
                    //if the binding address != 0.0.0.0
                    hostnameToUse = bindAddr.getHostName();
                }
            } catch (UnknownHostException e) {
                //this should not happen?
                log.warn("Unknown hostname passed in as the binding address for JBoss AS server discovery: "
                        + bindingAddress);
            }
        }

        if (jnpPort != null) {
            hostnameToUse += ":" + jnpPort;
        }

        return hostnameToUse + " " + configurationName;
    }
}

From source file:weinre.server.ServerSettings.java

@SuppressWarnings("unused")
private String getSuperNiceHostName() {
    String hostName = getBoundHost();

    // get the host address used
    InetAddress inetAddress;
    try {/*from  ww  w .  j a  v  a  2s  .c  o m*/
        inetAddress = InetAddress.getByName(hostName);
    } catch (UnknownHostException e) {
        Main.warn("Unable to get host address of " + hostName);
        return null;
    }

    // if it's "any local address", deal with that
    if (inetAddress.isAnyLocalAddress()) {
        try {
            InetAddress oneAddress = InetAddress.getLocalHost();
            return oneAddress.getHostName();
        } catch (UnknownHostException e) {
            Main.warn("Unable to get any local host address");
            return null;
        }
    }

    return inetAddress.getHostName();
}

From source file:edu.umd.lib.servlets.permissions.PermissionsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // explicitly set character encoding
    req.setCharacterEncoding("UTF-8");
    res.setCharacterEncoding("UTF-8");

    SimpleCredentials creds = BasicAuth.parseAuthorizationHeader(req);
    String credentialsId = creds.getUserID();
    log.debug("credentialsId={}", credentialsId);

    String jcrUserId = req.getParameter("jcrUserId");
    String jcrPath = req.getParameter("jcrPath");
    log.info("jcrUserId={}, jcrPath={}", jcrUserId, jcrPath);

    Session jcrSession = null;//from w  w  w. jav  a2  s.co  m
    Session impersonateSession = null;
    Map<String, Object> templateParams = new HashMap<String, Object>();

    try {
        if (creds.getUserID() == null || creds.getUserID().length() == 0) {
            jcrSession = repository.login();
        } else {
            jcrSession = repository.login(creds);
        }
        log.debug("jcrSession={}", jcrSession);
        User user = ((HippoSession) jcrSession).getUser();

        if (user.isSystemUser()) {
            final InetAddress address = InetAddress.getByName(req.getRemoteHost());
            if (!address.isAnyLocalAddress() && !address.isLoopbackAddress()) {
                throw new LoginException();
            }
        }

        templateParams.put("jcrSession", jcrSession);
        templateParams.put("jcrUserId", jcrUserId);
        templateParams.put("jcrPath", jcrPath);

        Credentials impersonateCredentials = new SimpleCredentials(jcrUserId, "".toCharArray());
        impersonateSession = jcrSession.impersonate(impersonateCredentials);
        Privilege[] privileges = getPrivileges(impersonateSession, jcrPath);
        log.info("========= " + ((SimpleCredentials) impersonateCredentials).getUserID() + " ==============");
        Map<String, String> privilegesMap = new HashMap<>();
        for (Privilege p : privileges) {
            privilegesMap.put(p.getName(), "true");
            log.info("p=" + p.getName());
        }
        templateParams.put("privilegesMap", privilegesMap);
        String[] allPermissions = { "jcr:read", "jcr:write", "hippo:author", "hippo:editor", "hippo:admin",
                "jcr:setProperties", "jcr:setAccessControlPolicy", "jcr:addChildNodes",
                "jcr:getAccessControlPolicy", "jcr:removeChildNodes" };

        templateParams.put("allPermissions", allPermissions);

    } catch (LoginException ex) {
        BasicAuth.setRequestAuthorizationHeaders(res, "Repository");
        log.error("Error logging in to repository", ex);
    } catch (Exception ex) {
        templateParams.put("exception", ex);
        log.error("Error retrieving permissions", ex);
    } finally {
        try {
            if (jcrSession != null) {
                renderTemplatePage(req, res, getRenderTemplate(req), templateParams);
            }
        } catch (Exception te) {
            log.warn("Failed to render freemarker template.", te);
        } finally {
            if (jcrSession != null) {
                jcrSession.logout();
            }

            if (impersonateSession != null) {
                impersonateSession.logout();
            }
        }
    }

}