下面列出了org.apache.log4j.spi.ErrorCode#java.net.UnknownHostException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This method handles a connection error that was caused while connecting the gateway to the backend.
*
* @param error the connection error to be handled
* @return a new ConnectorException
*/
public static ConnectorException handleConnectionError(Throwable error) {
ConnectorException ce = null;
if (error instanceof UnknownHostException || error instanceof ConnectException || error instanceof NoRouteToHostException) {
ce = new ConnectorException("Unable to connect to backend", error); //$NON-NLS-1$
ce.setStatusCode(502); // BAD GATEWAY
} else if (error instanceof InterruptedIOException || error instanceof java.util.concurrent.TimeoutException) {
ce = new ConnectorException("Connection to backend terminated" + error.getMessage(), error); //$NON-NLS-1$
ce.setStatusCode(504); // GATEWAY TIMEOUT
}
if (ce != null) {
return ce;
} else {
return new ConnectorException(error.getMessage(), error);
}
}
@GetMapping(value="/getHostInfo",produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String getHostInfo(HttpServletRequest request,
HttpServletResponse response){
JSONObject jo = new JSONObject();
String path = request.getContextPath();
String basePath = null;
try {
InetAddress addr = InetAddress.getLocalHost();
basePath = request.getScheme()+"://"+addr.getHostAddress()+":"+request.getServerPort()+path+"/";
} catch (UnknownHostException e) {
basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
}
jo.put("host", basePath);
return jo.toString();
}
/**
* @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
* java.lang.String, int, java.net.InetAddress, int,
* org.apache.http.params.HttpParams)
*/
public Socket connectSocket(Socket sock, String host, int port,
InetAddress localAddress, int localPort, HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
if ((localAddress != null) || (localPort > 0)) {
// we need to bind explicitly
if (localPort < 0) {
localPort = 0; // indicates "any"
}
InetSocketAddress isa = new InetSocketAddress(localAddress,
localPort);
sslsock.bind(isa);
}
sslsock.connect(remoteAddress, connTimeout);
sslsock.setSoTimeout(soTimeout);
return sslsock;
}
public void start() throws TTransportException, UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(hostName);
TSSLTransportFactory.TSSLTransportParameters params =
new TSSLTransportFactory.TSSLTransportParameters();
params.setKeyStore(keyStore, keyStorePassword);
TServerSocket serverTransport;
serverTransport = TSSLTransportFactory.getServerSocket(port, clientTimeout, inetAddress, params);
AuthenticatorService.Processor<AuthenticatorServiceImpl> processor =
new AuthenticatorService.Processor<AuthenticatorServiceImpl>(
new AuthenticatorServiceImpl(thriftAuthenticatorService));
authenticationServer = new TThreadPoolServer(
new TThreadPoolServer.Args(serverTransport).processor(processor));
Thread thread = new Thread(new ServerRunnable(authenticationServer));
if (log.isDebugEnabled()) {
log.debug("Thrift Authentication Service started at ssl://" + hostName + ":" + port);
}
thread.start();
}
/**
* Parses a single String as an address and port and converts it to an
* <code>InetSocketAddress</code>.
*
* @param address
* the address to convert.
* @param defaultPort
* the default port to use if one is not.
* @return the parsed <code>InetSocketAddress</code>.
* @throws UnknownHostException
* if the address is in an invalid format or if the host cannot
* be found.
*/
public static InetSocketAddress parseAddress(String address, int defaultPort) throws UnknownHostException {
String[] addressSplit = address.split(":");
if (addressSplit.length == 1 || addressSplit.length == 2) {
InetAddress inetAddress = InetAddress.getByName(!addressSplit[0].startsWith("/") ? addressSplit[0]
: addressSplit[0].substring(1, addressSplit[0].length()));
int port = (addressSplit.length == 2 ? parseIntPassive(addressSplit[1]) : defaultPort);
if (port >= 0x0000 && port <= 0xFFFF) {
return new InetSocketAddress(inetAddress, port);
} else {
throw new UnknownHostException("Port number must be between 0-65535");
}
} else {
throw new UnknownHostException("Format must follow address:port");
}
}
public InetAddress[] getInetAddresses() {
if (addresses == null || addresses.length == 0)
return null;
ArrayList<InetAddress> ipAddrs = new ArrayList<>(addresses.length);
for (int i = 0; i < addresses.length; i++) {
try {
if ((addresses[i].addrType == Krb5.ADDRTYPE_INET) ||
(addresses[i].addrType == Krb5.ADDRTYPE_INET6)) {
ipAddrs.add(addresses[i].getInetAddress());
}
} catch (java.net.UnknownHostException e) {
// Should not happen since IP address given
return null;
}
}
InetAddress[] retVal = new InetAddress[ipAddrs.size()];
return ipAddrs.toArray(retVal);
}
@Override
public InetAddress[] getAllByName(String host) throws UnknownHostException {
// Always bypass Private DNS.
final List<InetAddress> addrs = Arrays.asList(
ResolvUtil.blockingResolveAllLocally(this, host));
// Ensure the address family of the first address is tried first.
LinkedHashMap<Class, InetAddress> addressByFamily = new LinkedHashMap<>();
addressByFamily.put(addrs.get(0).getClass(), addrs.get(0));
Collections.shuffle(addrs);
for (InetAddress addr : addrs) {
addressByFamily.put(addr.getClass(), addr);
}
return addressByFamily.values().toArray(new InetAddress[addressByFamily.size()]);
}
@Test
public void testBadSslConfiguration()
throws UnknownHostException {
Properties props = new Properties();
props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_INDEX_NAME, "test");
props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_INDEX_TYPE, "test");
props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_TYPEMAPPER_CLASS,
AvroGenericRecordTypeMapper.class.getCanonicalName());
props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_ID_MAPPING_ENABLED, "true");
props.setProperty(ElasticsearchWriterConfigurationKeys.ELASTICSEARCH_WRITER_SSL_ENABLED, "true");
Config config = ConfigFactory.parseProperties(props);
try {
new ElasticsearchTransportClientWriter(config);
Assert.fail("Writer should not be constructed");
}
catch (Exception e) {
}
}
/**
* Queries the given timeserver <code>hostname</code> and returns the time
* in milliseconds.
*
* @param hostname the timeserver to query
* @return the time in milliseconds or the current time of the system if an
* error occurs.
*/
protected static long getTime(String hostname) {
try {
NTPUDPClient timeClient = new NTPUDPClient();
timeClient.setDefaultTimeout(NTP_TIMEOUT);
InetAddress inetAddress = InetAddress.getByName(hostname);
TimeInfo timeInfo = timeClient.getTime(inetAddress);
return timeInfo.getReturnTime();
} catch (UnknownHostException uhe) {
logger.warn("the given hostname '{}' of the timeserver is unknown -> returning current sytem time instead",
hostname);
} catch (IOException ioe) {
logger.warn("couldn't establish network connection [host '{}'] -> returning current sytem time instead",
hostname);
}
return System.currentTimeMillis();
}
private void disconnect(Collection<DataTreeModification<Node>> changes) {
for (DataTreeModification<Node> change : changes) {
final InstanceIdentifier<Node> key = change.getRootPath().getRootIdentifier();
final DataObjectModification<Node> mod = change.getRootNode();
Node deleted = getRemoved(mod);
if (deleted != null) {
HwvtepGlobalAugmentation hgDeleted = deleted.augmentation(HwvtepGlobalAugmentation.class);
if (hgDeleted != null) {
try {
hcm.disconnect(hgDeleted);
hcm.stopConnectionReconciliationIfActive(key, hgDeleted);
} catch (UnknownHostException e) {
LOG.warn("Failed to disconnect HWVTEP Node", e);
}
}
}
}
}
/** Resets {@link #nextInetSocketAddress} to the first option. */
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
socketAddresses = null; // Clear the addresses. Necessary if getAllByName() below throws!
String socketHost;
if (proxy.type() == Proxy.Type.DIRECT) {
socketHost = uri.getHost();
socketPort = getEffectivePort(uri);
} else {
SocketAddress proxyAddress = proxy.address();
if (!(proxyAddress instanceof InetSocketAddress)) {
throw new IllegalArgumentException(
"Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
}
InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
socketHost = proxySocketAddress.getHostName();
socketPort = proxySocketAddress.getPort();
}
// Try each address for best behavior in mixed IPv4/IPv6 environments.
socketAddresses = dns.getAllByName(socketHost);
nextSocketAddressIndex = 0;
}
public static Socket createSocket(final SocketTask task, int timeout)
throws IOException, UnknownHostException, ConnectTimeoutException
{
try {
TimeoutController.execute(task, timeout);
} catch (TimeoutController.TimeoutException e) {
throw new ConnectTimeoutException(
"The host did not accept the connection within timeout of "
+ timeout + " ms");
}
Socket socket = task.getSocket();
if (task.exception != null) {
throw task.exception;
}
return socket;
}
private void execute(final Event event) {
final String fileContent = (String) event.getProperty(FILE_CONTENT);
Map<String, String> content = new HashMap<>();
content.put("bdmXml", fileContent);
try {
new ClientResource(String.format("http://%s:%s/bdm",
InetAddress.getByName(null).getHostAddress(),
InstanceScope.INSTANCE.getNode(BonitaStudioPreferencesPlugin.PLUGIN_ID)
.get(BonitaPreferenceConstants.DATA_REPOSITORY_PORT, "-1")))
.post(new JacksonRepresentation<Object>(content));
BonitaStudioLog.info("BDM has been publish into Data Repository service", UIDesignerPlugin.PLUGIN_ID);
} catch (ResourceException | UnknownHostException e) {
BonitaStudioLog.error("An error occured while publishing the BDM into Data Repository service", e);
}
}
@Test
public void testConnectDisconnect() throws UnknownHostException {
NetworkManager nodeA = new NetworkManager(new H2HDummyEncryption(), serializer, new TestFileConfiguration());
NetworkManager nodeB = new NetworkManager(new H2HDummyEncryption(), serializer, new TestFileConfiguration());
INetworkConfiguration netConfigA = NetworkConfiguration.createInitial("nodeA");
INetworkConfiguration netConfigB = NetworkConfiguration.create("nodeB", InetAddress.getLocalHost());
try {
nodeA.connect(netConfigA);
nodeB.connect(netConfigB);
assertTrue(nodeB.disconnect(false));
assertTrue(nodeB.connect(netConfigB));
} finally {
nodeA.disconnect(false);
nodeB.disconnect(false);
}
}
/**
* Applies this function to the given argument.
*
* @param observable the function argument
* @return the function result
*/
@Override
public Observable<?> apply(Observable<? extends Throwable> observable) {
return observable.flatMap(new Function<Throwable, ObservableSource<?>>() {
@Override
public ObservableSource<?> apply(Throwable throwable) {
//未连接网络直接返回异常
if (!NetworkUtil.isConnected(mContext)) {
return Observable.error(throwable);
}
//仅仅对连接失败相关错误进行重试
if (throwable instanceof ConnectException
|| throwable instanceof UnknownHostException
|| throwable instanceof SocketTimeoutException
|| throwable instanceof SocketException
|| throwable instanceof TimeoutException) {
if (++mRetryCount <= mRetryMaxTime) {
LoggerManager.e(TAG, "网络请求错误,将在 " + mRetryDelay + " ms后进行重试, 重试次数 " + mRetryCount + ";throwable:" + throwable);
return Observable.timer(mRetryDelay, TimeUnit.MILLISECONDS);
}
}
return Observable.error(throwable);
}
});
}
private RemotingCommand consumeMessageDirectly(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
final ConsumeMessageDirectlyResultRequestHeader requestHeader = (ConsumeMessageDirectlyResultRequestHeader)request
.decodeCommandCustomHeader(ConsumeMessageDirectlyResultRequestHeader.class);
request.getExtFields().put("brokerName", this.brokerController.getBrokerConfig().getBrokerName());
SelectMappedBufferResult selectMappedBufferResult = null;
try {
MessageId messageId = MessageDecoder.decodeMessageId(requestHeader.getMsgId());
selectMappedBufferResult = this.brokerController.getMessageStore().selectOneMessageByOffset(messageId.getOffset());
byte[] body = new byte[selectMappedBufferResult.getSize()];
selectMappedBufferResult.getByteBuffer().get(body);
request.setBody(body);
} catch (UnknownHostException e) {
} finally {
if (selectMappedBufferResult != null) {
selectMappedBufferResult.release();
}
}
return this.callConsumer(RequestCode.CONSUME_MESSAGE_DIRECTLY, request, requestHeader.getConsumerGroup(),
requestHeader.getClientId());
}
/**
* Utility for test method.
*/
private OspfInterfaceImpl createOspfInterface1() throws UnknownHostException {
ospfInterface = new OspfInterfaceImpl();
OspfAreaImpl ospfArea = new OspfAreaImpl();
OspfInterfaceChannelHandler ospfInterfaceChannelHandler = EasyMock.createMock(
OspfInterfaceChannelHandler.class);
ospfNbr = new OspfNbrImpl(ospfArea, ospfInterface, ip4Address5,
ip4Address6, 2, topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfNbr.setNeighborId(ip4Address7);
ospfInterface = new OspfInterfaceImpl();
ospfInterface.setIpAddress(ip4Address5);
ospfInterface.setIpNetworkMask(subnetAddress);
ospfInterface.setBdr(ip4Address4);
ospfInterface.setDr(ip4Address4);
ospfInterface.setHelloIntervalTime(20);
ospfInterface.setInterfaceType(2);
ospfInterface.setReTransmitInterval(2000);
ospfInterface.setMtu(6500);
ospfInterface.setRouterDeadIntervalTime(1000);
ospfInterface.setRouterPriority(1);
ospfInterface.setInterfaceType(1);
ospfInterface.addNeighbouringRouter(ospfNbr);
return ospfInterface;
}
private MpdMonitor() throws UnknownHostException, MPDConnectionException
{
Configuration config = Play.application().configuration();
String hostname = config.getString("mpd.hostname");
int port = config.getInt("mpd.port");
String password = config.getString("mpd.password");
int timeout = config.getInt("mpd.timeout", 10) * 1000;
Logger.info("Connecting to MPD");
mpd = new MPD(hostname, port, password, timeout);
monitor = new MPDStandAloneMonitor(mpd, 1000);
thread = new Thread(monitor);
thread.start();
}
@Override
public List<InetSocketAddress> getInetSocketAddresses(String itemName) {
List<InetSocketAddress> theList = new ArrayList<InetSocketAddress>();
ProtocolBindingConfig config = (ProtocolBindingConfig) bindingConfigs.get(itemName);
if (config != null) {
for (Command command : config.keySet()) {
InetSocketAddress anAddress = null;
try {
anAddress = new InetSocketAddress(InetAddress.getByName(config.get(command).getHost()),
Integer.parseInt(config.get(command).getPort()));
} catch (UnknownHostException e) {
logger.warn("Could not resolve the hostname {} for item {}", config.get(command).getHost(),
itemName);
}
theList.add(anAddress);
}
}
return theList;
}
static void validateQuorumConfigs(
List<Stage.ConfigIssue> issues,
Stage.Context context,
String hbaseName,
String zookeeperQuorum,
String zookeeperParentZNode,
int clientPort
) {
if (zookeeperQuorum == null || zookeeperQuorum.isEmpty()) {
issues.add(context.createConfigIssue(hbaseName, "zookeeperQuorum", Errors.HBASE_04));
} else {
List<String> zkQuorumList = Lists.newArrayList(Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.split(zookeeperQuorum));
for (String hostName : zkQuorumList) {
try {
InetAddress.getByName(hostName);
} catch (UnknownHostException ex) {
LOG.warn(Utils.format("Cannot resolve host: '{}' from zookeeper quorum '{}', error: '{}'",
hostName,
zookeeperQuorum,
ex
), ex);
issues.add(context.createConfigIssue(hbaseName, "zookeeperQuorum", Errors.HBASE_39, hostName));
}
}
}
if (zookeeperParentZNode == null || zookeeperParentZNode.isEmpty()) {
issues.add(context.createConfigIssue(hbaseName, "zookeeperBaseDir", Errors.HBASE_09));
}
if (clientPort == 0) {
issues.add(context.createConfigIssue(hbaseName, "clientPort", Errors.HBASE_13));
}
}
protected String buildTextMessage(Throwable t)
{
StringBuffer result = new StringBuffer();
String timeOfFailure = (new Date()).toString();
String hostName = null;
String ipAddress = null;
try
{
hostName = InetAddress.getLocalHost().getHostName();
ipAddress = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException uhe)
{
hostName = "unknown";
ipAddress = "unknown";
}
result.append("\nTime of failure: " + timeOfFailure);
result.append("\nHost where failure occurred: " + hostName + " (" + ipAddress + ")");
if (t != null)
{
result.append("\nRoot exception:");
result.append(renderExceptionStackAsText(t));
}
else
{
result.append("\nNo exception was provided.");
}
return(result.toString());
}
@Override
public Collection<InetAddress> resolveRemapped(String remappedHost) {
try {
Collection<InetAddress> addresses = Arrays.asList(InetAddress.getAllByName(remappedHost));
return addresses;
} catch (UnknownHostException e) {
return Collections.emptyList();
}
}
@BeforeClass
public void initClass() {
try {
jobScheduler = new SchedulerImpl(rxSession, InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
/** Same test but the client should bind to a local interface */
@Test
public void testFileCreationSetLocalInterface() throws IOException {
assumeTrue(System.getProperty("os.name").startsWith("Linux"));
// The mini cluster listens on the loopback so we can use it here
checkFileCreation("lo", false);
try {
checkFileCreation("bogus-interface", false);
fail("Able to specify a bogus interface");
} catch (UnknownHostException e) {
assertEquals("No such interface bogus-interface", e.getMessage());
}
}
/**
* Validate IP address format for a given string.
* @param ipString
* @return true if the given string is a valid IP, else false.
*/
private boolean isValidIP(String ipString) {
boolean ret = false;
if (ipString != null && !ipString.isEmpty()) {
try {
InetAddress.getByName(ipString);
ret = true;
}
catch (UnknownHostException e) {
// Stay silent
}
}
return ret;
}
public Address(String uriHost, int uriPort, SSLSocketFactory sslSocketFactory,
HostnameVerifier hostnameVerifier, OkAuthenticator authenticator, Proxy proxy,
List<String> transports) throws UnknownHostException {
if (uriHost == null) throw new NullPointerException("uriHost == null");
if (uriPort <= 0) throw new IllegalArgumentException("uriPort <= 0: " + uriPort);
if (authenticator == null) throw new IllegalArgumentException("authenticator == null");
if (transports == null) throw new IllegalArgumentException("transports == null");
this.proxy = proxy;
this.uriHost = uriHost;
this.uriPort = uriPort;
this.sslSocketFactory = sslSocketFactory;
this.hostnameVerifier = hostnameVerifier;
this.authenticator = authenticator;
this.transports = Util.immutableList(transports);
}
@Test
public void saveAll_NumericArray_Test() throws SQLException, UnknownHostException {
// Create the Entity to insert:
ArrayEntity entity = new ArrayEntity();
entity.bigDecimalArray = Arrays.asList(
new BigDecimal("210000.00011234567"),
new BigDecimal("310000.00011234567")
);
testArrayInternal("col_numeric_array", entity, entity.bigDecimalArray, x -> x);
}
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(JeecgSystemApplication.class, args);
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
log.info("\n----------------------------------------------------------\n\t" +
"Application Jeecg-Boot is running! Access URLs:\n\t" +
"Local: \t\thttp://localhost:" + port + "/\n\t" +
"External: \thttp://" + ip + ":" + port + "/\n\t" +
"Swagger-UI: \t\thttp://" + ip + ":" + port + "/doc.html\n" +
"----------------------------------------------------------");
}
/**
* Test reading of input/holding registers, uses valuetype=int16
*/
@Test
public void testReadRegistersInt16()
throws InterruptedException, UnknownHostException, BindingConfigParseException, ConfigurationException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Modbus server ("modbus slave") has input registers
addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(2));
addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(-4));
addRegisterMethod.invoke(spi, constructRegisterInt.newInstance(99));
binding = new ModbusBinding();
binding.updated(addSlave(newLongPollBindingConfig(), SLAVE_NAME, type, ModbusBindingProvider.VALUE_TYPE_INT16,
nonZeroOffset ? 1 : 0, 2));
configureNumberItemBinding(2, SLAVE_NAME, 0);
binding.execute();
// Give the system some time to make the expected connections & requests
waitForConnectionsReceived(1);
waitForRequests(1);
verify(eventPublisher, never()).postCommand(null, null);
verify(eventPublisher, never()).sendCommand(null, null);
if (nonZeroOffset) {
verify(eventPublisher).postUpdate("Item1", new DecimalType(-4));
verify(eventPublisher).postUpdate("Item2", new DecimalType(99));
} else {
verify(eventPublisher).postUpdate("Item1", new DecimalType(2));
verify(eventPublisher).postUpdate("Item2", new DecimalType(-4));
}
verifyNoMoreInteractions(eventPublisher);
}
private void setupWSConnectionManager() {
try {
WSConnectionManager.setupInstance(WEB_SOCKET_PORT);
} catch (UnknownHostException e) {
//Crashlytics.logException(e);
//e.printStackTrace();
//Log.e(TAG,e.getMessage());
}
}