List of usage examples for java.net InetAddress getCanonicalHostName
public String getCanonicalHostName()
From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.AutConfigComponent.java
/** * @return if the current aut starter is localhost *//* w ww . j a v a 2 s . co m*/ private boolean isLocalhost() { boolean enable; try { final String serverComboText = getServerCombo().getText(); final InetAddress localHost = InetAddress.getLocalHost(); final String canonicalHostName = localHost.getCanonicalHostName(); enable = (Constants.LOCALHOST1.equals(serverComboText.toLowerCase()) || Constants.LOCALHOST2.equals(serverComboText) || localHost.getHostName().equals(serverComboText) || localHost.getHostAddress().equals(serverComboText) || (canonicalHostName != null && canonicalHostName.equals(serverComboText))); } catch (UnknownHostException e) { enable = false; } return enable; }
From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.AutConfigComponent.java
/** * @return true if the aut config is for the currently connected AUT starter *///from w ww. j ava 2 s. com protected boolean isRemoteRequest() { boolean enable; try { final AutAgent currentServer = ConnectAutAgentBP.getInstance().getCurrentAutAgent(); if (currentServer == null) { return false; } if (isLocalhost()) { return false; } final String serverName = getServerCombo().getText().toLowerCase(); final InetAddress serverAddress = InetAddress.getByName(serverName); final String canonicalServerName = serverAddress.getCanonicalHostName().toLowerCase(); final String currentServerName = currentServer.getName().toLowerCase(); final InetAddress currentServerAddress = InetAddress.getByName(currentServerName); final String canonicalCurrentServerName = currentServerAddress.getCanonicalHostName().toLowerCase(); enable = currentServerName.equals(serverName) || currentServerAddress.equals(serverAddress) || canonicalCurrentServerName.equals(canonicalServerName); } catch (UnknownHostException e) { enable = false; } return enable; }
From source file:name.livitski.databag.cli.Launcher.java
public void run() { try {//from w w w . ja v a2s . c om setStatus(Status.OK); if (!hasOption(NOBANNER_OPTION)) banner(); Level requestedLogLevel = getRequestedLogLevel(); setLogLevel(requestedLogLevel); log().finer("Verbosity level " + requestedLogLevel); if (hasOption(HELP_COMMAND)) { SYNTAX.usage(getOutputStream()); return; } try { boolean doneSomething = false; if (hasOption(CREATE_OPTION)) { create(); doneSomething = true; } else open(); // no database - print usage if (null == db) { log().warning("Could not find a bag on \"" + getMedium() + "\", giving up."); showHelpHint(); return; } if (hasOption(SCHEMA_EVOLUTION_OPTION)) db.setSchemaEvolutionAllowed(true); // determine current user and host String user = System.getProperty(USER_NAME_PROPERTY, "default_user"); InetAddress localAddress = InetAddress.getLocalHost(); String host = localAddress.getCanonicalHostName(); if ("127.0.0.1".equals(host) || "localhost".equalsIgnoreCase(host)) host = localAddress.getHostName(); // locate the copy of shared storage to work with Replicas replicaQueries = new Replicas(db, getConfiguration()); ReplicaInfo replica; File local = getLocal(); replica = replicaQueries.findReplica(user, host, null == local ? null : local.getPath()); if (null == replica) { // new local copy being created if (null != local) { if (hasOption(DROP_COMMAND)) log().warning("Replica at '" + local + "' shall not be created when running a --" + DROP_COMMAND + " command"); else { ReplicaManager rmgr = new ReplicaManager(db, getConfiguration()); Number rid = rmgr.registerNewReplica(user, host, local.getPath()); replica = replicaQueries.findReplica(rid); doneSomething = true; } } // no local copy - print warning else log().warning( "Local replica of bag " + getMedium() + " not found for " + user + '@' + host); } // drop request if (hasOption(DROP_COMMAND)) { if (hasOption(SAVE_OPTION)) throw new IllegalArgumentException("--" + DROP_COMMAND + " command does not support output redirection (--" + SAVE_OPTION + " option)"); DropType type = getDropType(); switch (type) { case REPLICA: if (null == replica) throw new IllegalStateException("Local replica for " + user + '@' + host + " does not exist" + (null == local ? "" : " at " + local)); else if (null == local) throw new IllegalArgumentException( "--" + DROP_COMMAND + " requires an explicit replica location to drop."); else dropReplica(replica); break; case FILTER: if (hasOption(SET_OPTION) || hasOption(LOAD_OPTION)) throw new IllegalArgumentException("Options --" + SET_OPTION + " and --" + LOAD_OPTION + " conflict with --" + DROP_COMMAND + ' ' + DropType.REPLICA + " command. Please remove these options before proceeding."); String[] optionValues = options.getOptionValues(DROP_COMMAND); dropFilter(1 < optionValues.length && FORCE_OPTION.equalsIgnoreCase(optionValues[1])); break; default: throw new UnsupportedOperationException("Unknown type of a record to drop: " + type); } return; } // update filters if necessary before proceeding if (hasFilterOption()) { File fileToLoad = getFileToLoad(); if (null != fileToLoad) { if (hasOption(SET_OPTION)) throw new IllegalArgumentException("Option --" + SET_OPTION + " conflicts with --" + LOAD_OPTION + ". Please remove either of these options before proceeding."); loadFilter(fileToLoad); doneSomething = true; } else { String[] patternsToSet = getPatternsToSet(); if (null != patternsToSet) { setFilter(patternsToSet); doneSomething = true; } } } // TODO: modify these checks when overloading --set or --load operations for // non-filter entities else if (hasOption(SET_OPTION)) throw new IllegalArgumentException("Option --" + SET_OPTION + " requires a --" + FILTER_OPTION + " option with a filter name"); else if (hasOption(LOAD_OPTION)) throw new IllegalArgumentException("Option --" + LOAD_OPTION + " requires a --" + FILTER_OPTION + " option with a filter name"); // default replica designation if (isLocalBecomingDefault()) { ReplicaManager rmgr = new ReplicaManager(db, getConfiguration()); Number rid = replica.getId(); rmgr.setDefaultReplica(rid); doneSomething = true; } // default filter designation if (isFilterBecomingDefault()) { // error if replica is null if (null == replica) throw new IllegalArgumentException("--" + LOCAL_OPTION + " option is required when setting the default filter for a replica."); setDefaultFilter(replica); doneSomething = true; } // list request if (hasOption(LIST_COMMAND)) { ListType type = getListType(); switch (type) { case FILES: listFiles(); break; case REPLICAS: if (hasFilterOption()) log().warning("Option --" + FILTER_OPTION + " does not apply when listing replicas and will be ignored."); listReplicas(user, host); break; case FILTER: listFilter(); break; case FILTERS: if (hasFilterOption()) log().warning("Option --" + FILTER_OPTION + " does not apply when listing filters and will be ignored."); listFilters(replica); break; default: throw new UnsupportedOperationException("Unknown type of record(s) to list: " + type); } return; } // history request if (hasOption(HISTORY_COMMAND)) { listVersions(); return; } // purge request if (hasOption(LOG_COMMAND)) { showLog(); return; } // purge request if (hasOption(PURGE_COMMAND)) { if (hasOption(SAVE_OPTION)) throw new IllegalArgumentException("--" + PURGE_COMMAND + " command does not support output redirection (--" + SAVE_OPTION + " option)"); purge(); return; } // file restore request if (hasOption(RESTORE_COMMAND)) { RestoreCommand cmd = new RestoreCommand(db, replica, getConfiguration()); cmd.setNameOption(optionValue(RESTORE_COMMAND)); cmd.setFileId(getFileId()); cmd.setVersionId(getVersionId()); cmd.setAsOfTime(getAsOfTimestamp()); cmd.setOutputFile(getOutputFile(true)); cmd.run(); return; } // file undo request if (hasOption(UNDO_COMMAND)) { UndoCommand cmd = new UndoCommand(db, replica, getConfiguration()); cmd.setNameOption(optionValue(UNDO_COMMAND)); cmd.setFileId(getFileId()); cmd.setVersionId(getVersionId()); cmd.setAsOfTime(getAsOfTimestamp()); cmd.setNoSync(hasOption(NOSYNC_OPTION)); cmd.run(); return; } // sync by default, unless asked not to if (hasOption(NOSYNC_OPTION)) { if (hasOption(SYNC_COMMAND)) throw new IllegalArgumentException( "Command --" + SYNC_COMMAND + " does not allow option --" + NOSYNC_OPTION); // display a warning when sync is disabled and nothing else is done else if (!doneSomething) { log().warning( "Nothing to do - you disabled synchronization, but didn't change any settings."); } } else if (null != replica) { if (hasOption(SAVE_OPTION)) log().warning("Synchronization does not support output redirection (--" + SAVE_OPTION + " option). That option will be ignored."); SyncCommand cmd = new SyncCommand(db, replica, getConfiguration()); cmd.setPattern(optionValue(SYNC_COMMAND)); cmd.setFileId(getFileId()); cmd.run(); return; } } catch (IncompatibleSchemaException outdated) { if (outdated.isUpgradable()) { log().severe(outdated.getMessage()); log().severe("Back up your database and use the --" + SCHEMA_EVOLUTION_OPTION + " option to allow schema upgrades."); } else log().log(Level.SEVERE, outdated.getMessage(), outdated); setStatus(Status.OBSOLETE); } catch (Exception ex) { log().log(Level.SEVERE, ex.getMessage(), ex); setStatus(Status.RUNTIME); } finally { if (null != db) try { db.close(); } catch (DBException ex) { log().log(Level.WARNING, ex.getMessage(), ex); } } } finally { if (null != this.out) { this.out.close(); this.out = null; } } }
From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.TestContainerManager.java
@Test public void testContainerManagerInitialization() throws IOException { containerManager.start();/*w w w . j av a2s .co m*/ InetAddress localAddr = InetAddress.getLocalHost(); String fqdn = localAddr.getCanonicalHostName(); if (!localAddr.getHostAddress().equals(fqdn)) { // only check if fqdn is not same as ip // api returns ip in case of resolution failure Assert.assertEquals(fqdn, context.getNodeId().getHost()); } // Just do a query for a non-existing container. boolean throwsException = false; try { List<ContainerId> containerIds = new ArrayList<ContainerId>(); ContainerId id = createContainerId(0); containerIds.add(id); GetContainerStatusesRequest request = GetContainerStatusesRequest.newInstance(containerIds); GetContainerStatusesResponse response = containerManager.getContainerStatuses(request); if (response.getFailedRequests().containsKey(id)) { throw response.getFailedRequests().get(id).deSerialize(); } } catch (Throwable e) { throwsException = true; } Assert.assertTrue(throwsException); }
From source file:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java
/** * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input *//* w w w . j a va 2 s. com*/ @SuppressWarnings("unchecked") static INodeEntry instanceToNode(final VM inst) throws GeneratorException { final NodeEntryImpl node = new NodeEntryImpl(); node.setNodename(inst.getName()); node.setOsArch(inst.getCpu().getArchitecture()); node.setOsName(inst.getOs().getType()); node.setDescription(inst.getDescription()); node.setUsername("root"); InetAddress address = null; if (inst.getGuestInfo() != null) { try { address = InetAddress.getByName(inst.getGuestInfo().getFqdn()); logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn() + " Address: " + address.getHostName()); if (address.getHostName() == "localhost") throw new UnknownHostException(); } catch (UnknownHostException e) { /* try the first IP instead then */ logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn() + " does not resolve. Trying IP addresses instead"); for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) { logger.debug("Host " + node.getNodename() + " Trying " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); try { address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); if (address != null) { if (address.isLinkLocalAddress() || address.isMulticastAddress()) { logger.warn("Host " + node.getNodename() + " ip address is not valid: " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress()); continue; } logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress() + " will be used instead"); break; } } catch (UnknownHostException e1) { logger.warn("Host " + node.getNodename() + " IP Address " + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid"); } } } } if (address == null) { /* try resolving based on name */ try { address = InetAddress.getByName(node.getNodename()); } catch (UnknownHostException e) { logger.warn("Unable to Find IP address for Host " + node.getNodename()); return null; } } if (address != null) node.setHostname(address.getCanonicalHostName()); if (inst.getTags() != null) { VMTags tags = inst.getTags(); final HashSet<String> tagset = new HashSet<String>(); try { for (int j = 0; j < tags.list().size(); j++) { tagset.add(tags.list().get(j).getName()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (null == node.getTags()) { node.setTags(tagset); } else { final HashSet<String> orig = new HashSet<String>(node.getTags()); orig.addAll(tagset); node.setTags(orig); } } if (inst.getHighAvailability().getEnabled()) node.setAttribute("HighAvailability", "true"); if (inst.getType() != null) node.setAttribute("Host Type", inst.getType()); node.setAttribute("oVirt VM", "true"); node.setAttribute("oVirt Host", inst.getHost().getName()); return node; }
From source file:com.bigstep.datalake.DLFileSystem.java
private URI selectDatalakeEndpointURI(URI uri, Configuration conf) throws UnknownHostException { String dataLakeDatanodesDomain = conf.get(FS_DL_IMPL_DATALAKE_DATANODES_DOMAIN); InetAddress addresses[] = InetAddress.getAllByName(dataLakeDatanodesDomain); ArrayList<String> datalakeEndpoints = new ArrayList<String>(); for (InetAddress address : addresses) { datalakeEndpoints.add(address.getCanonicalHostName()); }//from w w w .j a va 2 s . c o m int rnd = new Random().nextInt(addresses.length); String homeDirectory = conf.get(FS_DL_IMPL_HOME_DIRECTORY); return URI.create("dl://" + datalakeEndpoints.get(rnd) + ":" + DATALAKE_PORT + homeDirectory); }
From source file:lia.gsi.net.GSIGssSocketFactory.java
/** * @param inetAddress ://from www . ja v a 2s . c o m * the remote address * @param port : * the remote port * @param doDelegation : * if true, the client credential is delegated * @param fullDelegation : * if doDelegation is set, this parameter specifies the type of delegation (FULL or LIMITED) * @return the GSI-protected socket connected to the remote host * @throws IOException */ public java.net.Socket createSocket(java.net.InetAddress inetAddress, int port, boolean doDelegation, boolean fullDelegation) throws IOException { // raw socket Socket socket = null; try { //override the search path for the CA directory: (GSI-SSHTERM writes in the ~/.globus/certificates so we don;t use this) //1) java X509_CERT_DIR property //2) override with X509_CERT_DIR env var //3) default /etc/grid-security/certificates String x509CertDir = System.getProperty("X509_CERT_DIR"); if (x509CertDir == null) { x509CertDir = System.getenv("X509_CERT_DIR"); if (x509CertDir == null) x509CertDir = "/etc/grid-security/certificates"; System.setProperty("X509_CERT_DIR", x509CertDir); } String x509UserProxy = System.getenv("X509_USER_PROXY"); if (x509UserProxy == null) x509UserProxy = CoGProperties.getDefault().getProxyFile(); System.out.println("Trying " + x509UserProxy); GSSCredential credential = createUserCredential(x509UserProxy); if (credential == null) { throw new IOException("User credential not initialized !"); } logger.info("createSocket() user credential is " + credential.getName()); GSSManager manager = ExtendedGSSManager.getInstance(); org.globus.gsi.gssapi.auth.GSSAuthorization gssAuth = org.globus.gsi.gssapi.auth.HostAuthorization .getInstance(); GSSName targetName = gssAuth.getExpectedName(null, inetAddress.getCanonicalHostName()); ExtendedGSSContext context = (ExtendedGSSContext) manager.createContext(targetName, GSSConstants.MECH_OID, credential, GSSContext.DEFAULT_LIFETIME); context.setOption(GSSConstants.GSS_MODE, GSIConstants.MODE_GSI); context.requestCredDeleg(doDelegation); if (doDelegation) { if (fullDelegation) { context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_FULL); } else { context.setOption(GSSConstants.DELEGATION_TYPE, GSIConstants.DELEGATION_TYPE_LIMITED); } } SocketAddress socketAddress = new InetSocketAddress(inetAddress, port); socket = new Socket(); socket.connect(socketAddress, GSI_CONNECT_TIMEOUT); GSIGssSocket gsiSocket = new GSIGssSocket(socket, context); gsiSocket.setUseClientMode(true); gsiSocket.setAuthorization(gssAuth); // Should be GSI_MODE ? gsiSocket.setWrapMode(GssSocket.SSL_MODE); gsiSocket.startHandshake(); socket = gsiSocket; } catch (Throwable e) { if (socket != null) { try { socket.close(); } catch (Exception e1) { logger.debug("Socket is already closed."); } } throw new IOException(e.toString()); } // return the wrapped socket return socket; }
From source file:com.chiralBehaviors.autoconfigure.AutoConfigure.java
/** * @return the host address to bind this service to *//*w w w . j a v a2s .co m*/ protected InetAddress determineHostAddress() { NetworkInterface iface = determineNetworkInterface(); InetAddress raw = null; for (Enumeration<InetAddress> interfaceAddresses = iface.getInetAddresses(); interfaceAddresses .hasMoreElements();) { if (!interfaceAddresses.hasMoreElements()) { String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(), iface.getDisplayName()); logger.error(msg); throw new IllegalStateException(msg); } raw = interfaceAddresses.nextElement(); if (config.ipV6) { if (raw.getAddress().length == 6) { break; } } else if (raw.getAddress().length == 4) { break; } } if (raw == null) { String msg = String.format("Unable to find any network address for interface[%s] {%s}", iface.getName(), iface.getDisplayName()); logger.error(msg); throw new IllegalStateException(msg); } InetAddress address; try { address = InetAddress.getByName(raw.getCanonicalHostName()); } catch (UnknownHostException e) { String msg = String.format("Unable to resolve network address [%s] for interface[%s] {%s}", raw, iface.getName(), iface.getDisplayName()); logger.error(msg, e); throw new IllegalStateException(msg, e); } return address; }
From source file:org.apache.geode.distributed.LocatorLauncher.java
/** * Gets the host, as either hostname or IP address, on which the Locator was bound and running. An * attempt is made to get the canonical hostname for IP address to which the Locator was bound for * accepting client requests. If the bind address is null or localhost is unknown, then a default * String value of "localhost/127.0.0.1" is returned. * * Note, this information is purely information and should not be used to re-construct state or * for other purposes.//from w w w . j ava2s . c om * * @return the hostname or IP address of the host running the Locator, based on the bind-address, * or 'localhost/127.0.0.1' if the bind address is null and localhost is unknown. * @see java.net.InetAddress * @see #getBindAddress() */ protected String getBindAddressAsString() { try { if (getBindAddress() != null) { return getBindAddress().getCanonicalHostName(); } InetAddress localhost = SocketCreator.getLocalHost(); return localhost.getCanonicalHostName(); } catch (UnknownHostException handled) { // Returning localhost/127.0.0.1 implies the bindAddress was null and no IP address for // localhost could be found return "localhost/127.0.0.1"; } }
From source file:hudson.model.Computer.java
/** * This method tries to compute the name of the host that's reachable by all the other nodes. * * <p>//w ww . ja va2s . c o m * Since it's possible that the agent is not reachable from the master (it may be behind a firewall, * connecting to master via JNLP), this method may return null. * * It's surprisingly tricky for a machine to know a name that other systems can get to, * especially between things like DNS search suffix, the hosts file, and YP. * * <p> * So the technique here is to compute possible interfaces and names on the agent, * then try to ping them from the master, and pick the one that worked. * * <p> * The computation may take some time, so it employs caching to make the successive lookups faster. * * @since 1.300 * @return * null if the host name cannot be computed (for example because this computer is offline, * because the agent is behind the firewall, etc.) */ public String getHostName() throws IOException, InterruptedException { if (hostNameCached) // in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful. return cachedHostName; VirtualChannel channel = getChannel(); if (channel == null) return null; // can't compute right now for (String address : channel.call(new ListPossibleNames())) { try { InetAddress ia = InetAddress.getByName(address); if (!(ia instanceof Inet4Address)) { LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address); continue; } if (!ComputerPinger.checkIsReachable(ia, 3)) { LOGGER.log(Level.FINE, "{0} didn't respond to ping", address); continue; } cachedHostName = ia.getCanonicalHostName(); hostNameCached = true; return cachedHostName; } catch (IOException e) { // if a given name fails to parse on this host, we get this error LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}"); lr.setThrown(e); lr.setParameters(new Object[] { address }); LOGGER.log(lr); } } // allow the administrator to manually specify the host name as a fallback. HUDSON-5373 cachedHostName = channel.call(new GetFallbackName()); hostNameCached = true; return cachedHostName; }