项目:jdk8u-jdk
文件:SnmpEngineImpl.java
/**
* Constructor. A Local Configuration Datastore is passed to the engine. It will be used to store and retrieve data (engine Id,engine boots).
* <P> WARNING : The SnmpEngineId is computed as follow:
* <ul>
* <li> If an lcd file is provided containing the property "localEngineID",this property value is used.</li>.
* <li> If not,if the passed engineID is not null,this engine ID is used.</li>
* <li> If not,a time based engineID is computed.</li>
* </ul>
* This constructor should be called by an <CODE>SnmpEngineFactory</CODE>. Don't call it directly.
* @param fact The factory used to instantiate this engine.
* @param lcd The local configuration datastore.
* @param engineid The engine ID to use. If null is provided,an SnmpEngineId is computed using the current time.
* @throws UnkNownHostException Exception thrown,if the host name located in the property "localEngineID" is invalid.
*/
public SnmpEngineImpl(SnmpEngineFactory fact,SnmpLcd lcd,SnmpEngineId engineid) throws UnkNownHostException {
init(lcd,fact);
initEngineID();
if(this.engineid == null) {
if(engineid != null)
this.engineid = engineid;
else
this.engineid = SnmpEngineId.createEngineId();
}
lcd.storeEngineId(this.engineid);
if (SNMP_LOGGER.isLoggable(Level.FINER)) {
SNMP_LOGGER.logp(Level.FINER,SnmpEngineImpl.class.getName(),"SnmpEngineImpl(SnmpEngineFactory,SnmpLcd,SnmpEngineId)","LOCAL ENGINE ID: " + this.engineid);
}
}
项目:uDetective
文件:ElasticSearchDataSource.java
@Override
public TransportClient connect() {
Settings settings = Settings.builder()
.put("cluster.name","elasticsearch")
.put("client.transport.sniff",true).build();
try {
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("event-apptst01.as.it.ubc.ca"),9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("event-apptst02.as.it.ubc.ca"),9300));
} catch (UnkNownHostException uhe) {
logger.error(uhe.toString());
}
return client;
}
项目:java-coap
文件:ServerIntegrationTest.java
@Test
public void requestWithAccept() throws UnkNownHostException,IOException,InterruptedException,Exception {
CoapServer cnn = CoapServerBuilder.newBuilder().transport(0).build();
cnn.start();
CoapPacket request = new CoapPacket(new InetSocketAddress("127.0.0.1",SERVER_PORT));
request.setMethod(Method.GET);
request.headers().setUriPath("/test2");
request.setMessageId(1647);
short[] acceptList = {MediaTypes.CT_APPLICATION_JSON};
request.headers().setAccept(acceptList);
assertEquals(Code.C406_NOT_ACCEPTABLE,cnn.makeRequest(request).get().getCode());
cnn.stop();
}
项目:https-github.com-apache-zookeeper
文件:StaticHostProviderTest.java
private Collection<InetSocketAddress> getServerAddresses(byte size) {
if (precomputedLists.containsKey(size)) return precomputedLists.get(size);
ArrayList<InetSocketAddress> list = new ArrayList<InetSocketAddress>(
size);
while (size > 0) {
try {
list.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10,10,size}),1234 + size));
} catch (UnkNownHostException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
--size;
}
precomputedLists.put(size,list);
return list;
}
项目:virtualview_tools
文件:Log.java
/**
* Handy function to get a loggable stack trace from a Throwable
* @param tr An exception to log
*/
public static String getStackTraceString(Throwable tr) {
if (tr == null) {
return "";
}
// This is to reduce the amount of log spew that apps do in the non-error
// condition of the network being unavailable.
Throwable t = tr;
while (t != null) {
if (t instanceof UnkNownHostException) {
return "";
}
t = t.getCause();
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
tr.printstacktrace(pw);
pw.flush();
return sw.toString();
}
/**
* 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,Ip4Address.valueOf("10.226.165.164"),Ip4Address.valueOf("1.1.1.1"),2,topologyForDeviceAndLink);
ospfNbr.setState(OspfNeighborState.FULL);
ospfNbr.setNeighborId(Ip4Address.valueOf("10.226.165.100"));
ospfInterface = new OspfInterfaceImpl();
ospfInterface.setIpAddress(Ip4Address.valueOf("10.226.165.164"));
ospfInterface.setIpNetworkMask(Ip4Address.valueOf("255.255.255.255"));
ospfInterface.setBdr(Ip4Address.valueOf("111.111.111.111"));
ospfInterface.setDr(Ip4Address.valueOf("111.111.111.111"));
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;
}
项目:MVVMArms
文件:ResponseErrorListenerImpl.java
@Override
public void handleResponseError(Context context,Throwable t) {
//用来提供处理所有错误的监听
//rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
Timber.tag("Catch-Error").w(t.getMessage());
//这里不光是只能打印错误,还可以根据不同的错误作出不同的逻辑处理
String msg = "未知错误";
if (t instanceof UnkNownHostException) {
msg = "网络不可用";
} else if (t instanceof SocketTimeoutException) {
msg = "请求网络超时";
} else if (t instanceof HttpException) {
HttpException httpException = (HttpException) t;
msg = convertStatusCode(httpException);
} else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException) {
msg = "数据解析错误";
}
UiUtils.snackbarText(msg);
}
@Override
public void decode() {
try {
this.magic = this.checkMagic();
this.serverGuid = this.readLong();
this.clientAddress = this.readAddress();
this.maximumTransferUnit = this.readUShort();
this.encryptionEnabled = this.readBoolean();
} catch (UnkNownHostException e) {
this.Failed = true;
this.magic = false;
this.serverGuid = 0;
this.clientAddress = null;
this.maximumTransferUnit = 0;
this.encryptionEnabled = false;
this.clear();
}
}
/**
* Retrieve the name of the current host. Multihomed hosts may restrict the
* hostname lookup to a specific interface and nameserver with {@link
* org.apache.hadoop.fs.CommonConfigurationKeysPublic#HADOOP_Security_DNS_INTERFACE_KEY}
* and {@link org.apache.hadoop.fs.CommonConfigurationKeysPublic#HADOOP_Security_DNS_NAMESERVER_KEY}
*
* @param conf Configuration object. May be null.
* @return
* @throws UnkNownHostException
*/
static String getLocalHostName(@Nullable Configuration conf)
throws UnkNownHostException {
if (conf != null) {
String dnsInterface = conf.get(HADOOP_Security_DNS_INTERFACE_KEY);
String nameServer = conf.get(HADOOP_Security_DNS_NAMESERVER_KEY);
if (dnsInterface != null) {
return DNS.getDefaultHost(dnsInterface,nameServer,true);
} else if (nameServer != null) {
throw new IllegalArgumentException(HADOOP_Security_DNS_NAMESERVER_KEY +
" requires " + HADOOP_Security_DNS_INTERFACE_KEY + ". Check your" +
"configuration.");
}
}
// Fallback to querying the default hostname as we did before.
return InetAddress.getLocalHost().getCanonicalHostName();
}
项目:rskj
文件:PeerScoringManagerTest.java
@Test
public void recordEventUsingNodeIDAndAddress() throws UnkNownHostException {
NodeID id = generateNodeID();
InetAddress address = generateIPAddressV4();
PeerScoringManager manager = createPeerScoringManager();
manager.recordEvent(id,address,EventType.INVALID_BLOCK);
PeerScoring result = manager.getPeerScoring(id);
Assert.assertNotNull(result);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(1,result.getEventCounter(EventType.INVALID_BLOCK));
Assert.assertEquals(1,result.getTotalEventCounter());
result = manager.getPeerScoring(address);
Assert.assertNotNull(result);
Assert.assertFalse(result.isEmpty());
Assert.assertEquals(1,result.getTotalEventCounter());
}
项目:africastalking-android
文件:NetworkUtils.java
public static boolean isBehindNAT() {
String address = determineLocalIp();
try {
// 10.x.x.x | 192.168.x.x | 172.16.x.x .. 172.19.x.x
byte[] d = InetAddress.getByName(address).getAddress();
if ((d[0] == 10) ||
(((0x000000FF & d[0]) == 172) &&
((0x000000F0 & d[1]) == 16)) ||
(((0x000000FF & d[0]) == 192) &&
((0x000000FF & d[1]) == 168))) {
return true;
}
} catch (UnkNownHostException e) {
Log.e("isBehindAT()" + address,e.getMessage() + "");
}
return false;
}
/**
* Constructor. A Local Configuration Datastore is passed to the engine. It will be used to store and retrieve data (engine ID,a time based engineID is computed.</li>
* </ul>
* When no configuration nor java property is set for the engine ID value,a unique time based engine ID will be generated.
* This constructor should be called by an <CODE>SnmpEngineFactory</CODE>. Don't call it directly.
* @param fact The factory used to instantiate this engine.
* @param lcd The local configuration datastore.
*/
public SnmpEngineImpl(SnmpEngineFactory fact,SnmpLcd lcd) throws UnkNownHostException {
init(lcd,fact);
initEngineID();
if(engineid == null)
engineid = SnmpEngineId.createEngineId();
lcd.storeEngineId(engineid);
if (SNMP_LOGGER.isLoggable(Level.FINER)) {
SNMP_LOGGER.logp(Level.FINER,SnmpLcd)","LOCAL ENGINE ID: " + engineid + " / " +
"LOCAL ENGINE NB BOOTS: " + boot + " / " +
"LOCAL ENGINE START TIME: " + getEngineTime());
}
}
项目:activiti-cloud-examples
文件:EnglishCampaign.java
@Scheduled(fixedrate = 60000)
public void logExecutions() throws UnkNownHostException {
logger.info("There are "+runtimeService.createExecutionQuery().count()+" process executions in RB instance on host "+ InetAddress.getLocalHost().getHostName());
logger.info("There are "+runtimeService.createProcessInstanceQuery().processDeFinitionKey("launchCampaign").count()+" launchCampaign process instances in RB instance on host "+ InetAddress.getLocalHost().getHostName());
logger.info("There are "+runtimeService.createProcessInstanceQuery().processDeFinitionKey("tweet-prize").count()+" tweet-prize process instances in RB instance on host "+ InetAddress.getLocalHost().getHostName());
logger.info("There are "+taskService.createTaskQuery().count()+" tasks in RB instance on host "+ InetAddress.getLocalHost().getHostName());
/* List<ProcessInstance> procInstanceList = runtimeService.createProcessInstanceQuery().orderByProcessInstanceId().asc().includeProcessVariables().list();
for(ProcessInstance instance:procInstanceList) {
logger.debug("Inspecting open process instance with id " + instance.getProcessInstanceId() + " for " + instance.getProcessDeFinitionKey() + " started at " + instance.getStartTime());
logger.debug("Instance suspended? " + instance.isSuspended()+" Instance ended? " + instance.isEnded());
if (instance.getProcessVariables() != null && instance.getProcessVariables().size() > 0) {
for (String varKey : instance.getProcessVariables().keySet()) {
logger.debug(instance.getProcessInstanceId()+" Variable - " + varKey + " - " + instance.getProcessVariables().get(varKey));
}
}
}
List<Execution> processExecutions = runtimeService.createExecutionQuery().list();
for(Execution execution:processExecutions){
logger.debug("Inspecting open process execution with id " + execution.getId() + " for proc inst " + execution.getRootProcessInstanceId());
logger.debug("ParentId " + execution.getParentId()+" SuperExecutionId "+execution.getSuperExecutionId());
logger.debug("Execution suspended? " + execution.isSuspended()+" Execution ended? " + execution.isEnded());
}*/
}
项目:JWaves
文件:RxNodeErrorHandlingCallAdapterFactory.java
private Throwable asRetrofitException(Throwable throwable) {
if (throwable instanceof SocketTimeoutException) {
return new ServerNotAvailableException();
} else if (throwable instanceof UnkNownHostException) {
return new NoInternetConnectionException();
} else if (throwable instanceof HttpException) {
String url;
HttpException httpException = (HttpException) throwable;
if (httpException.response() != null) {
url = httpException.response().raw().request().url().toString();
ResponseBody body;
if (httpException.response().isSuccessful())
body = httpException.response().raw().body();
else
body = httpException.response().errorBody();
try {
ErrorNodeResponse error = parseNodeError(body);
return new ApiNodeException(url,httpException.code(),error,httpException.getMessage());
} catch (Throwable _ignore) {
_ignore.printstacktrace();
}
}
}
return throwable;
}
项目:CrawlerSYS
文件:CrawlerServlet.java
/**
* Initialization of the servlet. <br>
*
* @throws servletexception if an error occurs
*/
public void init() throws servletexception {
String file = this.getServletContext().getRealPath(this.getinitParameter("log4j"));
//从web.xml配置读取,名字一定要和web.xml配置一致
if(file != null){
PropertyConfigurator.configure(file);
}
// Put your code here
new CrawlerServer(DefaultConfig.serverPort).start();
try {
new WebSocket(DefaultConfig.socketPort).start();
} catch (UnkNownHostException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
}
项目:lams
文件:HttpWebResponse.java
private void readResponseHeader( HttpURLConnection connection ) throws IOException {
if (!needStatusWorkaround()) {
_responseCode = connection.getResponseCode();
_responseMessage = connection.getResponseMessage();
} else {
if (connection.getHeaderField(0) == null) throw new UnkNownHostException( connection.getURL().toExternalForm() );
StringTokenizer st = new StringTokenizer( connection.getHeaderField(0) );
st.nextToken();
if (!st.hasMoretokens()) {
_responseCode = HttpURLConnection.HTTP_OK;
_responseMessage = "OK";
} else try {
_responseCode = Integer.parseInt( st.nextToken() );
_responseMessage = getRemainingTokens( st );
} catch (NumberFormatException e) {
_responseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
_responseMessage = "Cannot parse response header";
}
}
}
项目:gitplex-mit
文件:GitPlex.java
public String guessServerUrl() {
String hostName;
try {
hostName = InetAddress.getLocalHost().getHostName();
} catch (UnkNownHostException e) {
throw new RuntimeException(e);
}
String serverUrl;
if (serverConfig.getHttpPort() != 0)
serverUrl = "http://" + hostName + ":" + serverConfig.getHttpPort();
else
serverUrl = "https://" + hostName + ":" + serverConfig.getSslConfig().getPort();
return StringUtils.stripEnd(serverUrl,"/");
}
项目:hadoop
文件:AmIpFilter.java
protected Set<String> getProxyAddresses() throws servletexception {
long Now = System.currentTimeMillis();
synchronized(this) {
if(proxyAddresses == null || (lastUpdate + updateInterval) >= Now) {
proxyAddresses = new HashSet<>();
for (String proxyHost : proxyHosts) {
try {
for(InetAddress add : InetAddress.getAllByName(proxyHost)) {
if (LOG.isDebugEnabled()) {
LOG.debug("proxy address is: {}",add.getHostAddress());
}
proxyAddresses.add(add.getHostAddress());
}
lastUpdate = Now;
} catch (UnkNownHostException e) {
LOG.warn("Could not locate {} - skipping",proxyHost,e);
}
}
if (proxyAddresses.isEmpty()) {
throw new servletexception("Could not locate any of the proxy hosts");
}
}
return proxyAddresses;
}
}
项目:jdk8u-jdk
文件:NTLMAuthentication.java
private void init0() {
hostname = java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<String>() {
public String run() {
String localhost;
try {
localhost = InetAddress.getLocalHost().getHostName().toupperCase();
} catch (UnkNownHostException e) {
localhost = "localhost";
}
return localhost;
}
});
int x = hostname.indexOf ('.');
if (x != -1) {
hostname = hostname.substring (0,x);
}
}
项目:tifoon
文件:ReflectionObjectTreeAwareTest.java
@Test
public void testTracePathFromHost() throws UnkNownHostException {
final Port port1 = Port.from(Protocol.TCP,23);
final Port port2 = Port.from(Protocol.UDP,53);
final Map<InetAddress,List<Port>> inetAddressportMap = new HashMap<>();
inetAddressportMap.put(InetAddress.getByName("1.5.3.6"),Collections.singletonList(port1));
inetAddressportMap.put(InetAddress.getByName("3.88.7.5"),Collections.singletonList(port2));
final NetworkResult networkResult1 = new NetworkResult("network1",true,Collections.EMPTY_MAP);
final NetworkResult networkResult2 = new NetworkResult("network2",inetAddressportMap);
final List<NetworkResult> networkResults = Arrays.asList(networkResult1,networkResult2);
final PortScannerResult portScannerResult = new PortScannerResult(UUID.randomUUID().toString(),PortScannerStatus.DONE,Collections.EMPTY_LIST,"",networkResults);
final List<ObjectTreeAware> path = portScannerResult.traceObjectPath(networkResult2.getopenHosts().get("3.88.7.5"));
Java6Assertions.assertthat(path).as("object path from host 3.88.7.5 to root").containsExactly(
networkResult2,portScannerResult);
}
项目:QDrill
文件:ServiceEngine.java
public DrillbitEndpoint start() throws DrillbitStartupException,UnkNownHostException{
int userPort = userServer.bind(config.getInt(ExecConstants.INITIAL_USER_PORT),allowPortHunting);
String address = useIP ? InetAddress.getLocalHost().getHostAddress() : InetAddress.getLocalHost().getCanonicalHostName();
DrillbitEndpoint partialEndpoint = DrillbitEndpoint.newBuilder()
.setAddress(address)
//.setAddress("localhost")
.setUserPort(userPort)
.build();
partialEndpoint = controller.start(partialEndpoint);
return dataPool.start(partialEndpoint);
}
项目:fuck_zookeeper
文件:StaticHostProvider.java
/**
* Constructs a SimpleHostSet.
*
* @param serverAddresses
* possibly unresolved ZooKeeper server addresses
* @throws UnkNownHostException
* @throws IllegalArgumentException
* if serverAddresses is empty or resolves to an empty list
*/
public StaticHostProvider(Collection<InetSocketAddress> serverAddresses)
throws UnkNownHostException {
for (InetSocketAddress address : serverAddresses) {
InetAddress ia = address.getAddress();
InetAddress resolvedAddresses[] = InetAddress.getAllByName((ia!=null) ? ia.getHostAddress():
address.getHostName());
for (InetAddress resolvedAddress : resolvedAddresses) {
// If hostName is null but the address is not,we can tell that
// the hostName is an literal IP address. Then we can set the host string as the hostname
// safely to avoid reverse DNS lookup(???).
// As far as i kNow,the only way to check if the hostName is null is use toString().
// Both the two implementations of InetAddress are final class,so we can trust the return value of
// the toString() method.
if (resolvedAddress.toString().startsWith("/")
&& resolvedAddress.getAddress() != null) {
this.serverAddresses.add(
new InetSocketAddress(InetAddress.getByAddress(
address.getHostName(),resolvedAddress.getAddress()),address.getPort()));
} else {
this.serverAddresses.add(new InetSocketAddress(resolvedAddress.getHostAddress(),address.getPort()));
}
}
}
if (this.serverAddresses.isEmpty()) {
throw new IllegalArgumentException(
"A HostProvider may not be empty!");
}
Collections.shuffle(this.serverAddresses);
}
@Before
public void setUp() {
groupId = new Identifier<Group>(1L);
groupId2 = new Identifier<Group>(2L);
group = new Group(groupId,"the-ws-group-name");
group2 = new Group(groupId2,"the-ws-group-name-2");
try {
powermockito.mockStatic(JwalaUtils.class);
powermockito.when(JwalaUtils.getHostAddress("testServer")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
powermockito.when(JwalaUtils.getHostAddress("testServer2")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
}catch (UnkNownHostException ex){
ex.printstacktrace();
}
when(Config.mockApplication.getId()).thenReturn(new Identifier<Application>(1L));
when(Config.mockApplication.getWarPath()).thenReturn("the-ws-group-name/jwala-1.0.war");
when(Config.mockApplication.getName()).thenReturn("jwala 1.0");
when(Config.mockApplication.getGroup()).thenReturn(group);
when(Config.mockApplication.getWebAppContext()).thenReturn("/jwala");
when(Config.mockApplication.isSecure()).thenReturn(true);
when(Config.mockApplication2.getId()).thenReturn(new Identifier<Application>(2L));
when(Config.mockApplication2.getWarPath()).thenReturn("the-ws-group-name-2/jwala-1.1.war");
when(Config.mockApplication2.getName()).thenReturn("jwala 1.1");
when(Config.mockApplication2.getGroup()).thenReturn(group2);
when(Config.mockApplication2.getWebAppContext()).thenReturn("/jwala");
when(Config.mockApplication2.isSecure()).thenReturn(false);
applications2.add(Config.mockApplication);
applications2.add(Config.mockApplication2);
ByteBuffer buf = java.nio.ByteBuffer.allocate(2); // 2 byte file
buf.asShortBuffer().put((short) 0xc0de);
uploadedFile = new ByteArrayInputStream(buf.array());
SshConfiguration mockSshConfig = mock(SshConfiguration.class);
sshConfig = mock(SshConfig.class);
when(mockSshConfig.getUserName()).thenReturn("mockUser");
when(sshConfig.getSshConfiguration()).thenReturn(mockSshConfig);
}
项目:FirefoxData-android
文件:SchemeSocketFactoryAdaptor.java
public Socket connectSocket(
final Socket sock,final InetSocketAddress remoteAddress,final InetSocketAddress localAddress,final HttpParams params) throws IOException,UnkNownHostException,ConnectTimeoutException {
final String host = remoteAddress.getHostName();
final int port = remoteAddress.getPort();
InetAddress local = null;
int localPort = 0;
if (localAddress != null) {
local = localAddress.getAddress();
localPort = localAddress.getPort();
}
return this.factory.connectSocket(sock,host,port,local,localPort,params);
}
@Bean
public TransportClient transportClient(Settings settings) {
TransportClient client = TransportClient.builder().settings(settings).build();
for (String ip : this.esProperties.getIps().split(Constants.COMMA)) {
try {
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(ip),this.esProperties.getPort()));
} catch (UnkNownHostException e) {
LOGGER.error("es集群主机名错误,ip: {}",ip);
}
}
return client;
}
项目:rskj
文件:PeerScoringManagerTest.java
@Test
public void invalidBlockGivesBadReputationToNode() throws UnkNownHostException {
NodeID id = generateNodeID();
PeerScoringManager manager = createPeerScoringManager();
manager.recordEvent(id,null,EventType.INVALID_BLOCK);
Assert.assertFalse(manager.hasGoodReputation(id));
Assert.assertNotEquals(0,manager.getPeerScoring(id).getTimeLostGoodReputation());
}
项目:incubator-servicecomb-java-chassis
文件:SSLSocketFactoryExt.java
@Override
public Socket createSocket(String host,int port,InetAddress localHost,int localPort) throws IOException,UnkNownHostException {
return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(host,localHost,localPort));
}
/**
* 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 specified.
* @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]);
int port = (addresssplit.length == 2 ? parseIntPassive(addresssplit[1]) : defaultPort);
if (port >= 0 && port <= 65535) {
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");
}
}
项目:guava-mock
文件:InetAddressesTest.java
public void testForStringIPv6input() throws UnkNownHostException {
String ipStr = "3ffe::1";
InetAddress ipv6Addr = null;
// Shouldn't hit DNS,because it's an IP string literal.
ipv6Addr = InetAddress.getByName(ipStr);
assertEquals(ipv6Addr,InetAddresses.forString(ipStr));
assertTrue(InetAddresses.isInetAddress(ipStr));
}
项目:elasticsearch_my
文件:IpRangeAggregatorTests.java
private static InetAddress randomIp(boolean v4) {
try {
if (v4) {
byte[] ipv4 = new byte[4];
random().nextBytes(ipv4);
return InetAddress.getByAddress(ipv4);
} else {
byte[] ipv6 = new byte[16];
random().nextBytes(ipv6);
return InetAddress.getByAddress(ipv6);
}
} catch (UnkNownHostException e) {
throw new AssertionError();
}
}
项目:datatree
文件:AbstractConverterSet.java
protected static final InetAddress toInetAddress(long number) {
ByteBuffer b8 = ByteBuffer.allocate(8);
b8.putLong(number);
try {
byte[] ipv4 = new byte[4];
System.arraycopy(b8.array(),ipv4,4);
return InetAddress.getByAddress(ipv4);
} catch (UnkNownHostException e) {
throw new IllegalArgumentException("Unable to convert \"" + number + "\" to InetAddress!");
}
}
项目:alfresco-repository
文件:AlfrescoLdapSSLSocketFactory.java
@Override
public Socket createSocket(String host,int port) throws IOException,UnkNownHostException
{
SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host,port);
addHostNameVerification(sslSocket);
return sslSocket;
}
private AclEntryImpl (AclEntryImpl i) throws UnkNownHostException {
setPrincipal(i.getPrincipal());
permlist = new Vector<Permission>();
commList = new Vector<String>();
for (Enumeration<String> en = i.communities(); en.hasMoreElements();){
addCommunity(en.nextElement());
}
for (Enumeration<Permission> en = i.permissions(); en.hasMoreElements();){
addPermission(en.nextElement());
}
if (i.isNegative()) setNegativePermissions();
}
项目:ait-platform
文件:AitTaskExcecutorBase.java
@Override
public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {
try {
serverPort = event.getEmbeddedServletContainer().getPort();
serverIp = AitLocalhostIpAddress.search().getHostAddress();
} catch (final UnkNownHostException e) {
e.printstacktrace();
}
}
项目:datatree
文件:AbstractConverterSet.java
项目:aos-FileCoreLibrary
文件:UniAddress.java
static NbtAddress lookupServerOrWorkgroup( String name,InetAddress svr )
throws UnkNownHostException {
Sem sem = new Sem( 2 );
int type = NbtAddress.isWINS( svr ) ? 0x1b : 0x1d;
QueryThread q1x = new QueryThread( sem,name,type,svr );
QueryThread q20 = new QueryThread( sem,0x20,svr );
q1x.setDaemon( true );
q20.setDaemon( true );
try {
synchronized( sem ) {
q1x.start();
q20.start();
while( sem.count > 0 && q1x.ans == null && q20.ans == null ) {
sem.wait();
}
}
} catch( InterruptedException ie ) {
throw new UnkNownHostException( name );
}
if( q1x.ans != null ) {
return q1x.ans;
} else if( q20.ans != null ) {
return q20.ans;
} else {
throw q1x.uhe;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。