Java Code Examples for java.net.UnknownHostException#getMessage()

The following examples show how to use java.net.UnknownHostException#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BMLSynthesizedOutputFactory.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
     * {@inheritDoc}
     */
    public SynthesizedOutput createResource() throws NoresourceError {
        final BMLSynthesizedOutput output = new BMLSynthesizedOutput();
        output.setType(type);
        try {
            output.setHost(host);
        } catch (UnknownHostException e) {
            throw new NoresourceError(e.getMessage(), e);
        }
        output.setPort(port);
        output.setFeedbackPort(feedbackPort);
        output.setExternalBMLPublisher(external);
//        output.setVoice(voice);
//        output.setDefaultLocale(defaultLocale);
        return output;
    }
 
Example 2
Source File: ToolUtil.java    From kylin with Apache License 2.0 6 votes vote down vote up
public static String getHostName() {
    String hostname = System.getenv("COMPUTERNAME");
    if (StringUtils.isEmpty(hostname)) {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
            hostname = address.getHostName();
            if (StringUtils.isEmpty(hostname)) {
                hostname = address.getHostAddress();
            }
        } catch (UnknownHostException uhe) {
            String host = uhe.getMessage(); // host = "hostname: hostname"
            if (host != null) {
                int colon = host.indexOf(':');
                if (colon > 0) {
                    return host.substring(0, colon);
                }
            }
            hostname = "Unknown";
        }
    }
    return hostname;
}
 
Example 3
Source File: DockerHostUtil.java    From SkyEye with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 从运行机器获取host
 * @return
 */
public static String getHostFromLocal() {
    try {
        return (InetAddress.getLocalHost()).getHostName();
    } catch (UnknownHostException uhe) {
        String host = uhe.getMessage();
        if (host != null) {
            int colon = host.indexOf(Constants.COLON);
            if (colon > 0) {
                return host.substring(0, colon);
            }
        }

    }
    return Constants.UNKNOWN_HOST;
}
 
Example 4
Source File: CreateStoragePoolCmd.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() {
    try {
        final StoragePool result = _storageService.createPool(this);
        if (result != null) {
            final StoragePoolResponse response = _responseGenerator.createStoragePoolResponse(result);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add storage pool");
        }
    } catch (final ResourceUnavailableException ex1) {
        s_logger.warn("Exception: ", ex1);
        throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, ex1.getMessage());
    } catch (final ResourceInUseException ex2) {
        s_logger.warn("Exception: ", ex2);
        throw new ServerApiException(ApiErrorCode.RESOURCE_IN_USE_ERROR, ex2.getMessage());
    } catch (final UnknownHostException ex3) {
        s_logger.warn("Exception: ", ex3);
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex3.getMessage());
    } catch (final Exception ex4) {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex4.getMessage());
    }
}
 
Example 5
Source File: ModbusTCPMaster.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Constructs a new master facade instance for communication
 * with a given slave.
 *
 * @param addr an internet address as resolvable IP name or IP number,
 *            specifying the slave to communicate with.
 */
public ModbusTCPMaster(String addr) {
    try {
        m_SlaveAddress = InetAddress.getByName(addr);
        m_Connection = new TCPMasterConnection(m_SlaveAddress);
        m_ReadCoilsRequest = new ReadCoilsRequest();
        m_ReadInputDiscretesRequest = new ReadInputDiscretesRequest();
        m_WriteCoilRequest = new WriteCoilRequest();
        m_WriteMultipleCoilsRequest = new WriteMultipleCoilsRequest();
        m_ReadInputRegistersRequest = new ReadInputRegistersRequest();
        m_ReadMultipleRegistersRequest = new ReadMultipleRegistersRequest();
        m_WriteSingleRegisterRequest = new WriteSingleRegisterRequest();
        m_WriteMultipleRegistersRequest = new WriteMultipleRegistersRequest();

    } catch (UnknownHostException e) {
        throw new RuntimeException(e.getMessage());
    }
}
 
Example 6
Source File: ToolUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
public static String getHostName() {
    String hostname = System.getenv("COMPUTERNAME");
    if (StringUtils.isEmpty(hostname)) {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
            hostname = address.getHostName();
            if (StringUtils.isEmpty(hostname)) {
                hostname = address.getHostAddress();
            }
        } catch (UnknownHostException uhe) {
            String host = uhe.getMessage(); // host = "hostname: hostname"
            if (host != null) {
                int colon = host.indexOf(':');
                if (colon > 0) {
                    return host.substring(0, colon);
                }
            }
            hostname = "Unknown";
        }
    }
    return hostname;
}
 
