Java Code Examples for java.net.InetSocketAddress#getHostName()

The following examples show how to use java.net.InetSocketAddress#getHostName() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: dubbox   File: RpcContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * is consumer side.
 * 
 * @return consumer side.
 */
public boolean isConsumerSide() {
    URL url = getUrl();
    if (url == null) {
        return false;
    }
    InetSocketAddress address = getRemoteAddress();
    if (address == null) {
        return false;
    }
    String host;
    if (address.getAddress() == null) {
        host = address.getHostName();
    } else {
        host = address.getAddress().getHostAddress();
    }
    return url.getPort() == address.getPort() && 
            NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host));
}
 
Example 2
Source Project: RDFS   File: CoronaAdmin.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Persists the state of the ClusterManager
 * @return 0 if successful.
 * @throws IOException
 */
private int persistState() throws IOException {
  // Get the current configuration
  CoronaConf conf = new CoronaConf(getConf());

  InetSocketAddress address = NetUtils.createSocketAddr(conf
    .getClusterManagerAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  ClusterManagerService.Client client = new ClusterManagerService.Client(
    new TBinaryProtocol(transport));

  try {
    transport.open();
    if (!client.persistState())  {
      System.err.println("Persisting Cluster Manager state failed. ");
    }
  } catch (TException e) {
    throw new IOException(e);
  }

  return 0;
}
 
Example 3
Source Project: phonegapbootcampsite   File: RouteSelector.java    License: MIT License 6 votes vote down vote up
/** 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;
}
 
Example 4
Source Project: rpcx-java   File: RpcContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * is provider side.
 *
 * @return provider side.
 */
public boolean isProviderSide() {
    URL url = getUrl();
    if (url == null) {
        return false;
    }
    InetSocketAddress address = getRemoteAddress();
    if (address == null) {
        return false;
    }
    String host;
    if (address.getAddress() == null) {
        host = address.getHostName();
    } else {
        host = address.getAddress().getHostAddress();
    }
    return url.getPort() != address.getPort() ||
            !NetUtils.filterLocalHost(url.getIp()).equals(NetUtils.filterLocalHost(host));
}
 
Example 5
Source Project: big-c   File: TaskAttemptImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void transition(TaskAttemptImpl taskAttempt, 
    TaskAttemptEvent evnt) {

  TaskAttemptContainerLaunchedEvent event =
    (TaskAttemptContainerLaunchedEvent) evnt;

  //set the launch time
  taskAttempt.launchTime = taskAttempt.clock.getTime();
  taskAttempt.shufflePort = event.getShufflePort();

  // register it to TaskAttemptListener so that it can start monitoring it.
  taskAttempt.taskAttemptListener
    .registerLaunchedTask(taskAttempt.attemptId, taskAttempt.jvmID);
  //TODO Resolve to host / IP in case of a local address.
  InetSocketAddress nodeHttpInetAddr = // TODO: Costly to create sock-addr?
      NetUtils.createSocketAddr(taskAttempt.container.getNodeHttpAddress());
  taskAttempt.trackerName = nodeHttpInetAddr.getHostName();
  taskAttempt.httpPort = nodeHttpInetAddr.getPort();
  taskAttempt.sendLaunchedEvents();
  taskAttempt.eventHandler.handle
      (new SpeculatorEvent
          (taskAttempt.attemptId, true, taskAttempt.clock.getTime()));
  //make remoteTask reference as null as it is no more needed
  //and free up the memory
  taskAttempt.remoteTask = null;
  
  //tell the Task that attempt has started
  taskAttempt.eventHandler.handle(new TaskTAttemptEvent(
      taskAttempt.attemptId, 
     TaskEventType.T_ATTEMPT_LAUNCHED));
}
 
Example 6
Source Project: nitmproxy   File: NitmProxyInitializer.java    License: MIT License 5 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
    Address clientAddress = new Address(address.getHostName(), address.getPort());
    channel.pipeline().addLast(
            master.proxyHandler(clientAddress),
            new SimpleChannelInboundHandler<Object>() {
                @Override
                protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o)
                        throws Exception {
                    LOGGER.info("[Client ({})] => Unhandled inbound: {}", clientAddress, o);
                }
            });
}
 
