下面列出了java.net.UnknownHostException#getMessage ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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());
}
}
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;
}
/**
* {@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;
}
@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());
}
}
/**
* 从运行机器获取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;
}
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;
}
/**
* 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;
}
/**
* 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());
}
}
/**
* 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;
}
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);
}
}
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());
}
}
private InetAddress getHostAddress() {
try {
return InetAddress.getLocalHost();
} catch (final UnknownHostException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
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());
}
}
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);
}
}
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);
}
}
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;
}
}
/**
* 指定したアドレス・ポートへ接続する, クライアントからの接続待ち中で無くても構わない
* @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;
}
protected InetAddress getLocalHost() {
try {
return InetAddress.getLocalHost();
}
catch (UnknownHostException ex) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
}
/**
* Syntax: IDNT [email protected]: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;
}
/**
* 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());
}
}
}