Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

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

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.opentestsystem.shared.mna.client.service.AbstractMnaClient.java

/**
 * Get the base server, node, component info using system data if need be
 * /*from w ww  .j  av  a  2 s .com*/
 * @return MnaBase
 */
protected MnaBase getBaseInfo() {
    if (this.baseInfo == null) {
        try {
            final MnaBase temp = new MnaBase();
            if (StringUtils.isBlank(this.mnaNodeName)) {
                // if not injected, we will use the servlet context to derive the required values.
                String nodePath = this.servletContext.getRealPath("");
                if (nodePath != null) {
                    final String[] separated = nodePath.split("\\" + File.separator);
                    // using the context and deploy directory because you could have one server with 2 jvms running the same app.
                    if (separated.length > 2) {
                        nodePath = separated[separated.length - 2] + "_" + separated[separated.length - 1];
                    } else {
                        nodePath = separated[0];
                    }
                }
                temp.setNode(nodePath);
            } else {
                temp.setNode(this.mnaNodeName);
            }

            if (StringUtils.isBlank(this.mnaServerName)) {
                final InetAddress address = InetAddress.getLocalHost();
                final String host = address.getHostName();
                temp.setServer(host);
            } else {
                temp.setServer(this.mnaServerName);
            }

            String compName = this.servletContext.getServletContextName();
            if (compName != null) {
                compName = compName.replaceAll(" ", "_");
            }
            temp.setComponent(compName);

            this.baseInfo = temp;
        } catch (final UnknownHostException e) {
            LOGGER.error("cannot find localHost", e);
        }
    }

    return this.baseInfo;
}

From source file:com.microsoft.alm.plugin.idea.services.TelemetryContextInitializer.java

private String getComputerName() {
    String hostname = "Unknown";

    try {//from   www .j av  a2  s  .c om
        final InetAddress address = InetAddress.getLocalHost();
        hostname = address.getHostName();
    } catch (UnknownHostException ex) {
        // This case is covered by the initial value of hostname above
    }

    return hostname;
}

From source file:org.wso2.carbon.automation.extensions.servers.webserver.SimpleWebServer.java

public void run() {
    ServerSocket serverSocket = null;
    Socket connectionSocket = null;
    try {/*ww w . j  a va  2 s.  c  o  m*/
        log.info("Trying to bind to localhost on port " + Integer.toString(port) + "...");
        serverSocket = new ServerSocket(port);
        log.info("Running Simple WebServer!\n");
        connectionSocket = serverSocket.accept();
        connectionSocket.setSoTimeout(30000);
        //go in a infinite loop, wait for connections, process request, send response
        while (running) {
            log.info("\nReady, Waiting for requests...\n");
            try {
                //this call waits/blocks until someone connects to the port we
                BufferedReader input;
                if (!connectionSocket.isClosed()) {
                    InetAddress client = connectionSocket.getInetAddress();
                    log.info(client.getHostName() + " connected to server.\n");
                    input = new BufferedReader(
                            new InputStreamReader(connectionSocket.getInputStream(), Charset.defaultCharset()));
                    if (input.ready()) {
                        DataOutputStream output = new DataOutputStream(connectionSocket.getOutputStream());
                        httpHandler(input, output);
                    }
                }
                //Prepare a outputStream. This will be used sending back our response
                //(header + requested file) to the client.
            } catch (Exception e) { //catch any errors, and print them
                log.info("\nError:" + e.getMessage());
                running = false;
            }
        }
    } catch (Exception e) {
        log.error("\nFatal Error:" + e.getMessage());
        running = false;
    } finally {
        try {
            if (connectionSocket != null) {
                connectionSocket.close();
                serverSocket.close();
            }
        } catch (IOException e) {
            log.error("Error while shutting down server sockets", e);
        }
    }
}

From source file:org.rdv.rbnb.MarkerManager.java

/**
 * Create the marker manager and starts listening for new markers from the
 * metadata manager./*  ww w  . j ava  2  s.  c  o  m*/
 * 
 * @param rbnbController  the rbnb interface
 */
public MarkerManager(RBNBController rbnbController) {
    super();

    try {
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();
        rbnbSourceName += "@" + hostname;
    } catch (UnknownHostException e) {
    }

    this.rbnbController = rbnbController;

    markers = new ArrayList<EventMarker>();

    markerListeners = new ArrayList<EventMarkerListener>();

    rbnbController.getMetadataManager().addMarkerListener(this);
}

From source file:org.everit.jetty.server.ecm.tests.JettyComponentTest.java

@Test
public void testForwardRequestCustomizer() {
    try {//from   w w w  . j  a  va 2s  .c  o m
        InetAddress localHost = InetAddress.getLocalHost();
        URL url = new URL("http://" + localHost.getHostName() + ":" + port + "/sample/echoremote");
        HttpURLConnection urlConnection = openConnection(url);
        JSONObject jsonObject = readJSONResponse(urlConnection);
        Assert.assertEquals(localHost.getHostName(), jsonObject.getString("serverName"));
        Assert.assertEquals(String.valueOf(port), jsonObject.get("serverPort").toString());

        final String testClientName = "11.11" + ".11.11";
        final String testServerName = "mytest.com";
        final int testServerPort = 888;

        urlConnection = openConnection(url);
        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_FOR.asString(), testClientName);

        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_HOST.asString(),
                testServerName + ":" + testServerPort);
        urlConnection.setRequestProperty(HttpHeader.X_FORWARDED_PROTO.asString(), "https");

        jsonObject = readJSONResponse(urlConnection);
        Assert.assertEquals(testClientName, jsonObject.getString("remoteAddr"));
        Assert.assertEquals(testServerName, jsonObject.getString("serverName"));
        Assert.assertEquals(String.valueOf(testServerPort), jsonObject.get("serverPort").toString());
        Assert.assertEquals(true, Boolean.valueOf(jsonObject.get("secure").toString()));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

}