Example 7
Source Project: hadoop   File: TestContainerLauncher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ContainerLauncher
    createContainerLauncher(final AppContext context) {
  return new ContainerLauncherImpl(context) {

    @Override
    public ContainerManagementProtocolProxyData getCMProxy(
        String containerMgrBindAddr, ContainerId containerId)
        throws IOException {
      InetSocketAddress addr = NetUtils.getConnectAddress(server);
      String containerManagerBindAddr =
          addr.getHostName() + ":" + addr.getPort();
      Token token =
          tokenSecretManager.createNMToken(
            containerId.getApplicationAttemptId(),
            NodeId.newInstance(addr.getHostName(), addr.getPort()), "user");
      ContainerManagementProtocolProxy cmProxy =
          new ContainerManagementProtocolProxy(conf);
      ContainerManagementProtocolProxyData proxy =
          cmProxy.new ContainerManagementProtocolProxyData(
            YarnRPC.create(conf), containerManagerBindAddr, containerId,
            token);
      return proxy;
    }
  };

}
 
Example 8
@Override public final Permission getPermission() throws IOException {
  String hostName = getURL().getHost();
  int hostPort = Util.getEffectivePort(getURL());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
    hostName = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}
 
Example 9
Source Project: OkSocket   File: ConnectionManagerImpl.java    License: MIT License 5 votes vote down vote up
@Override
public ConnectionInfo getLocalConnectionInfo() {
    ConnectionInfo local = super.getLocalConnectionInfo();
    if (local == null) {
        if (isConnect()) {
            InetSocketAddress address = (InetSocketAddress) mSocket.getLocalSocketAddress();
            if (address != null) {
                local = new ConnectionInfo(address.getHostName(), address.getPort());
            }
        }
    }
    return local;
}
 
Example 10
@Override public void set(@NonNull String key, @NonNull InetSocketAddress address,
    @NonNull SharedPreferences.Editor editor) {
  String host = null;
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
    host = address.getHostString();
  } else {
    host = address.getHostName();
  }
  int port = address.getPort();
  editor.putString(key, host + ":" + port);
}
 
Example 11
Source Project: RDFS   File: CoronaClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the thrift client to communicate with the cluster manager
 * @return a thrift client initialized to talk to the cluster manager
 * @param conf The configuration.
 * @throws TTransportException
 */
private static ClusterManagerService.Client getCMSClient(CoronaConf conf)
  throws TTransportException {
  InetSocketAddress address = NetUtils.createSocketAddr(conf
      .getClusterManagerAddress());
  TFramedTransport transport = new TFramedTransport(
    new TSocket(address.getHostName(), address.getPort()));
  ClusterManagerService.Client client = new ClusterManagerService.Client(
      new TBinaryProtocol(transport));
  transport.open();
  return client;
}
 
Example 12
Source Project: tajo   File: TestQueryResultResource.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  InetSocketAddress address = testBase.getTestingCluster().getConfiguration().getSocketAddrVar(ConfVars.REST_SERVICE_ADDRESS);
  restServiceURI = new URI("http", null, address.getHostName(), address.getPort(), "/rest", null, null);
  sessionsURI = new URI(restServiceURI + "/sessions");
  queriesURI = new URI(restServiceURI + "/queries");
  restClient = ClientBuilder.newBuilder()
      .register(new GsonFeature(PlanGsonHelper.registerAdapters()))
      .register(LoggingFilter.class)
      .property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true)
      .property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true)
      .build();
}
 
Example 13
@Override public final Permission getPermission() throws IOException {
  String hostName = getURL().getHost();
  int hostPort = Util.getEffectivePort(getURL());
  if (usingProxy()) {
    InetSocketAddress proxyAddress = (InetSocketAddress) client.getProxy().address();
    hostName = proxyAddress.getHostName();
    hostPort = proxyAddress.getPort();
  }
  return new SocketPermission(hostName + ":" + hostPort, "connect, resolve");
}
 
Example 14
Source Project: big-c   File: DFSUtil.java    License: Apache License 2.0 5 votes vote down vote up
/** Create a URI from the scheme and address */
public static URI createUri(String scheme, InetSocketAddress address) {
  try {
    return new URI(scheme, null, address.getHostName(), address.getPort(),
        null, null, null);
  } catch (URISyntaxException ue) {
    throw new IllegalArgumentException(ue);
  }
}
 
Example 15
Source Project: big-c   File: NetUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Compose a "host:port" string from the address.
 */
public static String getHostPortString(InetSocketAddress addr) {
  return addr.getHostName() + ":" + addr.getPort();
}
 