Example 7
Source File: PeerAddress.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a peer address from the serialized data
 *
 * @param inBuffer
 *            Serialized buffer
 * @throws EOFException
 *             End-of-data while processing serialized data
 */
public PeerAddress(SerializedBuffer inBuffer) throws EOFException {
	//
	// Get the address values
	//
	timeSeen = inBuffer.getInt();
	services = inBuffer.getLong();
	byte[] addrBytes = inBuffer.getBytes(16);
	port = (inBuffer.getUnsignedByte() << 8) | inBuffer.getUnsignedByte();
	//
	// Generate the IPv4 or IPv6 address
	//
	try {
		boolean ipv4 = true;
		for (int j = 0; j < 12; j++) {
			if (addrBytes[j] != IPV6_PREFIX[j]) {
				ipv4 = false;
				break;
			}
		}
		if (ipv4)
			address = InetAddress.getByAddress(Arrays.copyOfRange(addrBytes, 12, 16));
		else
			address = InetAddress.getByAddress(addrBytes);
	} catch (UnknownHostException exc) {
		throw new RuntimeException("Unexpected exception thrown by InetAddress.getByAddress: " + exc.getMessage());
	}
}
 
Example 8
Source File: Config.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Locate Kerberos realm using DNS
 *
 * @return the Kerberos realm
 */
private String getRealmFromDNS() throws KrbException {
    // use DNS to locate Kerberos realm
    String realm = null;
    String hostName = null;
    try {
        hostName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        KrbException ke = new KrbException(Krb5.KRB_ERR_GENERIC,
            "Unable to locate Kerberos realm: " + e.getMessage());
        ke.initCause(e);
        throw (ke);
    }
    // get the domain realm mapping from the configuration
    String mapRealm = PrincipalName.mapHostToRealm(hostName);
    if (mapRealm == null) {
        // No match. Try search and/or domain in /etc/resolv.conf
        List<String> srchlist = ResolverConfiguration.open().searchlist();
        for (String domain: srchlist) {
            realm = checkRealm(domain);
            if (realm != null) {
                break;
            }
        }
    } else {
        realm = checkRealm(mapRealm);
    }
    if (realm == null) {
        throw new KrbException(Krb5.KRB_ERR_GENERIC,
                            "Unable to locate Kerberos realm");
    }
    return realm;
}
 
Example 9
Source File: RTPSessionMgr.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public void addTarget(SessionAddress sessionaddress)
throws IOException
{
    remoteAddresses.addElement(sessionaddress);
    if(remoteAddresses.size() > 1)
    {
        setRemoteAddresses();
        return;
    }
    remoteAddress = sessionaddress;
    try
    {
        rtcpRawReceiver = new RTCPRawReceiver(localAddress, sessionaddress, defaultstats, streamSynch, controlSocket);
        rtpRawReceiver = new RTPRawReceiver(channel, localAddress, sessionaddress, defaultstats, dataSocket);
    }
    catch(SocketException socketexception)
    {
        throw new IOException(socketexception.getMessage());
    }
    catch(UnknownHostException unknownhostexception)
    {
        throw new IOException(unknownhostexception.getMessage());
    }
    rtpDemultiplexer = new RTPDemultiplexer(cache, rtpRawReceiver, streamSynch);
    rtcpForwarder = new PacketForwarder(rtcpRawReceiver, new RTCPReceiver(cache));
    if(rtpRawReceiver != null)
    {
        rtpForwarder = new PacketForwarder(rtpRawReceiver, new RTPReceiver(cache, rtpDemultiplexer));
    }
    rtcpForwarder.startPF("RTCP Forwarder for address" + sessionaddress.getControlHostAddress() + " port " + sessionaddress.getControlPort());
    if(rtpForwarder != null)
    {
        rtpForwarder.startPF("RTP Forwarder for address " + sessionaddress.getDataHostAddress() + " port " + sessionaddress.getDataPort());
    }
    cleaner = new SSRCCacheCleaner(cache, streamSynch);
    if(cache.ourssrc != null && participating)
    {
        cache.ourssrc.reporter = startParticipating(rtpRawReceiver.socket);
    }
}
 
