Example usage for java.net InetAddress getLocalHost

List of usage examples for java.net InetAddress getLocalHost

Introduction

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

Prototype

public static InetAddress getLocalHost() throws UnknownHostException 

Source Link

Document

Returns the address of the local host.

Usage

From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java

protected static String getComment(File basePath) {
    try {//from  w w w  .j a va2s  .  c  o  m
        String hostname;
        String user = System.getProperty("user.name", "unknown");
        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            hostname = InetAddress.getLocalHost().getHostAddress();
        }
        return user + " " + getScmRevision(basePath) + " " + hostname;
    } catch (Throwable t) {
        // If this blows up, continue on....
        return "";
    }
}

From source file:edu.bsu.issgame.java.IssGameJava.java

@Override
public RFuture<Boolean> startGameService() {
    final RPromise<Boolean> promise = RPromise.create();
    try {//from www. j a v a  2s  .c om
        server = new Server(executorService, new SocketConnectionAccepter(NetworkInterface.PORT),
                "Expedition Java", versionCode);
    } catch (IOException e) {
        e.printStackTrace();
    }
    server.onServerStart().connect(new UnitSlot() {
        @Override
        public void onEmit() {
            promise.succeed(true);
            startClientAsync();
        }

        private void startClientAsync() {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        log().debug("Starting up the local client.");
                        InetAddress localhost = InetAddress.getLocalHost();
                        Socket socket = new Socket(localhost, NetworkInterface.PORT);
                        MessageIO io = MessageIO.SocketAdapter.inClientMode(socket);
                        Client client = Client.withIO(io).withVersionCode(versionCode);
                        clientCreated.emit(client);
                        executorService.execute(client);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    });
    executorService.execute(server);
    return promise;
}

From source file:net.firejack.platform.installation.processor.SetupSystemProcessor.java

/***/
public void setupSystem() {
    String domainUrl = OpenFlameConfig.DOMAIN_URL.getValue();
    Integer port = Integer.parseInt(OpenFlameConfig.PORT.getValue());
    String contextUrl = OpenFlameConfig.CONTEXT_URL.getValue();

    if (domainUrl != null && port != null && contextUrl != null) {
        Env.FIREJACK_URL.setValue(WebUtils.getNormalizedUrl(domainUrl, port, contextUrl));
    }/*from   w  w w . j av a 2  s  . c  o  m*/

    RootDomainModel rootDomain = rootDomainStore.findByLookup(OpenFlame.ROOT_DOMAIN);
    if (rootDomain == null) {
        rootDomain = new RootDomainModel();
        rootDomain.setName(DiffUtils.findRootDomainName(OpenFlame.ROOT_DOMAIN));
        rootDomain.setLookup(OpenFlame.ROOT_DOMAIN);
        rootDomainStore.save(rootDomain);
    }

    try {
        Environments<Environment> environments = EnvironmentsUtils.deserialize(InstallUtils.getXmlEnv());
        if (environments != null && !environments.isEmpty()) {
            for (Environment environment : environments.getEnvironments()) {
                if (rootDomain.getLookup().equals(environment.getSystem().getPath())) {
                    environmentStore.save(rootDomain, environment);
                }
            }
        }

        loadRepositories();

        File contentXmlInstallationFile = FileUtils.getResource("dbupdate",
                PackageFileType.CONTENT_XML.getOfrFileName());
        //        File resourceZipInstallationFile = FileUtils.getResource("dbupdate", PackageFileType.RESOURCE_ZIP.getOfrFileName());

        FileInputStream stream = new FileInputStream(contentXmlInstallationFile);
        importContentProcessor.importContent(stream, null);
        IOUtils.closeQuietly(stream);

        if (environments != null && !environments.isEmpty()) {
            for (Environment environment : environments.getEnvironments()) {
                if (rootDomain.getLookup().equals(environment.getSystem().getPath())) {
                    for (ServerModel model : environment.getServers()) {
                        if (model.getName().equals("server")) {
                            String name = InetAddress.getLocalHost().getHostName();

                            KeyPair pair = KeyUtils.generate(EnvironmentsUtils.getKeyStore());
                            byte[] encodedPubKey = Base64.encode(pair.getPublic().getEncoded());

                            model.setName(name);
                            model.setPublicKey(new String(encodedPubKey));

                            serverStore.merge(model);

                            KeyUtils.add(EnvironmentsUtils.getKeyStore(), pair, "");
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        logger.error(e, e);
        throw new BusinessFunctionException("Occurred error in initialize content.", e);
    }
}

From source file:com.asquareb.kaaval.MachineKey.java

/**
 * Method to decrypt a string. Accepts the string to be decrypted and the
 * name of the file which stores the key values
 *//*from   w  ww . j  a v a  2 s  . c  om*/
public static String decrypt(String property, String app) throws IOException, KaavalException {
    SecretKey key = null;
    ObjectInputStream is = null;
    MachineKey mKey = null;
    int eti = 0;
    Cipher pbeCipher = null;
    InetAddress ip = InetAddress.getLocalHost();
    NetworkInterface macAddress = NetworkInterface.getByInetAddress(ip);
    byte[] macId = macAddress.getHardwareAddress();
    try {
        is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(app)));
        mKey = (MachineKey) is.readObject();
        key = mKey.yek;
        salt = mKey.tlas;
        eti = mKey.eti;
        String ipa = ip.getHostAddress();
        if (!ipa.equals(mKey.api) || !new String(macId).equals(mKey.macad))
            throw new KaavalException(5, "Key file is not for this machine");
        is.close();
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, eti));
        return new String(pbeCipher.doFinal(base64Decode(property)));
    } catch (IOException e) {
        throw new KaavalException(3, "Error in reading key file during decryption", e);
    } catch (KaavalException e) {
        throw e;
    } catch (Exception e) {
        throw new KaavalException(4, "Error during decryption", e);
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Determine if an address is available.
 *///from  ww  w.  j a  va 2s .c  o m
public static boolean isAlive(String ips, int port) {
    if (logger.isDebugEnabled())
        logger.debug("trying to reach: " + ips + ":" + port);
    try {
        if ("".equals(ips))
            ips = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
        throw new StoreException(
                "can not determine local adapter, but there is another node, which would need to be contacted.",
                e);
    }
    StringTokenizer tokens = new StringTokenizer(ips, ",");
    while (tokens.hasMoreTokens()) {
        String ip = tokens.nextToken();
        if (logger.isDebugEnabled())
            logger.debug("determining whether '" + ip + ":" + port + "' is alive...");
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), SOCKET_CONNECT_TIMEOUT);
            socket.close();
            return true; // Success, so return true
        } catch (Exception e) {
            logger.debug("unreachable node at '" + ip + ":" + port + ", " + e.getMessage());
        }
    }
    logger.debug("could not reach any of the ips given for node");
    return false;
}

From source file:de.iai.ilcd.configuration.ConfigurationService.java

private void confNodeInfo() {
    String detectedHostName = null;
    try {/*ww  w .j a  v  a 2 s. c  o  m*/
        InetAddress inetAddress = InetAddress.getLocalHost();
        detectedHostName = inetAddress.getHostName();
    } catch (UnknownHostException e) {
        this.logger.error("Could not detect hostname", e);
    }

    String configuredHostName = this.fileConfig.getString("service.url.hostname");
    int port = this.fileConfig.getInteger("service.url.port", 80);

    String hostName;

    if (configuredHostName != null) {
        hostName = configuredHostName;
    } else {
        hostName = detectedHostName;
    }

    try {
        URI newUri = new URI("http", null, hostName, (port == 80 ? -1 : port), this.contextPath, null, null);
        this.logger.info("application base URI: " + newUri.toString());
        this.baseURI = newUri;
        this.nodeInfo.setBaseURL(newUri.toString() + "/resource/");
    } catch (URISyntaxException e) {
        throw new RuntimeException("FATAL ERROR: could not determine base URL for service interface", e);
    }

    try {
        this.nodeInfo.setNodeID(this.fileConfig.getString("service.node.id"));
    } catch (Exception e) {
        this.logger.error("Cannot set nodeid from configuration file", e);
    }
    try {
        this.nodeInfo.setName(this.fileConfig.getString("service.node.name"));
    } catch (Exception e) {
        this.logger.error("Cannot set nodename from configuration file", e);
    }

    this.nodeInfo.setOperator(this.fileConfig.getString("service.node.operator"));
    this.nodeInfo.setDescription(this.fileConfig.getString("service.node.description"));

    // override baseURL only if it is explicitly set in the configuration file
    if (this.fileConfig.getString("service.node.baseURL") != null) {
        String url = this.fileConfig.getString("service.node.baseURL");
        if (!url.endsWith("/"))
            url += "/";
        this.nodeInfo.setBaseURL(url);
    }

    this.nodeInfo.setAdminName(this.fileConfig.getString("service.admin.name"));
    this.nodeInfo.setAdminEMail(this.fileConfig.getString("service.admin.email"));
    this.nodeInfo.setAdminPhone(this.fileConfig.getString("service.admin.phone"));
    this.nodeInfo.setAdminWWW(this.fileConfig.getString("service.admin.www"));

}

From source file:cc.osint.graphd.server.GraphServerHandler.java

@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    String clientId = "" + e.getChannel().getId();
    if (null == clientStateMap.get(clientId)) {
        ConcurrentHashMap<String, String> clientState = new ConcurrentHashMap<String, String>();
        clientState.put(ST_NAMECON, DEFAULT_CONNECTION_NAME + "-" + clientId);
        clientStateMap.put(clientId, clientState);
        clientIdChannelMap.put(clientId, e.getChannel());

        /*//from   w w  w.  j  a va  2s .  c  o m
         * start "client fiber & channel" & connect them
        */
        Fiber fiber = fiberFactory.create();
        fiber.start();
        org.jetlang.channels.Channel<JSONObject> inboundChannel = new MemoryChannel<JSONObject>();
        InboundChannelProcess inboundChannelProcess = new InboundChannelProcess(clientId, fiber, inboundChannel, // jetlang channel
                e.getChannel()); // netty channel
        inboundChannelMap.put(clientId, new WeakReference<InboundChannelProcess>(inboundChannelProcess));

        log.info(clientId + ": " + inboundChannelMap.get(clientId));

        inboundChannel.subscribe(fiber, inboundChannelProcess);
    }
    e.getChannel().write("-graphd " + InetAddress.getLocalHost().getHostName() + GraphServerProtocol.SPACE
            + clientId + GraphServerProtocol.NL);
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;/*from www. ja v  a2 s .  c  o m*/
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:com.momathink.common.tools.ToolMonitor.java

/**
 * MAC? /*from   w  w w .  ja  v  a  2 s  . co m*/
 * @return : "00 00 00 00 00 00"
 */
private String getMACAddr() {
    String mac = "";
    try {
        NetworkInterface netInterface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
        byte[] macAddr = netInterface.getHardwareAddress();
        String macByte = "";
        // ????
        for (byte b : macAddr) {
            macByte = Integer.toHexString((int) (b & 0xff));
            if (macByte.length() == 1) {
                macByte = "0" + macByte;
            }
            mac = mac + " " + macByte;
        }
    } catch (Exception e) {
    }
    return mac.substring(1);
}