Example 16
public List<Integer> evaluate(TaskServiceContext ctx, TaskInfo taskInfo) {
	List<Integer> result = new ArrayList<Integer>();
	if (ctx.getTaskType().matches(this.getTaskTypePattern())) {
		if (taskInfo.getName().matches(this.getTaskNamePattern())) {
			int count = ctx.getServerCount();
			InetSocketAddress sockAddr;
			InetAddress inetAddr;
			if (log.isDebugEnabled()) {
				log.debug("Task server count : " + count);
				log.debug("Address pattern : " + this.addressPattern);
			}
			String ip = null, host1, host2 = null, identifier = null;
			for (int i = 0; i < count; i++) {
				sockAddr = ctx.getServerAddress(i);
				identifier = ctx.getServerIdentifier(i);
				if (sockAddr != null) {
				    host1 = sockAddr.getHostName();
					if (log.isDebugEnabled()) {
						log.debug("Hostname 1 : " + host1);
					}
				    inetAddr = sockAddr.getAddress();
				    if (inetAddr != null) {
					    ip = inetAddr.getHostAddress();
					    host2 = inetAddr.getCanonicalHostName();
						if (log.isDebugEnabled()) {
							log.debug("IP address : " + ip);
							log.debug("Hostname 1 : " + host2);
						}
				    }
				    if (host1.matches(this.getAddressPattern())) {
						if (log.isDebugEnabled()) {
							log.debug("Hostname 1 matched");
						}
					    result.add(i);
				    } else if (ip != null && ip.matches(this.getAddressPattern())) {
						if (log.isDebugEnabled()) {
							log.debug("IP address matched");
						}
					    result.add(i);
				    } else if (!host1.equals(host2) && host2 != null && host2.matches(this.getAddressPattern())) {
						if (log.isDebugEnabled()) {
							log.debug("Hostname 2 matched");
						}
						result.add(i);
					} else if (identifier != null && identifier.matches(this.getAddressPattern())) {
						if (log.isDebugEnabled()) {
							log.debug("localMemberIdentifier : " + identifier);
							log.debug("localMemberIdentifier matched");
						}
						result.add(i);
					}
				} else {
					log.warn("RuleBasedLocationResolver: cannot find the host address for node: " + i);
				}					
			} 
		}
	}
	return result;
}
 
Example 17
@Override
public HttpHeaders filter(HttpHeaders input, ServerWebExchange exchange) {
	ServerHttpRequest request = exchange.getRequest();
	HttpHeaders original = input;
	HttpHeaders updated = new HttpHeaders();

	// copy all headers except Forwarded
	original.entrySet().stream().filter(
			entry -> !entry.getKey().toLowerCase().equalsIgnoreCase(FORWARDED_HEADER))
			.forEach(entry -> updated.addAll(entry.getKey(), entry.getValue()));

	List<Forwarded> forwardeds = parse(original.get(FORWARDED_HEADER));

	for (Forwarded f : forwardeds) {
		updated.add(FORWARDED_HEADER, f.toHeaderValue());
	}

	// TODO: add new forwarded
	URI uri = request.getURI();
	String host = original.getFirst(HttpHeaders.HOST);
	Forwarded forwarded = new Forwarded().put("host", host).put("proto",
			uri.getScheme());

	InetSocketAddress remoteAddress = request.getRemoteAddress();
	if (remoteAddress != null) {
		// If remoteAddress is unresolved, calling getHostAddress() would cause a
		// NullPointerException.
		String forValue = remoteAddress.isUnresolved() ? remoteAddress.getHostName()
				: remoteAddress.getAddress().getHostAddress();
		int port = remoteAddress.getPort();
		if (port >= 0) {
			forValue = forValue + ":" + port;
		}
		forwarded.put("for", forValue);
	}
	// TODO: support by?

	updated.add(FORWARDED_HEADER, forwarded.toHeaderValue());

	return updated;
}
 
Example 18
Source Project: RDFS   File: AvatarNode.java    License: Apache License 2.0 4 votes vote down vote up
public static String getClusterAddress(Configuration conf)
  throws UnknownHostException {
  InetSocketAddress addr = NameNode.getClientProtocolAddress(conf);
  return addr.getHostName() + ":" + addr.getPort();
}
 
Example 19
Source Project: nifi   File: Node.java    License: Apache License 2.0 4 votes vote down vote up
private String getClusterAddress() {
    final InetSocketAddress address = nodeProperties.getClusterNodeProtocolAddress();
    return address.getHostName() + ":" + address.getPort();
}
 
Example 20
Source Project: nifi   File: ListenWebSocket.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected String getTransitUri(final WebSocketSessionInfo sessionInfo) {
    final InetSocketAddress localAddress = sessionInfo.getLocalAddress();
    return (sessionInfo.isSecure() ? "wss:" : "ws:")
            + localAddress.getHostName() + ":" + localAddress.getPort() + endpointId;
}