Example usage for java.net InetAddress equals

List of usage examples for java.net InetAddress equals

Introduction

In this page you can find the example usage for java.net InetAddress equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object against the specified object.

Usage

From source file:at.alladin.rmbt.shared.Helperfunctions.java

public static String getNatType(final InetAddress localAdr, final InetAddress publicAdr) {
    try {/* ww  w  .  j  av a 2 s .c  o  m*/
        final String ipVersion;
        if (publicAdr instanceof Inet4Address)
            ipVersion = "ipv4";
        else if (publicAdr instanceof Inet6Address)
            ipVersion = "ipv6";
        else
            ipVersion = "ipv?";

        if (localAdr.equals(publicAdr))
            return "no_nat_" + ipVersion;
        else {
            final String localType = isIPLocal(localAdr) ? "local" : "public";
            final String publicType = isIPLocal(publicAdr) ? "local" : "public";
            return String.format("nat_%s_to_%s_%s", localType, publicType, ipVersion);
        }
    } catch (final IllegalArgumentException e) {
        return "illegal_ip";
    }
}

From source file:com.eislab.af.translator.Translator_hub_i.java

public static boolean ipv6InRange(String localIp, int localMask, String remoteIp) {
    InetAddress remoteAddress = parseAddress(remoteIp);
    InetAddress requiredAddress = parseAddress(localIp);
    int nMaskBits = localMask;

    if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
        return false;
    }/* w  w w  .j  a v a  2  s  . co  m*/

    if (nMaskBits <= 0) {
        return remoteAddress.equals(requiredAddress);
    }

    byte[] remAddr = remoteAddress.getAddress();
    byte[] reqAddr = requiredAddress.getAddress();

    int oddBits = nMaskBits % 8;
    int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
    byte[] mask = new byte[nMaskBytes];

    Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);

    if (oddBits != 0) {
        int finalByte = (1 << oddBits) - 1;
        finalByte <<= 8 - oddBits;
        mask[mask.length - 1] = (byte) finalByte;
    }

    //       System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));

    for (int i = 0; i < mask.length; i++) {
        if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
            return false;
        }
    }

    return true;
}

From source file:com.bigdata.dastor.service.StorageProxy.java

public static void mutateBlocking(List<RowMutation> mutations, ConsistencyLevel consistency_level)
        throws UnavailableException, TimeoutException {
    long startTime = System.nanoTime();
    ArrayList<WriteResponseHandler> responseHandlers = new ArrayList<WriteResponseHandler>();

    RowMutation mostRecentRowMutation = null;
    StorageService ss = StorageService.instance;
    try {/*from  w  ww  .j av a 2 s. c  om*/
        for (RowMutation rm : mutations) {
            mostRecentRowMutation = rm;
            String table = rm.getTable();
            AbstractReplicationStrategy rs = ss.getReplicationStrategy(table);

            List<InetAddress> naturalEndpoints = ss.getNaturalEndpoints(table, rm.key());
            Collection<InetAddress> writeEndpoints = rs.getWriteEndpoints(
                    StorageService.getPartitioner().getToken(rm.key()), table, naturalEndpoints);
            Multimap<InetAddress, InetAddress> hintedEndpoints = rs.getHintedEndpoints(table, writeEndpoints);
            int blockFor = determineBlockFor(writeEndpoints.size(), consistency_level);

            // avoid starting a write we know can't achieve the required consistency
            assureSufficientLiveNodes(blockFor, writeEndpoints, hintedEndpoints, consistency_level);

            // send out the writes, as in mutate() above, but this time with a callback that tracks responses
            final WriteResponseHandler responseHandler = ss.getWriteResponseHandler(blockFor, consistency_level,
                    table);
            responseHandlers.add(responseHandler);
            Message unhintedMessage = null;
            for (Map.Entry<InetAddress, Collection<InetAddress>> entry : hintedEndpoints.asMap().entrySet()) {
                InetAddress destination = entry.getKey();
                Collection<InetAddress> targets = entry.getValue();

                if (targets.size() == 1 && targets.iterator().next().equals(destination)) {
                    // unhinted writes
                    if (destination.equals(FBUtilities.getLocalAddress())) {
                        insertLocalMessage(rm, responseHandler);
                    } else {
                        // belongs on a different server.  send it there.
                        if (unhintedMessage == null) {
                            unhintedMessage = rm.makeRowMutationMessage();
                            MessagingService.instance.addCallback(responseHandler,
                                    unhintedMessage.getMessageId());
                        }
                        if (logger.isDebugEnabled())
                            logger.debug("insert writing key " + rm.key() + " to "
                                    + unhintedMessage.getMessageId() + "@" + destination);
                        MessagingService.instance.sendOneWay(unhintedMessage, destination);
                    }
                } else {
                    // hinted
                    Message hintedMessage = rm.makeRowMutationMessage();
                    for (InetAddress target : targets) {
                        if (!target.equals(destination)) {
                            addHintHeader(hintedMessage, target);
                            if (logger.isDebugEnabled())
                                logger.debug("insert writing key " + rm.key() + " to "
                                        + hintedMessage.getMessageId() + "@" + destination + " for " + target);
                        }
                    }
                    // (non-destination hints are part of the callback and count towards consistency only under CL.ANY)
                    if (writeEndpoints.contains(destination) || consistency_level == ConsistencyLevel.ANY)
                        MessagingService.instance.addCallback(responseHandler, hintedMessage.getMessageId());
                    MessagingService.instance.sendOneWay(hintedMessage, destination);
                }
            }
        }
        // wait for writes.  throws timeoutexception if necessary
        for (WriteResponseHandler responseHandler : responseHandlers) {
            responseHandler.get();
        }
    } catch (IOException e) {
        if (mostRecentRowMutation == null)
            throw new RuntimeException("no mutations were seen but found an error during write anyway", e);
        else
            throw new RuntimeException("error writing key " + mostRecentRowMutation.key(), e);
    } finally {
        writeStats.addNano(System.nanoTime() - startTime);
    }

}