From source file:runtime.starter.MPJYarnWrapper.java

public void run() {

    try {//from  www  .j av a2s.c om
        clientSock = new Socket(serverName, ioServerPort);
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (IOException exp) {
        exp.printStackTrace();
    }

    // Redirecting Output Stream 
    try {
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        c = Class.forName(className);
    } catch (ClassNotFoundException exp) {
        exp.printStackTrace();
    }

    try {
        String[] arvs = new String[3];

        if (appArgs != null) {
            arvs = new String[3 + appArgs.length];
        }
        arvs[0] = rank;
        arvs[1] = portInfo;
        arvs[2] = deviceName;

        if (appArgs != null) {
            for (int i = 0; i < appArgs.length; i++) {
                arvs[3 + i] = appArgs[i];
            }
        }

        InetAddress localaddr = InetAddress.getLocalHost();
        String hostName = localaddr.getHostName();

        System.out.println("Starting process <" + rank + "> on <" + hostName + ">");

        Method m = c.getMethod("main", new Class[] { arvs.getClass() });
        m.setAccessible(true);
        int mods = m.getModifiers();

        if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
            throw new NoSuchMethodException("main");
        }

        m.invoke(null, new Object[] { arvs });

        System.out.println("Stopping process <" + rank + "> on <" + hostName + ">");

        System.out.println("EXIT");//Stopping IOThread

        try {
            clientSock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception ioe) {
        ioe.printStackTrace();
    }

}

From source file:uk.ac.ebi.arrayexpress.app.Application.java

public void sendEmail(String originator, String[] recipients, String subject, String message) {
    try {//from  w  w w .j  a v a 2  s.c  o m
        Thread currentThread = Thread.currentThread();
        String hostName = "unknown";
        try {
            InetAddress localMachine = InetAddress.getLocalHost();
            hostName = localMachine.getHostName();
        } catch (Exception xx) {
            logger.debug("Caught an exception:", xx);
        }

        if (null == recipients || 0 == recipients.length) {
            recipients = getPreferences().getStringArray("app.reports.recipients");
        }

        if (null == originator || "".equals(originator)) {
            originator = getPreferences().getString("app.reports.originator");
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("variable.appname", getName());
        params.put("variable.thread", String.valueOf(currentThread));
        params.put("variable.hostname", hostName);
        StrSubstitutor sub = new StrSubstitutor(params);

        emailer.send(recipients, getPreferences().getStringArray("app.reports.hidden-recipients"), subject,
                sub.replace(message), originator);

    } catch (Throwable x) {
        logger.error("[SEVERE] Cannot even send an email without an exception:", x);
    }
}

From source file:ca.ualberta.physics.cssdp.file.remote.protocol.FtpConnection.java

@Override
public boolean disconnect() {

    try {//from w  ww  . j  av  a  2 s .  c o  m
        InetAddress remoteAddress = ftpClient.getRemoteAddress();
        logger.info("Disconnecting from " + (remoteAddress != null ? remoteAddress.getHostName() : "unknown"));
        ftpClient.disconnect();
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:de.yaio.commons.net.NetFirewall.java

/** 
 * checks if url is allowed//from ww  w  .  java2 s  .c o  m
 * @param url                    url to check (check protocoll, hostname and ip)
 * @return                       true/false if it is allowed
 * @throws MalformedURLException parsing the url
 * @throws UnknownHostException  parsing the url
 */
public boolean isAllowed(final URL url) throws UnknownHostException, MalformedURLException {
    // check protocol
    if (!isInProtocolList(url.getProtocol())) {
        return false;
    }

    // check inetAddr
    InetAddress inetAddr = NetUtils.parseAddress(url.getHost());
    String hostName = inetAddr.getHostName();
    String ip = inetAddr.getHostAddress();
    if (isInHostBlackList(hostName) || isInIPBlackList(ip)) {
        // blacklisted: but check for override by whitelist
        if (isInHostWhiteList(hostName) || isInIPWhiteList(ip)) {
            return true;
        }

        // blacklisted
        return false;
    }

    return true;
}

From source file:org.apache.whirr.service.hbase.BasicServerClusterActionHandler.java

@Override
protected void beforeConfigure(ClusterActionEvent event) throws IOException, InterruptedException {
    ClusterSpec clusterSpec = event.getClusterSpec();
    Cluster cluster = event.getCluster();
    int port = defaultPort;
    if (configKeyPort != null) {
        port = getConfiguration(clusterSpec).getInt(configKeyPort, defaultPort);
    }//w  w w  .  j a v a  2  s .  c  o m

    Cluster.Instance instance = cluster.getInstanceMatching(role(role));
    InetAddress masterPublicAddress = instance.getPublicAddress();

    event.getFirewallManager().addRule(Rule.create().destination(instance).port(port));

    String master = masterPublicAddress.getHostName();
    String quorum = ZooKeeperCluster.getHosts(cluster);

    String tarurl = prepareRemoteFileUrl(event,
            getConfiguration(clusterSpec).getString(HBaseConstants.KEY_TARBALL_URL));

    addStatement(event,
            call(getConfigureFunction(getConfiguration(clusterSpec)), role, HBaseConstants.PARAM_MASTER, master,
                    HBaseConstants.PARAM_QUORUM, quorum, HBaseConstants.PARAM_PORT, Integer.toString(port),
                    HBaseConstants.PARAM_TARBALL_URL, tarurl));
}