下面列出了java.net.InetAddress#getLoopbackAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* This test validates that vertices with too many input streams do not have a location
* preference any more.
*/
@Test
public void testNoLocalityInputLargeAllToAll() throws Exception {
final int parallelism = 100;
final ExecutionGraph graph = createTestGraph(parallelism, true);
// set the location for all sources to a distinct location
for (int i = 0; i < parallelism; i++) {
ExecutionVertex source = graph.getAllVertices().get(sourceVertexId).getTaskVertices()[i];
TaskManagerLocation location = new TaskManagerLocation(
ResourceID.generate(), InetAddress.getLoopbackAddress(), 10000 + i);
initializeLocation(source, location);
}
// validate that the target vertices have no location preference
for (int i = 0; i < parallelism; i++) {
ExecutionVertex target = graph.getAllVertices().get(targetVertexId).getTaskVertices()[i];
Iterator<CompletableFuture<TaskManagerLocation>> preference = target.getPreferredLocations().iterator();
assertFalse(preference.hasNext());
}
}
private static SocketAddress getRevealedLocalAddress(SocketAddress sa,
SecurityManager sm)
{
if (sm == null || sa == null)
return sa;
InetSocketAddress ia = (InetSocketAddress)sa;
try{
sm.checkConnect(ia.getAddress().getHostAddress(), -1);
// Security check passed
} catch (SecurityException e) {
// Return loopback address
return new InetSocketAddress(InetAddress.getLoopbackAddress(),
ia.getPort());
}
return sa;
}
private static SocketAddress getRevealedLocalAddress(SocketAddress sa,
SecurityManager sm)
{
if (sm == null || sa == null)
return sa;
InetSocketAddress ia = (InetSocketAddress)sa;
try{
sm.checkConnect(ia.getAddress().getHostAddress(), -1);
// Security check passed
} catch (SecurityException e) {
// Return loopback address
return new InetSocketAddress(InetAddress.getLoopbackAddress(),
ia.getPort());
}
return sa;
}
public SimpleSlotProvider(JobID jobId, int numSlots, TaskManagerGateway taskManagerGateway) {
checkNotNull(jobId, "jobId");
checkArgument(numSlots >= 0, "numSlots must be >= 0");
this.slots = new ArrayDeque<>(numSlots);
for (int i = 0; i < numSlots; i++) {
SimpleSlotContext as = new SimpleSlotContext(
new AllocationID(),
new TaskManagerLocation(ResourceID.generate(), InetAddress.getLoopbackAddress(), 10000 + i),
0,
taskManagerGateway,
ResourceProfile.UNKNOWN);
slots.add(as);
}
allocatedSlots = new HashMap<>(slots.size());
}
/**
* Initialize the MINA server.
*/
public TCPTestServer(int port, boolean loopback, IoHandler handler) throws Exception {
acceptor = new NioSocketAcceptor();
IoFilter tupleEncoder = new ProtocolCodecFilter(new TestTupleEncoder(),
new TestTupleDecoder());
acceptor.getFilterChain().addLast("testtuples", tupleEncoder);
acceptor.setHandler(handler);
// Get the bind address now so the majority of
// errors are caught at initialization time.
bindAddress = new InetSocketAddress(
loopback ? InetAddress.getLoopbackAddress() : InetAddress.getLocalHost(), port);
}
/**
* Tests that when {@link IvyAuthenticator} can't handle a authentication request and falls back
* on an authenticator that was previously set, before IvyAuthenticator installed on top of it,
* the other authenticator gets passed all the relevant requesting information, including the
* {@link Authenticator#getRequestingURL() requesting URL} and
* {@link Authenticator#getRequestorType() request type}
*
* @throws Exception if something goes wrong
* @see <a href="https://issues.apache.org/jira/browse/IVY-1557">IVY-1557</a>
*/
@Test
public void testRequestURLAndType() throws Exception {
testAuthenticator.expectedHost = "localhost";
testAuthenticator.expectedPort = 12345;
testAuthenticator.expectedPrompt = "Test prompt - testRequestURLAndType";
testAuthenticator.expectedProtocol = "HTTP/1.1";
testAuthenticator.expectedURL = new URL("http", "localhost", 12345, "/a/b/c");
testAuthenticator.expectedType = Authenticator.RequestorType.PROXY;
testAuthenticator.expectedScheme = "BASIC";
testAuthenticator.expectedSite = InetAddress.getLoopbackAddress();
// trigger the authentication
final PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(testAuthenticator.expectedHost, testAuthenticator.expectedSite,
testAuthenticator.expectedPort, testAuthenticator.expectedProtocol, testAuthenticator.expectedPrompt,
testAuthenticator.expectedScheme, testAuthenticator.expectedURL, testAuthenticator.expectedType);
assertNotNull("Expected a password authentication, but got none", auth);
assertEquals("Unexpected username", "dummy", auth.getUserName());
assertTrue("Unexpected password", Arrays.equals("dummy".toCharArray(), auth.getPassword()));
}
protected void startPeerServer(int i) throws IOException {
peerServers[i] = new NioServer(new StreamConnectionFactory() {
@Nullable
@Override
public StreamConnection getNewConnection(InetAddress inetAddress, int port) {
return new InboundMessageQueuer(UNITTEST) {
@Override
public void connectionClosed() {
}
@Override
public void connectionOpened() {
newPeerWriteTargetQueue.offer(this);
}
};
}
}, new InetSocketAddress(InetAddress.getLoopbackAddress(), 2000 + i));
peerServers[i].startAsync();
peerServers[i].awaitRunning();
}
/**
* Returns the socket address of an endpoint that refuses connections. The
* endpoint is an InetSocketAddress where the address is the loopback address
* and the port is a system port (1-1023 range).
* This method is a better choice than getFreePort for tests that need
* an endpoint that refuses connections.
*/
public static InetSocketAddress refusingEndpoint() {
InetAddress lb = InetAddress.getLoopbackAddress();
int port = 1;
while (port < 1024) {
InetSocketAddress sa = new InetSocketAddress(lb, port);
try {
SocketChannel.open(sa).close();
} catch (IOException ioe) {
return sa;
}
port++;
}
throw new RuntimeException("Unable to find system port that is refusing connections");
}
@VisibleForTesting
void checkPorts(RunConfiguration devServerRunConfiguration,
BiPredicate<InetAddress, Integer> portInUse) throws CoreException {
InetAddress serverHost = InetAddress.getLoopbackAddress();
if (devServerRunConfiguration.getHost() != null) {
serverHost = LocalAppEngineServerLaunchConfigurationDelegate
.resolveAddress(devServerRunConfiguration.getHost());
}
serverPort = checkPort(serverHost,
ifNull(devServerRunConfiguration.getPort(), DEFAULT_SERVER_PORT), portInUse);
}
@UsesJava7 // fallback to InetAddress.getLoopbackAddress()
private InetAddress getLocalHost() {
try {
return InetAddress.getLocalHost();
}
catch (UnknownHostException ex) {
return InetAddress.getLoopbackAddress();
}
}
@Test
public void getMachaineAddressTest() throws UnknownHostException {
InetAddress localHost = InetAddress.getLocalHost();
log.debug("Localhost: " + localHost.getHostAddress());
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
log.debug("Loopback: " + loopbackAddress.getHostAddress());
}
private InetSocketAddress getAddress(int port) {
int socketPort = port < 0 ? 0 : port;
if (Boolean.parseBoolean(System.getProperties().getProperty("twill.zk.server.localhost", "true"))) {
return new InetSocketAddress(InetAddress.getLoopbackAddress(), socketPort);
} else {
return new InetSocketAddress(socketPort);
}
}
public static void main(String[] args) throws Exception {
final String HOST = "dummyserver.java.net";
InetAddress ia = null;
ia = InetAddress.getByName(HOST);
testInetAddress(ia, HOST);
ia = InetAddress.getByName("255.255.255.0");
testInetAddress(ia, null);
ia = InetAddress.getByAddress(new byte[]{1,1,1,1});
testInetAddress(ia, null);
ia = InetAddress.getLocalHost();
testInetAddress(ia, ia.getHostName());
ia = InetAddress.getLoopbackAddress();
testInetAddress(ia, ia.getHostName());
}
private static NettyConfig createNettyConfig(Configuration config) {
return new NettyConfig(
InetAddress.getLoopbackAddress(),
NetUtils.getAvailablePort(),
NettyTestUtil.DEFAULT_SEGMENT_SIZE,
1,
config);
}
/**
* Creates an ExecutionControl instance based on a JDI
* {@code ListeningConnector} or {@code LaunchingConnector}.
*
* Initialize JDI and use it to launch the remote JVM. Set-up a socket for
* commands and results. This socket also transports the user
* input/output/error.
*
* @param env the context passed by
* {@link jdk.jshell.spi.ExecutionControl#start(jdk.jshell.spi.ExecutionEnv) }
* @param remoteAgent the remote agent to launch
* @param isLaunch does JDI do the launch? That is, LaunchingConnector,
* otherwise we start explicitly and use ListeningConnector
* @param host explicit hostname to use, if null use discovered
* hostname, applies to listening only (!isLaunch)
* @return the channel
* @throws IOException if there are errors in set-up
*/
static ExecutionControl create(ExecutionEnv env, String remoteAgent,
boolean isLaunch, String host, int timeout) throws IOException {
try (final ServerSocket listener = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
// timeout on I/O-socket
listener.setSoTimeout(timeout);
int port = listener.getLocalPort();
// Set-up the JDI connection
JdiInitiator jdii = new JdiInitiator(port,
env.extraRemoteVMOptions(), remoteAgent, isLaunch, host,
timeout, Collections.emptyMap());
VirtualMachine vm = jdii.vm();
Process process = jdii.process();
List<Consumer<String>> deathListeners = new ArrayList<>();
Util.detectJdiExitEvent(vm, s -> {
for (Consumer<String> h : deathListeners) {
h.accept(s);
}
});
// Set-up the commands/reslts on the socket. Piggy-back snippet
// output.
Socket socket = listener.accept();
// out before in -- match remote creation so we don't hang
OutputStream out = socket.getOutputStream();
Map<String, OutputStream> outputs = new HashMap<>();
outputs.put("out", env.userOut());
outputs.put("err", env.userErr());
Map<String, InputStream> input = new HashMap<>();
input.put("in", env.userIn());
return remoteInputOutput(socket.getInputStream(), out, outputs, input,
(objIn, objOut) -> new JdiDefaultExecutionControl(env,
objOut, objIn, vm, process, remoteAgent, deathListeners));
}
}
@Test
public void shouldFailCreatingSocketForUnknownHost() throws Exception {
// Given
String unknownHost = "localhorst";
InetAddress localAddress = InetAddress.getLoopbackAddress();
int localPort = 28080;
HttpConnectionParams params = new HttpConnectionParams();
params.setConnectionTimeout(60000);
// When / Then
assertThrows(
IOException.class,
() ->
socketFactory.createSocket(
unknownHost, serverPort, localAddress, localPort, params));
}
@Override
public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException {
if (firstCall) {
firstCall = false;
// throw unchecked exception first time round
throw new IllegalStateException();
}
// return any valid address
return new InetAddress[] { InetAddress.getLoopbackAddress() };
}
private void initRes() throws IOException {
serverSocket = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
server = new TestLDAPServer();
server.start();
}
public LocalTaskManagerLocation() {
super(ResourceID.generate(), InetAddress.getLoopbackAddress(), 42);
}
@Override
public InetAddress getAcceptorAddress() {
return InetAddress.getLoopbackAddress();
}