Example 10
Source File: NetworkMonitor.java    From fuchsia with Apache License 2.0 5 votes vote down vote up
private static InetSocketAddress createLocalSocket(InetAddress host, Integer port)
{
	final int p = port != null ? port.intValue() : 0;
	try {
		return host != null ? new InetSocketAddress(host, p) : p != 0
			? new InetSocketAddress(InetAddress.getLocalHost(), p) : null;
	}
	catch (final UnknownHostException e) {
		throw new IllegalArgumentException("failed to create local host "
			+ e.getMessage());
	}
}
 
Example 11
Source File: LightminClientProperties.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
private InetAddress getHostAddress() {
    try {
        return InetAddress.getLocalHost();
    } catch (final UnknownHostException ex) {
        throw new IllegalArgumentException(ex.getMessage(), ex);
    }
}
 
Example 12
Source File: PropClient.java    From fuchsia with Apache License 2.0 5 votes vote down vote up
private static InetSocketAddress createLocalSocket(InetAddress host, Integer port)
{
	final int p = port != null ? port.intValue() : 0;
	try {
		return host != null ? new InetSocketAddress(host, p) : p != 0
			? new InetSocketAddress(InetAddress.getLocalHost(), p) : null;
	}
	catch (final UnknownHostException e) {
		throw new IllegalArgumentException("failed to create local host "
			+ e.getMessage());
	}
}
 
Example 13
Source File: MasterDescriptions.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static String getHost(String host) {
    if (host != null && !host.isEmpty()) {
        return host;
    }

    try {
        return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        throw new RuntimeException("Failed to get the host information: " + e.getMessage(), e);
    }
}
 
Example 14
Source File: MasterDescriptions.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private static String getHostIP(String masterIp) {
    String ip = masterIp;
    if (ip != null && !ip.isEmpty()) {
        return ip;
    }

    try {
        return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        throw new RuntimeException("Failed to get the host information: " + e.getMessage(), e);
    }
}
 
Example 15
Source File: ControllersEchoCommand.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
public static String getNodeName() {
  try {
    return InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    String message = e.getMessage();
    int index = message.indexOf(':');
    if (index < 0) {
      return null;
    }
    String nodeName = message.substring(0, index);
    return nodeName;
  }
}
 
Example 16
Source File: Config.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Locate Kerberos realm using DNS
 *
 * @return the Kerberos realm
 */
private String getRealmFromDNS() throws KrbException {
    // use DNS to locate Kerberos realm
    String realm = null;
    String hostName = null;
    try {
        hostName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        KrbException ke = new KrbException(Krb5.KRB_ERR_GENERIC,
            "Unable to locate Kerberos realm: " + e.getMessage());
        ke.initCause(e);
        throw (ke);
    }
    // get the domain realm mapping from the configuration
    String mapRealm = PrincipalName.mapHostToRealm(hostName);
    if (mapRealm == null) {
        // No match. Try search and/or domain in /etc/resolv.conf
        List<String> srchlist = ResolverConfiguration.open().searchlist();
        for (String domain: srchlist) {
            realm = checkRealm(domain);
            if (realm != null) {
                break;
            }
        }
    } else {
        realm = checkRealm(mapRealm);
    }
    if (realm == null) {
        throw new KrbException(Krb5.KRB_ERR_GENERIC,
                            "Unable to locate Kerberos realm");
    }
    return realm;
}
 
Example 17
Source File: SocketChannelDataLink.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 指定したアドレス・ポートへ接続する, クライアントからの接続待ち中で無くても構わない
 * @param addr
 * @param port
 * @return
 * @throws IOException
 */
public Client connectTo(final String addr, final int port) throws IOException {
	if (DEBUG) Log.v(TAG, "connectTo:addr=" + addr + ",port=" + port);
	Client result;
	try {
		final InetAddress address = InetAddress.getByName(addr);
		result = new Client(this, addr, port);
		add(result);
	} catch (final UnknownHostException e) {
		throw new IOException(e.getMessage());
	}
	return result;
}
 
Example 18
Source File: DefaultApplicationFactory.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
protected InetAddress getLocalHost() {
	try {
		return InetAddress.getLocalHost();
	}
	catch (UnknownHostException ex) {
		throw new IllegalArgumentException(ex.getMessage(), ex);
	}
}
 
Example 19
Source File: FeastProperties.java    From feast with Apache License 2.0 4 votes vote down vote up
/**
 * Validates all FeastProperties. This method runs after properties have been initialized and
 * individually and conditionally validates each class.
 */
