Java Code Examples for java.net.SocketAddress#equals()

The following examples show how to use java.net.SocketAddress#equals() . 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 File: BoundDataCenter.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: BoundCluster.java    From simulacron with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
Source File: Main.java    From riiablo with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 4
Source File: Server.java    From riiablo with Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 5
Source File: DistributedLogClientImpl.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 6
Source File: DistributedLogClientImpl.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 7
Source File: NioSocketChannel.java    From android-netty with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture write(Object message, SocketAddress remoteAddress) {
    if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
        return super.write(message, null);
    } else {
        return getUnsupportedOperationFuture();
    }
}
 
Example 8
Source File: NioSocketChannel.java    From simple-netty-source with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelFuture write(Object message, SocketAddress remoteAddress) {
    if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) {
        return super.write(message, null);
    } else {
        return getUnsupportedOperationFuture();
    }
}
 
Example 9
Source File: ConsistentHashRoutingService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 10
Source File: ConsistentHashRoutingService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 11
Source File: PooledConnectionProvider.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: ConsistentHashRoutingService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
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);
        }
    }
}
 
Example 13
Source File: ConsistentHashRoutingService.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 14
Source File: AbstractOption.java    From lippen-network-tool with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 15
Source File: EmptyBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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) { }
    }
}
 
Example 16
Source File: OwnershipCache.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source File: OwnershipCache.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
}