From source file:com.bigdata.dastor.service.StorageProxy.java

/**
 * Use this method to have these RowMutations applied
 * across all replicas. This method will take care
 * of the possibility of a replica being down and hint
 * the data across to some other replica.
 *
 * This is the ZERO consistency level. We do not wait for replies.
 *
 * @param mutations the mutations to be applied across the replicas
*//*ww w . java  2  s .  c o  m*/
public static void mutate(List<RowMutation> mutations) {
    long startTime = System.nanoTime();
    try {
        StorageService ss = StorageService.instance;
        for (final RowMutation rm : mutations) {
            try {
                String table = rm.getTable();
                AbstractReplicationStrategy rs = ss.getReplicationStrategy(table);

                List<InetAddress> naturalEndpoints = ss.getNaturalEndpoints(table, rm.key());
                Multimap<InetAddress, InetAddress> hintedEndpoints = rs.getHintedEndpoints(table,
                        naturalEndpoints);
                Message unhintedMessage = null; // lazy initialize for non-local, unhinted writes

                // 3 cases:
                // 1. local, unhinted write: run directly on write stage
                // 2. non-local, unhinted write: send row mutation message
                // 3. hinted write: add hint header, and send message
                for (Map.Entry<InetAddress, Collection<InetAddress>> entry : hintedEndpoints.asMap()
                        .entrySet()) {
                    InetAddress destination = entry.getKey();
                    Collection<InetAddress> targets = entry.getValue();
                    if (targets.size() == 1 && targets.iterator().next().equals(destination)) {
                        // unhinted writes
                        if (destination.equals(FBUtilities.getLocalAddress())) {
                            if (logger.isDebugEnabled())
                                logger.debug("insert writing local key " + rm.key());
                            Runnable runnable = new WrappedRunnable() {
                                public void runMayThrow() throws IOException {
                                    rm.apply();
                                }
                            };
                            StageManager.getStage(StageManager.MUTATION_STAGE).execute(runnable);
                        } else {
                            if (unhintedMessage == null)
                                unhintedMessage = rm.makeRowMutationMessage();
                            if (logger.isDebugEnabled())
                                logger.debug("insert writing key " + rm.key() + " to "
                                        + unhintedMessage.getMessageId() + "@" + destination);
                            MessagingService.instance.sendOneWay(unhintedMessage, destination);
                        }
                    } else {
                        // hinted
                        Message hintedMessage = rm.makeRowMutationMessage();
                        for (InetAddress target : targets) {
                            if (!target.equals(destination)) {
                                addHintHeader(hintedMessage, target);
                                if (logger.isDebugEnabled())
                                    logger.debug("insert writing key " + rm.key() + " to "
                                            + hintedMessage.getMessageId() + "@" + destination + " for "
                                            + target);
                            }
                        }
                        MessagingService.instance.sendOneWay(hintedMessage, destination);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException("error inserting key " + rm.key(), e);
            }
        }
    } finally {
        writeStats.addNano(System.nanoTime() - startTime);
    }
}

From source file:org.opendaylight.infrautils.diagstatus.internal.ClusterMemberInfoImpl.java

@Override
public boolean isLocalAddress(InetAddress ipAddress) {
    return ipAddress.equals(InetAddress.getLoopbackAddress()) || ipAddress.equals(getSelfAddress());
}

From source file:org.mule.transport.tcp.TcpServerSocketFactory.java

public ServerSocket createServerSocket(URI uri, int backlog, Boolean reuse) throws IOException {
    String host = StringUtils.defaultIfEmpty(uri.getHost(), "localhost");
    InetAddress inetAddress = InetAddress.getByName(host);

    if ((inetAddress.equals(InetAddress.getLocalHost()) || host.trim().equals("localhost"))
            && TcpPropertyHelper.isBindingLocalhostToAllLocalInterfaces()) {
        logger.warn(TcpMessages.localhostBoundToAllLocalInterfaces());
        return createServerSocket(uri.getPort(), backlog, reuse);
    } else {/*from ww  w.  j a v a  2 s  . com*/
        return createServerSocket(inetAddress, uri.getPort(), backlog, reuse);
    }
}

From source file:com.stimulus.archiva.domain.Agent.java

public boolean isAllowed(InetAddress address) {

    // if nothing defined, by default we allow
    if (allowIPAddress.size() == 0)
        return true;

    for (String ip : allowIPAddress) {
        try {/* ww w .  ja  v a  2 s.c om*/
            InetAddress newip = InetAddress.getByName(ip);
            if (newip.equals(address))
                return true;
        } catch (UnknownHostException uhe) {
            logger.debug("allowed agent ip address appears invalid");

        }
    }
    return false;
}

From source file:com.predic8.membrane.core.interceptor.acl.Hostname.java

@Override
public boolean matches(String hostname, String ip) {
    try {/*from   www  .j a va  2  s . c om*/
        if (pattern.toString().equals("^localhost$")) {
            InetAddress ia = InetAddress.getByName(ip);
            if (ia.equals(localhostIp4) || ia.equals(localhostIp6)) {
                log.debug("Address to be matched : " + ia + " is being matched to :" + pattern.toString());
                return true;
            }
        }
        if (!reverseDNS) {
            long now = System.currentTimeMillis();
            if (now - lastWarningSlowReverseDNSUsed > 10 * 60 * 1000) {
                log.warn(
                        "transport/@reverseDNS=false is incompatible with ACL hostname filtering. (Please use ip filtering instead.) Slow reverse DNS lookup will be performed.");
                lastWarningSlowReverseDNSUsed = now;
            }
        }
        String canonicalHostName = router.getDnsCache().getCanonicalHostName(InetAddress.getByName(ip));
        log.debug("CanonicalHostname for " + hostname + " / " + ip + " is " + canonicalHostName);
        return pattern.matcher(canonicalHostName).matches();
    } catch (UnknownHostException e) {
        log.warn("Could not reverse lookup canonical hostname for " + hostname + " " + ip + ".", e);
        return false;
    }
}

From source file:org.apache.cassandra.service.StorageProxy.java

/**
 * Handle counter mutation on the coordinator host.
 *
 * A counter mutation needs to first be applied to a replica (that we'll call the leader for the mutation) before being
 * replicated to the other endpoint. To achieve so, there is two case:
 *   1) the coordinator host is a replica: we proceed to applying the update locally and replicate throug
 *   applyCounterMutationOnCoordinator// www.j a v  a2s  .  co m
 *   2) the coordinator is not a replica: we forward the (counter)mutation to a chosen replica (that will proceed through
 *   applyCounterMutationOnLeader upon receive) and wait for its acknowledgment.
 *
 * Implementation note: We check if we can fulfill the CL on the coordinator host even if he is not a replica to allow
 * quicker response and because the WriteResponseHandlers don't make it easy to send back an error. We also always gather
 * the write latencies at the coordinator node to make gathering point similar to the case of standard writes.
 */
//mutationcoordinator nodemutationreplica
//coordinator nodeapplyCounterMutationOnCoordinator
//mutationreplicareplicaleader
public static IWriteResponseHandler mutateCounter(CounterMutation cm, String localDataCenter)
        throws UnavailableException, TimeoutException, IOException {
    InetAddress endpoint = findSuitableEndpoint(cm.getTable(), cm.key());

    if (endpoint.equals(FBUtilities.getLocalAddress())) {
        return applyCounterMutationOnCoordinator(cm, localDataCenter);
    } else {
        // Exit now if we can't fulfill the CL here instead of forwarding to the leader replica
        String table = cm.getTable();
        AbstractReplicationStrategy rs = Table.open(table).getReplicationStrategy();
        Collection<InetAddress> writeEndpoints = getWriteEndpoints(table, cm.key());
        Multimap<InetAddress, InetAddress> hintedEndpoints = rs.getHintedEndpoints(writeEndpoints);
        rs.getWriteResponseHandler(writeEndpoints, hintedEndpoints, cm.consistency())
                .assureSufficientLiveNodes();

        // Forward the actual update to the chosen leader replica
        IWriteResponseHandler responseHandler = WriteResponseHandler.create(endpoint);

        Message message = cm.makeMutationMessage(Gossiper.instance.getVersion(endpoint));
        if (logger.isDebugEnabled())
            logger.debug("forwarding counter update of key " + ByteBufferUtil.bytesToHex(cm.key()) + " to "
                    + endpoint);
        MessagingService.instance().sendRR(message, endpoint, responseHandler);
        return responseHandler;
    }
}

From source file:org.apache.cassandra.service.StorageProxy.java

public static List<Row> currentReadFetchRow(ReadCommand command, ConsistencyLevel consistency_level,
        List<InetAddress> endpoints) throws IOException, UnavailableException, TimeoutException {
    //        List<ReadCallback<Row>> readCallbacks = new ArrayList<ReadCallback<Row>>();
    List<Row> rows = new ArrayList<Row>();

    // send out read requests
    //        for (ReadCommand command: commands)
    //        {// w w  w.j  a  va  2 s. c o m
    //            assert !command.isDigestQuery();
    logger.debug("Command/ConsistencyLevel is {}/{}", command, consistency_level);

    //            List<InetAddress> endpoints = StorageService.instance.getLiveNaturalEndpoints(command.table, command.key);
    //            DatabaseDescriptor.getEndpointSnitch().sortByProximity(FBUtilities.getLocalAddress(), endpoints);

    NullRowResolver resolver = new NullRowResolver(command.table, command.key);
    ReadCallback<Row> handler = getReadCallback(resolver, command, consistency_level, endpoints);
    handler.assureSufficientLiveNodes();
    assert !handler.endpoints.isEmpty();

    // no digestCommand

    for (InetAddress address : handler.endpoints) {
        if (address.equals(FBUtilities.getLocalAddress())) {
            if (logger.isDebugEnabled())
                logger.debug("reading data locally");
            StageManager.getStage(Stage.READ).execute(new LocalReadRunnable(command, handler));
        } else {
            if (logger.isDebugEnabled())
                logger.debug("reading data from " + address);
            MessagingService.instance().sendRR(command, address, handler);
        }
    }

    //            readCallbacks.add(handler);
    //        }

    //        for (int i = 0; i < commands.size(); i++)
    //        {
    //            ReadCallback<Row> handler = readCallbacks.get(i);
    Row row;
    //            ReadCommand command = commands.get(i);
    try {
        long startTime2 = System.currentTimeMillis();
        row = handler.get(); // CL.ONE is special cased here to ignore digests even if some have arrived
        if (row != null)
            rows.add(row);

        if (logger.isDebugEnabled())
            logger.debug("Read: " + (System.currentTimeMillis() - startTime2) + " ms.");
    } catch (TimeoutException ex) {
        if (logger.isDebugEnabled())
            logger.debug("Read timeout: {}", ex.toString());
        throw ex;
    } catch (DigestMismatchException ex) {
        //                if (logger.isDebugEnabled())
        //                    logger.debug("Digest mismatch: {}", ex.toString());
        //                RowRepairResolver resolver = new RowRepairResolver(command.table, command.key);
        //                RepairCallback<Row> repairHandler = new RepairCallback<Row>(resolver, handler.endpoints);
        //                for (InetAddress endpoint : handler.endpoints)
        //                    MessagingService.instance().sendRR(command, endpoint, repairHandler);
        //
        //                if (repairResponseHandlers == null)
        //                    repairResponseHandlers = new ArrayList<RepairCallback<Row>>();
        //                repairResponseHandlers.add(repairHandler);
    }
    //        }

    return rows;
}