@PostConstruct
public void validate() {
  ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
  Validator validator = factory.getValidator();

  // Validate root fields in FeastProperties
  Set<ConstraintViolation<FeastProperties>> violations = validator.validate(this);
  if (!violations.isEmpty()) {
    throw new ConstraintViolationException(violations);
  }

  // Validate Stream properties
  Set<ConstraintViolation<StreamProperties>> streamPropertyViolations =
      validator.validate(getStream());
  if (!streamPropertyViolations.isEmpty()) {
    throw new ConstraintViolationException(streamPropertyViolations);
  }

  // Validate Stream Options
  Set<ConstraintViolation<FeatureStreamOptions>> featureStreamOptionsViolations =
      validator.validate(getStream().getOptions());
  if (!featureStreamOptionsViolations.isEmpty()) {
    throw new ConstraintViolationException(featureStreamOptionsViolations);
  }

  // Validate JobProperties
  Set<ConstraintViolation<JobProperties>> jobPropertiesViolations = validator.validate(getJobs());
  if (!jobPropertiesViolations.isEmpty()) {
    throw new ConstraintViolationException(jobPropertiesViolations);
  }

  // Validate MetricsProperties
  if (getJobs().getMetrics().isEnabled()) {
    Set<ConstraintViolation<MetricsProperties>> jobMetricViolations =
        validator.validate(getJobs().getMetrics());
    if (!jobMetricViolations.isEmpty()) {
      throw new ConstraintViolationException(jobMetricViolations);
    }
    // Additional custom check for hostname value because there is no built-in Spring annotation
    // to validate the value is a DNS resolvable hostname or an IP address.
    try {
      //noinspection ResultOfMethodCallIgnored
      InetAddress.getByName(getJobs().getMetrics().getHost());
    } catch (UnknownHostException e) {
      throw new IllegalArgumentException(
          "Invalid config value for feast.jobs.metrics.host: "
              + getJobs().getMetrics().getHost()
              + ". Make sure it is a valid IP address or DNS hostname e.g. localhost or 10.128.10.40. Error detail: "
              + e.getMessage());
    }
  }
}
 
Example 20
Source File: LoginHandler.java    From drftpd with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Syntax: IDNT ident@ip:dns
 * Returns nothing on success.
 */
public CommandResponse doIDNT(CommandRequest request) {
    BaseFtpConnection conn = (BaseFtpConnection) request.getSession();
    request.getSession().setObject(BaseFtpConnection.FAILEDLOGIN, true);

    if (request.getSession().getObject(BaseFtpConnection.ADDRESS, null) != null) {
        logger.error("Multiple IDNT commands");
        request.getSession().setObject(BaseFtpConnection.FAILEDREASON, "IDNT Multiple");
        return new CommandResponse(530, "Multiple IDNT commands");
    }

    if (!GlobalContext.getConfig().getBouncerIps().contains(conn.getClientAddress())) {
        logger.warn("IDNT from non-bnc");
        request.getSession().setObject(BaseFtpConnection.FAILEDREASON, "IDNT Non-BNC");
        return StandardCommandManager.genericResponse("RESPONSE_530_ACCESS_DENIED");
    }

    String arg = request.getArgument();
    int pos1 = arg.indexOf('@');

    if (pos1 == -1) {
        request.getSession().setObject(BaseFtpConnection.FAILEDREASON, "IDNT Syntax");
        return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
    }

    int pos2 = arg.indexOf(':', pos1 + 1);

    if (pos2 == -1) {
        request.getSession().setObject(BaseFtpConnection.FAILEDREASON, "IDNT Syntax");
        return StandardCommandManager.genericResponse("RESPONSE_501_SYNTAX_ERROR");
    }

    try {
        request.getSession().setObject(BaseFtpConnection.ADDRESS, InetAddress.getByName(arg.substring(pos1 + 1, pos2)));
        request.getSession().setObject(BaseFtpConnection.IDENT, arg.substring(0, pos1));
    } catch (UnknownHostException e) {
        logger.info("Invalid hostname passed to IDNT", e);
        request.getSession().setObject(BaseFtpConnection.FAILEDREASON, "IDNT Failed");
        //this will most likely cause control connection to become unsynchronized
        //but give error anyway, this error is unlikely to happen
        return new CommandResponse(501, "IDNT FAILED: " + e.getMessage());
    }

    // bnc doesn't expect any reply
    request.getSession().setObject(BaseFtpConnection.FAILEDLOGIN, false);
    return null;
}