下面列出了java.net.SocketAddress#equals ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public CompletionStage<ClusterConnectionReport> closeConnectionAsync(
SocketAddress connection, CloseType type) {
for (BoundNode node : this.getNodes()) {
// identify the node that has the connection and close it with that node.
for (SocketAddress address : node.getConnections().getConnections()) {
if (connection.equals(address)) {
return node.closeConnectionAsync(address, type)
.thenApply(NodeConnectionReport::getRootReport);
}
}
}
CompletableFuture<ClusterConnectionReport> failedFuture = new CompletableFuture<>();
failedFuture.completeExceptionally(new IllegalArgumentException("Not found"));
return failedFuture;
}
@Override
public CompletionStage<DataCenterConnectionReport> closeConnectionAsync(
SocketAddress connection, CloseType type) {
for (BoundNode node : this.getNodes()) {
// identify the node that has the connection and close it with that node.
for (SocketAddress address : node.getConnections().getConnections()) {
if (connection.equals(address)) {
return node.closeConnectionAsync(address, type)
.thenApply(n -> n.getRootReport().getDataCenters().iterator().next());
}
}
}
CompletableFuture<DataCenterConnectionReport> failedFuture = new CompletableFuture<>();
failedFuture.completeExceptionally(new IllegalArgumentException("Not found"));
return failedFuture;
}
void handleRedirectResponse(ResponseHeader header, StreamOp op, SocketAddress curAddr) {
SocketAddress ownerAddr = null;
if (header.isSetLocation()) {
String owner = header.getLocation();
try {
ownerAddr = DLSocketAddress.deserialize(owner).getSocketAddress();
// if we are receiving a direct request to same host, we won't try the same host.
// as the proxy will shut itself down if it redirects client to itself.
if (curAddr.equals(ownerAddr)) {
logger.warn("Request to stream {} is redirected to same server {}!", op.stream, curAddr);
ownerAddr = null;
} else {
// update ownership when redirects.
ownershipCache.updateOwner(op.stream, ownerAddr);
}
} catch (IOException e) {
ownerAddr = null;
}
}
redirect(op, ownerAddr);
}
void handleRedirectResponse(ResponseHeader header, StreamOp op, SocketAddress curAddr) {
SocketAddress ownerAddr = null;
if (header.isSetLocation()) {
String owner = header.getLocation();
try {
ownerAddr = DLSocketAddress.deserialize(owner).getSocketAddress();
// if we are receiving a direct request to same host, we won't try the same host.
// as the proxy will shut itself down if it redirects client to itself.
if (curAddr.equals(ownerAddr)) {
logger.warn("Request to stream {} is redirected to same server {}!", op.stream, curAddr);
ownerAddr = null;
} else {
// update ownership when redirects.
ownershipCache.updateOwner(op.stream, ownerAddr);
}
} catch (IOException e) {
ownerAddr = null;
}
}
redirect(op, ownerAddr);
}
private void disconnect(ChannelHandlerContext ctx, SocketAddress from) {
Gdx.app.debug(TAG, " " + "disconnecting " + from);
synchronized (clients) {
int id;
for (id = 0; id < MAX_CLIENTS && !from.equals(clients[id].address); id++) ;
if (id == MAX_CLIENTS) {
Gdx.app.debug(TAG, " " + "client from " + from + " already disconnected");
} else {
Gdx.app.debug(TAG, " " + "found connection record for " + from + " as " + id);
Gdx.app.debug(TAG, " " + "disconnecting " + id);
clients[id].disconnect();
connected &= ~(1 << id);
ids.remove(from, INVALID_CLIENT);
Disconnect(id);
}
Gdx.app.debug(TAG, " " + "closing " + ctx);
ctx.close();
}
}
private void disconnect(ChannelHandlerContext ctx, SocketAddress from) {
Gdx.app.debug(TAG, " " + "disconnecting " + from);
synchronized (clients) {
int id;
for (id = 0; id < MAX_CLIENTS && !from.equals(clients[id].address); id++) ;
if (id == MAX_CLIENTS) {
Gdx.app.debug(TAG, " " + "client from " + from + " already disconnected");
} else {
Gdx.app.debug(TAG, " " + "found connection record for " + from + " as " + id);
Gdx.app.debug(TAG, " " + "disconnecting " + id);
clients[id].disconnect();
}
Gdx.app.debug(TAG, " " + "closing " + ctx);
ctx.close();
}
}
@Override
public void run() {
try {
ByteBuffer bb = ByteBuffer.allocateDirect(12);
bb.clear();
// Only one clear. The buffer will be full after
// the first receive, but it should still block
// and receive and discard the next two
int numberReceived = 0;
while (!Thread.interrupted()) {
SocketAddress sa;
try {
sa = dc.receive(bb);
} catch (ClosedByInterruptException cbie) {
// Expected
log.println("Took expected exit");
// Verify that enough packets were received
if (numberReceived != 3)
throw new RuntimeException("Failed: Too few datagrams");
break;
}
if (sa != null) {
log.println("Client: " + sa);
// Check client address so as not to count stray packets
if (sa.equals(clientAddress)) {
showBuffer("RECV", bb);
numberReceived++;
}
if (numberReceived > 3)
throw new RuntimeException("Failed: Too many datagrams");
sa = null;
}
}
} catch (Exception ex) {
e = ex;
} finally {
try { dc.close(); } catch (IOException ignore) { }
}
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AbstractOption) {
SocketAddress s1 = ((AbstractOption) obj).getAddress();
SocketAddress s2 = this.getAddress();
return s1 != null && s1.equals(s2);
}
return false;
}
public synchronized void remove(int shardId, SocketAddress address) {
for (int i = 0; i < numOfReplicas; i++) {
long hash = replicaHash(shardId, i, address);
SocketAddress oldAddress = circle.get(hash);
if (null != oldAddress && oldAddress.equals(address)) {
circle.remove(hash);
}
}
hostRemovedCounter.incr();
}
private void removeHostInternal(SocketAddress host, Optional<Throwable> reason) {
synchronized (shardId2Address) {
Integer shardId = address2ShardId.remove(host);
if (null != shardId) {
SocketAddress curHost = shardId2Address.get(shardId);
if (null != curHost && curHost.equals(host)) {
shardId2Address.remove(shardId);
}
circle.remove(shardId, host);
if (reason.isPresent()) {
if (reason.get() instanceof ChannelException) {
logger.info("Shard {} ({}) left due to ChannelException, black it out for {} seconds"
+ " (message = {})",
new Object[] { shardId, host, blackoutSeconds, reason.get().toString() });
BlackoutHost blackoutHost = new BlackoutHost(shardId, host);
hashedWheelTimer.newTimeout(blackoutHost, blackoutSeconds, TimeUnit.SECONDS);
} else {
logger.info("Shard {} ({}) left due to exception {}",
new Object[] { shardId, host, reason.get().toString() });
}
} else {
logger.info("Shard {} ({}) left after server set change",
shardId, host);
}
} else if (reason.isPresent()) {
logger.info("Node {} left due to exception {}", host, reason.get().toString());
} else {
logger.info("Node {} left after server set change", host);
}
}
}
final boolean compareAddresses(SocketAddress origin, SocketAddress target) {
if (origin.equals(target)) {
return true;
}
else if (origin instanceof InetSocketAddress && target instanceof InetSocketAddress) {
InetSocketAddress isaOrigin = (InetSocketAddress) origin;
InetSocketAddress isaTarget = (InetSocketAddress) target;
if (isaOrigin.getPort() == isaTarget.getPort()) {
InetAddress iaTarget = isaTarget.getAddress();
return (iaTarget != null && iaTarget.isAnyLocalAddress()) ||
Objects.equals(isaOrigin.getHostString(), isaTarget.getHostString());
}
}
return false;
}
public synchronized void remove(int shardId, SocketAddress address) {
for (int i = 0; i < numOfReplicas; i++) {
long hash = replicaHash(shardId, i, address);
SocketAddress oldAddress = circle.get(hash);
if (null != oldAddress && oldAddress.equals(address)) {
circle.remove(hash);
}
}
hostRemovedCounter.incr();
}
private void removeHostInternal(SocketAddress host, Optional<Throwable> reason) {
synchronized (shardId2Address) {
Integer shardId = address2ShardId.remove(host);
if (null != shardId) {
SocketAddress curHost = shardId2Address.get(shardId);
if (null != curHost && curHost.equals(host)) {
shardId2Address.remove(shardId);
}
circle.remove(shardId, host);
if (reason.isPresent()) {
if (reason.get() instanceof ChannelException) {
logger.info("Shard {} ({}) left due to ChannelException, black it out for {} seconds (message = {})",
new Object[] { shardId, host, blackoutSeconds, reason.get().toString() });
BlackoutHost blackoutHost = new BlackoutHost(shardId, host);
hashedWheelTimer.newTimeout(blackoutHost, blackoutSeconds, TimeUnit.SECONDS);
} else {
logger.info("Shard {} ({}) left due to exception {}",
new Object[] { shardId, host, reason.get().toString() });
}
} else {
logger.info("Shard {} ({}) left after server set change",
shardId, host);
}
} else if (reason.isPresent()) {
logger.info("Node {} left due to exception {}", host, reason.get().toString());
} else {
logger.info("Node {} left after server set change", host);
}
}
}
@Override
public ChannelFuture write(Object message, SocketAddress remoteAddress) {
if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
return super.write(message, null);
} else {
return getUnsupportedOperationFuture();
}
}
@Override
public ChannelFuture write(Object message, SocketAddress remoteAddress) {
if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
return super.write(message, null);
} else {
return getUnsupportedOperationFuture();
}
}
/**
* Update ownership of <i>stream</i> to <i>addr</i>.
*
* @param stream
* Stream Name.
* @param addr
* Owner Address.
* @return true if owner is updated
*/
public boolean updateOwner(String stream, SocketAddress addr) {
// update ownership
SocketAddress oldAddr = stream2Addresses.putIfAbsent(stream, addr);
if (null != oldAddr && oldAddr.equals(addr)) {
return true;
}
if (null != oldAddr) {
if (stream2Addresses.replace(stream, oldAddr, addr)) {
// Store the relevant mappings for this topic and host combination
logger.info("Storing ownership for stream : {}, old host : {}, new host : {}.",
new Object[] { stream, oldAddr, addr });
StringBuilder sb = new StringBuilder();
sb.append("Ownership changed '")
.append(oldAddr).append("' -> '").append(addr).append("'");
removeOwnerFromStream(stream, oldAddr, sb.toString());
// update stats
ownershipStatsLogger.onRemove(stream);
ownershipStatsLogger.onAdd(stream);
} else {
logger.warn("Ownership of stream : {} has been changed from {} to {} when storing host : {}.",
new Object[] { stream, oldAddr, stream2Addresses.get(stream), addr });
return false;
}
} else {
logger.info("Storing ownership for stream : {}, host : {}.", stream, addr);
// update stats
ownershipStatsLogger.onAdd(stream);
}
Set<String> streamsForHost = address2Streams.get(addr);
if (null == streamsForHost) {
Set<String> newStreamsForHost = new HashSet<String>();
streamsForHost = address2Streams.putIfAbsent(addr, newStreamsForHost);
if (null == streamsForHost) {
streamsForHost = newStreamsForHost;
}
}
synchronized (streamsForHost) {
// check whether the ownership changed, since it might happend after replace succeed
if (addr.equals(stream2Addresses.get(stream))) {
streamsForHost.add(stream);
}
}
return true;
}
/**
* Update ownership of <i>stream</i> to <i>addr</i>.
*
* @param stream
* Stream Name.
* @param addr
* Owner Address.
* @return true if owner is updated
*/
public boolean updateOwner(String stream, SocketAddress addr) {
// update ownership
SocketAddress oldAddr = stream2Addresses.putIfAbsent(stream, addr);
if (null != oldAddr && oldAddr.equals(addr)) {
return true;
}
if (null != oldAddr) {
if (stream2Addresses.replace(stream, oldAddr, addr)) {
// Store the relevant mappings for this topic and host combination
logger.info("Storing ownership for stream : {}, old host : {}, new host : {}.",
new Object[] { stream, oldAddr, addr });
StringBuilder sb = new StringBuilder();
sb.append("Ownership changed '")
.append(oldAddr).append("' -> '").append(addr).append("'");
removeOwnerFromStream(stream, oldAddr, sb.toString());
// update stats
ownershipStatsLogger.onRemove(stream);
ownershipStatsLogger.onAdd(stream);
} else {
logger.warn("Ownership of stream : {} has been changed from {} to {} when storing host : {}.",
new Object[] { stream, oldAddr, stream2Addresses.get(stream), addr });
return false;
}
} else {
logger.info("Storing ownership for stream : {}, host : {}.", stream, addr);
// update stats
ownershipStatsLogger.onAdd(stream);
}
Set<String> streamsForHost = address2Streams.get(addr);
if (null == streamsForHost) {
Set<String> newStreamsForHost = new HashSet<String>();
streamsForHost = address2Streams.putIfAbsent(addr, newStreamsForHost);
if (null == streamsForHost) {
streamsForHost = newStreamsForHost;
}
}
synchronized (streamsForHost) {
// check whether the ownership changed, since it might happend after replace succeed
if (addr.equals(stream2Addresses.get(stream))) {
streamsForHost.add(stream);
}
}
return true;
}