Java Code Examples for java.net.UnknownHostException

The following are top voted examples for showing how to use java.net.UnknownHostException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jdk8u-jdk   File: SnmpEngineImpl.java   View source code 7 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Project: uDetective   File: ElasticSearchDataSource.java   View source code 7 votes vote down vote up
@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;
}
 
Example 3
Project: java-coap   File: ServerIntegrationTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 4
Project: https-github.com-apache-zookeeper   File: StaticHostProviderTest.java   View source code 6 votes vote down vote up
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, 10, size}), 1234 + size));
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        --size;
    }
    precomputedLists.put(size, list);
    return list;
}
 
Example 5
Project: virtualview_tools   File: Log.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Project: athena   File: OspfInterfaceImplTest.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 7
Project: MVVMArms   File: ResponseErrorListenerImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: BedrockProxy   File: OpenConnectionResponseTwo.java   View source code 6 votes vote down vote up
@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();
    }
}
 
Example 9
Project: hadoop-oss   File: SecurityUtil.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 10
Project: rskj   File: PeerScoringManagerTest.java   View source code 6 votes vote down vote up
@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.getEventCounter(EventType.INVALID_BLOCK));
    Assert.assertEquals(1, result.getTotalEventCounter());
}
 
Example 11
Project: africastalking-android   File: NetworkUtils.java   View source code 6 votes vote down vote up
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;
}
 
Example 12
Project: OpenJSharp   File: SnmpEngineImpl.java   View source code 6 votes vote down vote up
/**
 * 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, 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, SnmpEngineImpl.class.getName(),
                "SnmpEngineImpl(SnmpEngineFactory,SnmpLcd)",
                "LOCAL ENGINE ID: " + engineid + " / " +
                "LOCAL ENGINE NB BOOTS: " + boot + " / " +
                "LOCAL ENGINE START TIME: " + getEngineTime());
    }
}
 
Example 13
Project: activiti-cloud-examples   File: EnglishCampaign.java   View source code 6 votes vote down vote up
@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());
        }*/
    }
 
Example 14
Project: JWaves   File: RxNodeErrorHandlingCallAdapterFactory.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: CrawlerSYS   File: CrawlerServlet.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 16
Project: lams   File: HttpWebResponse.java   View source code 6 votes vote down vote up
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";
        }
    }
}
 
Example 17
Project: gitplex-mit   File: GitPlex.java   View source code 6 votes vote down vote up
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, "/");
}
 
Example 18
Project: hadoop   File: AmIpFilter.java   View source code 6 votes vote down vote up
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;
  }
}
 
Example 19
Project: jdk8u-jdk   File: NTLMAuthentication.java   View source code 6 votes vote down vote up
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);
        }
    }
 
Example 20
Project: tifoon   File: ReflectionObjectTreeAwareTest.java   View source code 6 votes vote down vote up
@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", true, inetAddressPortMap);

    final List<NetworkResult> networkResults = Arrays.asList(networkResult1, networkResult2);

    final PortScannerResult portScannerResult = new PortScannerResult(UUID.randomUUID().toString(), 0, 0, 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);
}
 
Example 21
Project: joal   File: StaticClientFilesTester.java   View source code 5 votes vote down vote up
private static InetAddress createMockedINet6Address() {
    try {
        return InetAddress.getByName("fd2d:7212:4cd5:2f14:ffff:ffff:ffff:ffff");
    } catch (final UnknownHostException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 22
Project: QDrill   File: ServiceEngine.java   View source code 5 votes vote down vote up
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);
}
 
Example 23
Project: fuck_zookeeper   File: StaticHostProvider.java   View source code 5 votes vote down vote up
/**
 * 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);	
}
 
Example 24
Project: rskj   File: InetAddressTableTest.java   View source code 5 votes vote down vote up
@Test
public void removeUnknownAddress() throws UnknownHostException {
    InetAddressTable table = new InetAddressTable();
    InetAddress address = generateIPAddressV4();

    table.removeAddress(address);
    Assert.assertFalse(table.contains(address));
}
 
Example 25
Project: jwala   File: ApplicationServiceImplTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 26
Project: FirefoxData-android   File: SchemeSocketFactoryAdaptor.java   View source code 5 votes vote down vote up
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);
}
 
Example 27
Project: jwala   File: JwalaUtilsTest.java   View source code 5 votes vote down vote up
@Test
/**
 * Test IP from IP
 */
public void testIPv4Address() throws UnknownHostException{
    String host = Inet4Address.getLocalHost().getHostAddress();
    assertEquals(host,JwalaUtils.getHostAddress(host));
}
 
Example 28
Project: SkyEye   File: EsConfiguration.java   View source code 5 votes vote down vote up
@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;
}
 
Example 29
Project: dubbox-hystrix   File: NetUtils.java   View source code 5 votes vote down vote up
/**
 * @param hostName
 * @return ip address or hostName if UnknownHostException 
 */
public static String getIpByHost(String hostName) {
    try{
        return InetAddress.getByName(hostName).getHostAddress();
    }catch (UnknownHostException e) {
        return hostName;
    }
}
 
Example 30
Project: rskj   File: PeerScoringManagerTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 31
Project: incubator-servicecomb-java-chassis   File: SSLSocketFactoryExt.java   View source code 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port, InetAddress localHost,
    int localPort) throws IOException, UnknownHostException {
  return wrapSocket((SSLSocket) this.sslSocketFactory.createSocket(host,
      port,
      localHost,
      localPort));
}
 
Example 32
Project: BedrockProxy   File: RakNetUtils.java   View source code 5 votes vote down vote up
/**
 * 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");
    }
}
 
Example 33
Project: guava-mock   File: InetAddressesTest.java   View source code 5 votes vote down vote up
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));
}
 
Example 34
Project: elasticsearch_my   File: IpRangeAggregatorTests.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 35
Project: datatree   File: AbstractConverterSet.java   View source code 5 votes vote down vote up
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(), 0, ipv4, 0, 4);
		return InetAddress.getByAddress(ipv4);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Unable to convert \"" + number + "\" to InetAddress!");
	}
}
 
Example 36
Project: alfresco-repository   File: AlfrescoLdapSSLSocketFactory.java   View source code 5 votes vote down vote up
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException
{
    SSLSocket sslSocket = (SSLSocket) SSLSocketFactory.getDefault().createSocket(host, port);
    addHostNameVerification(sslSocket);
    return sslSocket;
}
 
Example 37
Project: OpenJSharp   File: AclEntryImpl.java   View source code 5 votes vote down vote up
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();
}
 
Example 38
Project: ait-platform   File: AitTaskExcecutorBase.java   View source code 5 votes vote down vote up
@Override
public void onApplicationEvent(final EmbeddedServletContainerInitializedEvent event) {
	try {
		serverPort = event.getEmbeddedServletContainer().getPort();
		serverIp = AitLocalhostIpAddress.search().getHostAddress();
	} catch (final UnknownHostException e) {
		e.printStackTrace();
	}
}
 
Example 39
Project: datatree   File: AbstractConverterSet.java   View source code 5 votes vote down vote up
protected static final InetAddress toInetAddress(byte[] from) {
	try {
		return InetAddress.getByAddress(from);
	} catch (UnknownHostException e) {
		throw new IllegalArgumentException("Unable to convert byte array to InetAddress!");
	}
}
 
Example 40
Project: aos-FileCoreLibrary   File: UniAddress.java   View source code 5 votes vote down vote up
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, null, svr );
    QueryThread q20 = new QueryThread( sem, name, 0x20, null, 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;
    }
}