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:com.vuze.plugin.azVPN_Air.Checker.java

private int handleUnboundOrLoopback(InetAddress bindIP, StringBuilder sReply) {

    int newStatusID = STATUS_ID_OK;

    InetAddress newBindIP = null;
    NetworkInterface newBindNetworkInterface = null;

    String s;/*from  w w  w .j ava  2s.  c o m*/

    if (bindIP.isAnyLocalAddress()) {
        addReply(sReply, CHAR_WARN, "airvpn.vuze.unbound");
    } else {
        addReply(sReply, CHAR_BAD, "airvpn.vuze.loopback");
    }

    try {
        NetworkAdmin networkAdmin = NetworkAdmin.getSingleton();

        // Find a bindable address that starts with 10.
        InetAddress[] bindableAddresses = networkAdmin.getBindableAddresses();

        for (InetAddress bindableAddress : bindableAddresses) {
            if (matchesVPNIP(bindableAddress)) {
                newBindIP = bindableAddress;
                newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);

                addReply(sReply, CHAR_GOOD, "airvpn.found.bindable.vpn", new String[] { "" + newBindIP });

                break;
            }
        }

        // Find a Network Interface that has an address that starts with 10.
        NetworkAdminNetworkInterface[] interfaces = networkAdmin.getInterfaces();

        boolean foundNIF = false;
        for (NetworkAdminNetworkInterface networkAdminInterface : interfaces) {
            NetworkAdminNetworkInterfaceAddress[] addresses = networkAdminInterface.getAddresses();
            for (NetworkAdminNetworkInterfaceAddress a : addresses) {
                InetAddress address = a.getAddress();
                if (address instanceof Inet4Address) {
                    if (matchesVPNIP(address)) {
                        s = texts.getLocalisedMessageText("airvpn.possible.vpn",
                                new String[] { "" + address, networkAdminInterface.getName() + " ("
                                        + networkAdminInterface.getDisplayName() + ")" });

                        if (newBindIP == null) {
                            foundNIF = true;
                            newBindIP = address;

                            // Either one should work
                            //newBindNetworkInterface = NetworkInterface.getByInetAddress(newBindIP);
                            newBindNetworkInterface = NetworkInterface
                                    .getByName(networkAdminInterface.getName());

                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                        } else if (address.equals(newBindIP)) {
                            s = CHAR_GOOD + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.same.address");
                            foundNIF = true;
                        } else {
                            if (newStatusID != STATUS_ID_BAD) {
                                newStatusID = STATUS_ID_WARN;
                            }
                            s = CHAR_WARN + " " + s + ". "
                                    + texts.getLocalisedMessageText("airvpn.not.same.address");
                        }

                        addLiteralReply(sReply, s);

                        if (rebindNetworkInterface) {
                            // stops message below from being added, we'll rebind later
                            foundNIF = true;
                        }

                    }
                }
            }
        }

        if (!foundNIF) {
            addReply(sReply, CHAR_BAD, "airvpn.interface.not.found");
        }

        // Check if default routing goes through 10.*, by connecting to address
        // via socket.  Address doesn't need to be reachable, just routable.
        // This works on Windows, but on Mac returns a wildcard address
        DatagramSocket socket = new DatagramSocket();
        socket.connect(testSocketAddress, 0);
        InetAddress localAddress = socket.getLocalAddress();
        socket.close();

        if (!localAddress.isAnyLocalAddress()) {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localAddress);

            s = texts.getLocalisedMessageText("airvpn.nonvuze.probable.route",
                    new String[] { "" + localAddress, networkInterface == null ? "null"
                            : networkInterface.getName() + " (" + networkInterface.getDisplayName() + ")" });

            if ((localAddress instanceof Inet4Address) && matchesVPNIP(localAddress)) {

                if (newBindIP == null) {
                    newBindIP = localAddress;
                    newBindNetworkInterface = networkInterface;

                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.assuming.vpn");
                } else if (localAddress.equals(newBindIP)) {
                    s = CHAR_GOOD + " " + s + " " + texts.getLocalisedMessageText("airvpn.same.address");
                } else {
                    // Vuze not bound. We already found a boundable address, but it's not this one
                    /* Possibly good case:
                     * - Vuze: unbound
                     * - Found Bindable: 10.100.1.6
                     * - Default Routing: 10.255.1.1
                     * -> Split network
                     */
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s = CHAR_WARN + " " + s + " "
                            + texts.getLocalisedMessageText("airvpn.not.same.future.address") + " "
                            + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting") + " "
                            + texts.getLocalisedMessageText(
                                    "default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);

            } else {
                s = CHAR_WARN + " " + s;
                if (!bindIP.isLoopbackAddress()) {
                    s += " " + texts.getLocalisedMessageText("default.routing.not.vpn.network.splitting");
                }

                if (newBindIP == null && foundNIF) {
                    if (newStatusID != STATUS_ID_BAD) {
                        newStatusID = STATUS_ID_WARN;
                    }
                    s += " " + texts
                            .getLocalisedMessageText("default.routing.not.vpn.network.splitting.unbound");
                }

                addLiteralReply(sReply, s);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        addReply(sReply, CHAR_BAD, "airvpn.nat.error", new String[] { e.toString() });
    }

    if (newBindIP == null) {
        addReply(sReply, CHAR_BAD, "airvpn.vpn.ip.detect.fail");
        return STATUS_ID_BAD;
    }

    rebindNetworkInterface(newBindNetworkInterface, newBindIP, sReply);
    return newStatusID;
}

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

/**
 * Remove a node that has died, attempting to restore the replica count.
 * If the node is alive, decommission should be attempted.  If decommission
 * fails, then removeToken should be called.  If we fail while trying to
 * restore the replica count, finally forceRemoveCompleteion should be
 * called to forcibly remove the node without regard to replica count.
 *
 * @param tokenString token for the node
 *//*  w  w  w .  java 2 s .c o  m*/
public void removeToken(String tokenString) {
    InetAddress myAddress = FBUtilities.getLocalAddress();
    Token localToken = tokenMetadata_.getToken(myAddress);
    Token token = partitioner.getTokenFactory().fromString(tokenString);
    InetAddress endpoint = tokenMetadata_.getEndpoint(token);

    if (endpoint == null)
        throw new UnsupportedOperationException("Token not found.");

    if (endpoint.equals(myAddress))
        throw new UnsupportedOperationException("Cannot remove node's own token");

    if (Gossiper.instance.getLiveMembers().contains(endpoint))
        throw new UnsupportedOperationException("Node " + endpoint
                + " is alive and owns this token. Use decommission command to remove it from the ring");

    // A leaving endpoint that is dead is already being removed.
    if (tokenMetadata_.isLeaving(endpoint))
        logger_.warn("Node " + endpoint + " is already being removed, continuing removal anyway");

    if (!replicatingNodes.isEmpty())
        throw new UnsupportedOperationException(
                "This node is already processing a removal. Wait for it to complete, or use 'removetoken force' if this has failed.");

    // Find the endpoints that are going to become responsible for data
    for (String table : DatabaseDescriptor.getNonSystemTables()) {
        // if the replication factor is 1 the data is lost so we shouldn't wait for confirmation
        if (Table.open(table).getReplicationStrategy().getReplicationFactor() == 1)
            continue;

        // get all ranges that change ownership (that is, a node needs
        // to take responsibility for new range)
        Multimap<Range, InetAddress> changedRanges = getChangedRangesForLeaving(table, endpoint);
        IFailureDetector failureDetector = FailureDetector.instance;
        for (InetAddress ep : changedRanges.values()) {
            if (failureDetector.isAlive(ep))
                replicatingNodes.add(ep);
            else
                logger_.warn("Endpoint " + ep + " is down and will not receive data for re-replication of "
                        + endpoint);
        }
    }
    removingNode = endpoint;

    tokenMetadata_.addLeavingEndpoint(endpoint);
    calculatePendingRanges();
    // bundle two states together. include this nodes state to keep the status quo, 
    // but indicate the leaving token so that it can be dealt with.
    Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS,
            valueFactory.removingNonlocal(localToken, token));

    // kick off streaming commands
    restoreReplicaCount(endpoint, myAddress);

    // wait for ReplicationFinishedVerbHandler to signal we're done
    while (!replicatingNodes.isEmpty()) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new AssertionError(e);
        }
    }

    excise(token, endpoint);

    // indicate the token has left
    Gossiper.instance.addLocalApplicationState(ApplicationState.STATUS,
            valueFactory.removedNonlocal(localToken, token));

    replicatingNodes.clear();
    removingNode = null;
}

From source file:org.apache.nutch.protocol.ftp.FtpResponse.java

public FtpResponse(URL url, CrawlDatum datum, Ftp ftp, Configuration conf) throws FtpException, IOException {

    this.orig = url.toString();
    this.base = url.toString();
    this.ftp = ftp;
    this.conf = conf;

    if (!"ftp".equals(url.getProtocol()))
        throw new FtpException("Not a ftp url:" + url);

    if (url.getPath() != url.getFile()) {
        if (Ftp.LOG.isWarnEnabled()) {
            Ftp.LOG.warn("url.getPath() != url.getFile(): " + url);
        }//  w  ww  .j  ava 2  s.  c  o m
    }

    String path = "".equals(url.getPath()) ? "/" : url.getPath();

    try {

        if (ftp.followTalk) {
            if (Ftp.LOG.isInfoEnabled()) {
                Ftp.LOG.info("fetching " + url);
            }
        } else {
            if (Ftp.LOG.isTraceEnabled()) {
                Ftp.LOG.trace("fetching " + url);
            }
        }

        InetAddress addr = InetAddress.getByName(url.getHost());
        if (addr != null && conf.getBoolean("store.ip.address", false) == true) {
            headers.add("_ip_", addr.getHostAddress());
        }

        // idled too long, remote server or ourselves may have timed out,
        // should start anew.
        if (ftp.client != null && ftp.keepConnection && ftp.renewalTime < System.currentTimeMillis()) {
            if (Ftp.LOG.isInfoEnabled()) {
                Ftp.LOG.info("delete client because idled too long");
            }
            ftp.client = null;
        }

        // start anew if needed
        if (ftp.client == null) {
            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("start client");
            }
            // the real client
            ftp.client = new Client();
            // when to renew, take the lesser
            // ftp.renewalTime = System.currentTimeMillis()
            // + ((ftp.timeout<ftp.serverTimeout) ? ftp.timeout :
            // ftp.serverTimeout);

            // timeout for control connection
            ftp.client.setDefaultTimeout(ftp.timeout);
            // timeout for data connection
            ftp.client.setDataTimeout(ftp.timeout);

            // follow ftp talk?
            if (ftp.followTalk)
                ftp.client.addProtocolCommandListener(new PrintCommandListener(Ftp.LOG));
        }

        // quit from previous site if at a different site now
        if (ftp.client.isConnected()) {
            InetAddress remoteAddress = ftp.client.getRemoteAddress();
            if (!addr.equals(remoteAddress)) {
                if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                    Ftp.LOG.info("disconnect from " + remoteAddress + " before connect to " + addr);
                }
                // quit from current site
                ftp.client.logout();
                ftp.client.disconnect();
            }
        }

        // connect to current site if needed
        if (!ftp.client.isConnected()) {

            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("connect to " + addr);
            }

            ftp.client.connect(addr);
            if (!FTPReply.isPositiveCompletion(ftp.client.getReplyCode())) {
                ftp.client.disconnect();
                if (Ftp.LOG.isWarnEnabled()) {
                    Ftp.LOG.warn("ftp.client.connect() failed: " + addr + " " + ftp.client.getReplyString());
                }
                this.code = 500; // http Internal Server Error
                return;
            }

            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("log into " + addr);
            }

            if (!ftp.client.login(ftp.userName, ftp.passWord)) {
                // login failed.
                // please note that some server may return 421 immediately
                // after USER anonymous, thus ftp.client.login() won't return false,
                // but throw exception, which then will be handled by caller
                // (not dealt with here at all) .
                ftp.client.disconnect();
                if (Ftp.LOG.isWarnEnabled()) {
                    Ftp.LOG.warn("ftp.client.login() failed: " + addr);
                }
                this.code = 401; // http Unauthorized
                return;
            }

            // insist on binary file type
            if (!ftp.client.setFileType(FTP.BINARY_FILE_TYPE)) {
                ftp.client.logout();
                ftp.client.disconnect();
                if (Ftp.LOG.isWarnEnabled()) {
                    Ftp.LOG.warn("ftp.client.setFileType() failed: " + addr);
                }
                this.code = 500; // http Internal Server Error
                return;
            }

            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("set parser for " + addr);
            }

            // SYST is valid only after login
            try {
                ftp.parser = null;
                String parserKey = ftp.client.getSystemName();
                // some server reports as UNKNOWN Type: L8, but in fact UNIX Type: L8
                if (parserKey.startsWith("UNKNOWN Type: L8"))
                    parserKey = "UNIX Type: L8";
                ftp.parser = (new DefaultFTPFileEntryParserFactory()).createFileEntryParser(parserKey);
            } catch (FtpExceptionBadSystResponse e) {
                if (Ftp.LOG.isWarnEnabled()) {
                    Ftp.LOG.warn("ftp.client.getSystemName() failed: " + addr + " " + e);
                }
                ftp.parser = null;
            } catch (ParserInitializationException e) {
                // ParserInitializationException is RuntimeException defined in
                // org.apache.commons.net.ftp.parser.ParserInitializationException
                if (Ftp.LOG.isWarnEnabled()) {
                    Ftp.LOG.warn("createFileEntryParser() failed. " + addr + " " + e);
                }
                ftp.parser = null;
            } finally {
                if (ftp.parser == null) {
                    // do not log as severe, otherwise
                    // FetcherThread/RequestScheduler will abort
                    if (Ftp.LOG.isWarnEnabled()) {
                        Ftp.LOG.warn("ftp.parser is null: " + addr);
                    }
                    ftp.client.logout();
                    ftp.client.disconnect();
                    this.code = 500; // http Internal Server Error
                    return;
                }
            }

        } else {
            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("use existing connection");
            }
        }

        this.content = null;

        path = java.net.URLDecoder.decode(path, "UTF-8");

        if (path.endsWith("/")) {
            getDirAsHttpResponse(path, datum.getModifiedTime());
        } else {
            getFileAsHttpResponse(path, datum.getModifiedTime());
        }

        // reset next renewalTime, take the lesser
        if (ftp.client != null && ftp.keepConnection) {
            ftp.renewalTime = System.currentTimeMillis()
                    + ((ftp.timeout < ftp.serverTimeout) ? ftp.timeout : ftp.serverTimeout);
            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("reset renewalTime to " + HttpDateFormat.toString(ftp.renewalTime));
            }
        }

        // getDirAsHttpResponse() or getFileAsHttpResponse() above
        // may have deleted ftp.client
        if (ftp.client != null && !ftp.keepConnection) {
            if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
                Ftp.LOG.info("disconnect from " + addr);
            }
            ftp.client.logout();
            ftp.client.disconnect();
        }

    } catch (Exception e) {
        if (Ftp.LOG.isWarnEnabled()) {
            Ftp.LOG.warn("Error: ", e);
        }
        // for any un-foreseen exception (run time exception or not),
        // do ultimate clean and leave ftp.client for garbage collection
        if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
            Ftp.LOG.info("delete client due to exception");
        }
        ftp.client = null;
        // or do explicit garbage collection?
        // System.gc();
        // can we be less dramatic, using the following instead?
        // probably unnecessary for our practical purpose here
        // try {
        // ftp.client.logout();
        // ftp.client.disconnect();
        // }
        throw new FtpException(e);
        // throw e;
    }

}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPClient.java

/***
 * Requests a named file from a remote host, writes the
 * file to an OutputStream, closes the connection, and returns the number
 * of bytes read.  A local UDP socket must first be created by
 * {@link org.apache.commons.net.DatagramSocketClient#open open()} before
 * invoking this method.  This method will not close the OutputStream
 * containing the file; you must close it after the method invocation.
 * <p>/* w  w  w . j a  va2  s .co m*/
 * @param filename  The name of the file to receive.
 * @param mode   The TFTP mode of the transfer (one of the MODE constants).
 * @param output The OutputStream to which the file should be written.
 * @param host   The remote host serving the file.
 * @param port   The port number of the remote TFTP server.
 * @exception IOException If an I/O error occurs.  The nature of the
 *            error will be reported in the message.
 ***/
public int receiveFile(String filename, int mode, OutputStream output, InetAddress host, int port)
        throws IOException {
    int bytesRead, timeouts, lastBlock, block, hostPort, dataLength;
    TFTPPacket sent, received = null;
    TFTPErrorPacket error;
    TFTPDataPacket data;
    TFTPAckPacket ack = new TFTPAckPacket(host, port, 0);

    beginBufferedOps();

    dataLength = lastBlock = hostPort = bytesRead = 0;
    block = 1;

    if (mode == TFTP.ASCII_MODE)
        output = new FromNetASCIIOutputStream(output);

    sent = new TFTPReadRequestPacket(host, port, filename, mode);

    _sendPacket: do {
        bufferedSend(sent);

        _receivePacket: while (true) {
            timeouts = 0;
            while (timeouts < __maxTimeouts) {
                try {
                    received = bufferedReceive();
                    break;
                } catch (SocketException e) {
                    if (++timeouts >= __maxTimeouts) {
                        endBufferedOps();
                        throw new IOException("Connection timed out.");
                    }
                    continue;
                } catch (InterruptedIOException e) {
                    if (++timeouts >= __maxTimeouts) {
                        endBufferedOps();
                        throw new IOException("Connection timed out.");
                    }
                    continue;
                } catch (TFTPPacketException e) {
                    endBufferedOps();
                    throw new IOException("Bad packet: " + e.getMessage());
                }
            }

            // The first time we receive we get the port number and
            // answering host address (for hosts with multiple IPs)
            if (lastBlock == 0) {
                hostPort = received.getPort();
                ack.setPort(hostPort);
                if (!host.equals(received.getAddress())) {
                    host = received.getAddress();
                    ack.setAddress(host);
                    sent.setAddress(host);
                }
            }

            // Comply with RFC 783 indication that an error acknowledgement
            // should be sent to originator if unexpected TID or host.
            if (host.equals(received.getAddress()) && received.getPort() == hostPort) {

                switch (received.getType()) {
                case TFTPPacket.ERROR:
                    error = (TFTPErrorPacket) received;
                    endBufferedOps();
                    throw new IOException(
                            "Error code " + error.getError() + " received: " + error.getMessage());
                case TFTPPacket.DATA:
                    data = (TFTPDataPacket) received;
                    dataLength = data.getDataLength();

                    lastBlock = data.getBlockNumber();

                    if (lastBlock == block) {
                        try {
                            output.write(data.getData(), data.getDataOffset(), dataLength);
                        } catch (IOException e) {
                            error = new TFTPErrorPacket(host, hostPort, TFTPErrorPacket.OUT_OF_SPACE,
                                    "File write failed.");
                            bufferedSend(error);
                            endBufferedOps();
                            throw e;
                        }
                        ++block;
                        break _receivePacket;
                    } else {
                        discardPackets();

                        if (lastBlock == (block - 1))
                            continue _sendPacket; // Resend last acknowledgement.

                        continue _receivePacket; // Start fetching packets again.
                    }
                    //break;

                default:
                    endBufferedOps();
                    throw new IOException("Received unexpected packet type.");
                }
            } else {
                error = new TFTPErrorPacket(received.getAddress(), received.getPort(),
                        TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port.");
                bufferedSend(error);
                continue _sendPacket;
            }

            // We should never get here, but this is a safety to avoid
            // infinite loop.  If only Java had the goto statement.
            //break;
        }

        ack.setBlockNumber(lastBlock);
        sent = ack;
        bytesRead += dataLength;
    } // First data packet less than 512 bytes signals end of stream.

    while (dataLength == TFTPPacket.SEGMENT_SIZE);

    bufferedSend(sent);
    endBufferedOps();

    return bytesRead;
}

From source file:org.eredlab.g4.ccl.net.tftp.TFTPClient.java

/***
 * Requests to send a file to a remote host, reads the file from an
 * InputStream, sends the file to the remote host, and closes the
 * connection.  A local UDP socket must first be created by
 * {@link org.apache.commons.net.DatagramSocketClient#open open()} before
 * invoking this method.  This method will not close the InputStream
 * containing the file; you must close it after the method invocation.
 * <p>/*  w w w . j av a  2  s  .c o m*/
 * @param filename The name the remote server should use when creating
 *        the file on its file system.
 * @param mode     The TFTP mode of the transfer (one of the MODE constants).
 * @param host     The remote host receiving the file.
 * @param port     The port number of the remote TFTP server.
 * @exception IOException If an I/O error occurs.  The nature of the
 *            error will be reported in the message.
 ***/
public void sendFile(String filename, int mode, InputStream input, InetAddress host, int port)
        throws IOException {
    int bytesRead, timeouts, lastBlock, block, hostPort, dataLength, offset;
    TFTPPacket sent, received = null;
    TFTPErrorPacket error;
    TFTPDataPacket data = new TFTPDataPacket(host, port, 0, _sendBuffer, 4, 0);
    ;
    TFTPAckPacket ack;

    beginBufferedOps();

    dataLength = lastBlock = hostPort = bytesRead = 0;
    block = 0;
    boolean lastAckWait = false;

    if (mode == TFTP.ASCII_MODE)
        input = new ToNetASCIIInputStream(input);

    sent = new TFTPWriteRequestPacket(host, port, filename, mode);

    _sendPacket: do {
        bufferedSend(sent);

        _receivePacket: while (true) {
            timeouts = 0;
            while (timeouts < __maxTimeouts) {
                try {
                    received = bufferedReceive();
                    break;
                } catch (SocketException e) {
                    if (++timeouts >= __maxTimeouts) {
                        endBufferedOps();
                        throw new IOException("Connection timed out.");
                    }
                    continue;
                } catch (InterruptedIOException e) {
                    if (++timeouts >= __maxTimeouts) {
                        endBufferedOps();
                        throw new IOException("Connection timed out.");
                    }
                    continue;
                } catch (TFTPPacketException e) {
                    endBufferedOps();
                    throw new IOException("Bad packet: " + e.getMessage());
                }
            }

            // The first time we receive we get the port number and
            // answering host address (for hosts with multiple IPs)
            if (lastBlock == 0) {
                hostPort = received.getPort();
                data.setPort(hostPort);
                if (!host.equals(received.getAddress())) {
                    host = received.getAddress();
                    data.setAddress(host);
                    sent.setAddress(host);
                }
            }

            // Comply with RFC 783 indication that an error acknowledgement
            // should be sent to originator if unexpected TID or host.
            if (host.equals(received.getAddress()) && received.getPort() == hostPort) {

                switch (received.getType()) {
                case TFTPPacket.ERROR:
                    error = (TFTPErrorPacket) received;
                    endBufferedOps();
                    throw new IOException(
                            "Error code " + error.getError() + " received: " + error.getMessage());
                case TFTPPacket.ACKNOWLEDGEMENT:
                    ack = (TFTPAckPacket) received;

                    lastBlock = ack.getBlockNumber();

                    if (lastBlock == block) {
                        ++block;
                        if (lastAckWait)
                            break _sendPacket;
                        else
                            break _receivePacket;
                    } else {
                        discardPackets();

                        if (lastBlock == (block - 1))
                            continue _sendPacket; // Resend last acknowledgement.

                        continue _receivePacket; // Start fetching packets again.
                    }
                    //break;

                default:
                    endBufferedOps();
                    throw new IOException("Received unexpected packet type.");
                }
            } else {
                error = new TFTPErrorPacket(received.getAddress(), received.getPort(),
                        TFTPErrorPacket.UNKNOWN_TID, "Unexpected host or port.");
                bufferedSend(error);
                continue _sendPacket;
            }

            // We should never get here, but this is a safety to avoid
            // infinite loop.  If only Java had the goto statement.
            //break;
        }

        dataLength = TFTPPacket.SEGMENT_SIZE;
        offset = 4;
        while (dataLength > 0 && (bytesRead = input.read(_sendBuffer, offset, dataLength)) > 0) {
            offset += bytesRead;
            dataLength -= bytesRead;
        }

        data.setBlockNumber(block);
        data.setData(_sendBuffer, 4, offset - 4);
        sent = data;
    } while (dataLength == 0 || lastAckWait);

    endBufferedOps();
}

From source file:org.lealone.cluster.service.StorageService.java

@Override
public void onChange(InetAddress endpoint, ApplicationState state, VersionedValue value) {
    if (state == ApplicationState.STATUS) {
        String apStateValue = value.value;
        String[] pieces = apStateValue.split(VersionedValue.DELIMITER_STR, -1);
        assert (pieces.length > 0);

        String moveName = pieces[0];

        switch (moveName) {
        case VersionedValue.STATUS_BOOTSTRAPPING:
            handleStateBootstrap(endpoint);
            break;
        case VersionedValue.STATUS_NORMAL:
            handleStateNormal(endpoint);
            break;
        case VersionedValue.REMOVING_TOKEN:
        case VersionedValue.REMOVED_TOKEN:
            handleStateRemoving(endpoint, pieces);
            break;
        case VersionedValue.STATUS_LEAVING:
            handleStateLeaving(endpoint);
            break;
        case VersionedValue.STATUS_LEFT:
            handleStateLeft(endpoint, pieces);
            break;
        case VersionedValue.STATUS_MOVING:
            handleStateMoving(endpoint, pieces);
            break;
        }//www  .j  av  a 2s.  c  om
    } else {
        EndpointState epState = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
        if (epState == null || Gossiper.instance.isDeadState(epState)) {
            logger.debug("Ignoring state change for dead or unknown endpoint: {}", endpoint);
            return;
        }

        if (!endpoint.equals(Utils.getBroadcastAddress()))
            updatePeerInfo(endpoint, state, value);
    }
}

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

/**
 * Handle node move to normal state. That is, node is entering token ring and participating
 * in reads.//from  ww  w  .j a  va  2s.  c  om
 *
 * @param endpoint node
 * @param pieces STATE_NORMAL,token[,other_state,token]
 */
private void handleStateNormal(InetAddress endpoint, String[] pieces) {
    assert pieces.length >= 2;
    Token token = getPartitioner().getTokenFactory().fromString(pieces[1]);

    if (logger_.isDebugEnabled())
        logger_.debug("Node " + endpoint + " state normal, token " + token);

    if (tokenMetadata_.isMember(endpoint))
        logger_.info("Node " + endpoint + " state jump to normal");

    // we don't want to update if this node is responsible for the token and it has a later startup time than endpoint.
    InetAddress currentOwner = tokenMetadata_.getEndpoint(token);
    if (currentOwner == null) {
        logger_.debug("New node " + endpoint + " at token " + token);
        tokenMetadata_.updateNormalToken(token, endpoint);
        if (!isClientMode)
            SystemTable.updateToken(endpoint, token);
    } else if (endpoint.equals(currentOwner)) {
        // set state back to normal, since the node may have tried to leave, but failed and is now back up
        // no need to persist, token/ip did not change
        tokenMetadata_.updateNormalToken(token, endpoint);
    } else if (Gossiper.instance.compareEndpointStartup(endpoint, currentOwner) > 0) {
        logger_.info(String.format("Nodes %s and %s have the same token %s.  %s is the new owner", endpoint,
                currentOwner, token, endpoint));
        tokenMetadata_.updateNormalToken(token, endpoint);
        if (!isClientMode)
            SystemTable.updateToken(endpoint, token);
    } else {
        logger_.info(String.format("Nodes %s and %s have the same token %s.  Ignoring %s", endpoint,
                currentOwner, token, endpoint));
    }

    if (pieces.length > 2) {
        assert pieces.length == 4;
        handleStateRemoving(endpoint, getPartitioner().getTokenFactory().fromString(pieces[3]), pieces[2]);
    }

    if (tokenMetadata_.isMoving(endpoint)) // if endpoint was moving to a new token
        tokenMetadata_.removeFromMoving(endpoint);

    calculatePendingRanges();
}

From source file:org.sipfoundry.preflight.TFTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*w ww .  java 2 s . c  o  m*/
    InetAddress tftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No TFTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting TFTP server test.");

    TFTPClient tftp = new TFTPClient();

    tftp.setDefaultTimeout(timeout * 1000);

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            tftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using TFTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for TFTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up TFTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String(
                    "  TFTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return TFTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (tftpServerAddress == null) {
                        tftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same address.
                        if (!tftpServerAddress.equals(targetAddress)) {
                            journalService.println("  TFTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = TFTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((tftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting TFTP test.\n");
        return results;
    }

    journalService.println("Beginning TFTP get request of test file: " + testFile);
    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        journalService.println("TFTP client failure. " + e.getMessage() + "\n");
        return TFTP_CLIENT_FAILURE;
    }

    // Try to receive remote file via TFTP
    try {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tftp.open(bindPort, bindAddress);
        tftp.receiveFile(testFile, org.apache.commons.net.tftp.TFTP.ASCII_MODE, output, tftpServerAddress);
        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            results = TFTP_CONTENTS_FAILED;
        }
    } catch (UnknownHostException e) {
        journalService.println("TFTP client failure. " + e.getMessage());
        results = TFTP_CLIENT_FAILURE;
    } catch (IOException e) {
        journalService.println("TFTP get failed. " + e.getMessage());
        results = TFTP_GET_FAILED;
    } finally {
        // Close local socket and output file
        tftp.close();
    }

    journalService.println("");
    return results;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;/*  w  w w  .j  a v a 2 s  .  com*/
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

/**
 * Determines if any SNMP data collection related events need to be
 * generated based upon the results of the current rescan. If necessary
 * will generate one of the following events:
 * 'reinitializePrimarySnmpInterface' 'primarySnmpInterfaceChanged'
 *
 * @param nodeEntry  DbNodeEntry object of the node being rescanned.
 * @param oldPrimary Old primary SNMP interface
 * @param newPrimary New primary SNMP interface
 *//*  w  w  w . j av  a  2 s .  c o m*/
private void generateSnmpDataCollectionEvents(DbNodeEntry nodeEntry, InetAddress oldPrimary,
        InetAddress newPrimary) {
    // Sanity check -- should not happen
    if (oldPrimary == null && newPrimary == null) {
        LOG.warn("generateSnmpDataCollectionEvents: both old and new primary SNMP interface vars are null!");
    }

    // Sanity check -- should not happen
    else {
        if (oldPrimary != null && newPrimary == null) {
            LOG.warn("generateSnmpDataCollectionEvents: old primary ({}) is not null but new primary is null!",
                    str(oldPrimary));
        }

        // Just added the primary SNMP interface to the node, the
        // nodeGainedService
        // event already generated is sufficient to start SNMP data
        // collection...no
        // additional events are required.
        else {
            if (oldPrimary == null && newPrimary != null) {
                LOG.debug(
                        "generateSnmpDataCollectionEvents: identified {} as the primary SNMP interface for node {}",
                        str(newPrimary), nodeEntry.getNodeId());
            }

            // A PrimarySnmpInterfaceChanged event is generated if the scan
            // found a different primary SNMP interface than what is stored
            // in the database.
            //
            else {
                if (!oldPrimary.equals(newPrimary)) {
                    LOG.debug(
                            "generateSnmpDataCollectionEvents: primary SNMP interface has changed.  Was: {} Is: {}",
                            str(oldPrimary), str(newPrimary));

                    createAndSendPrimarySnmpInterfaceChangedEvent(nodeEntry.getNodeId(), newPrimary,
                            oldPrimary);
                }

                // The primary SNMP interface did not change but the Capsd scan just
                // added
                // an interface to the node so we need to update the interface
                // map which is maintained in memory for the purpose of doing
                // SNMP data collection. Therefore we generate a
                // reinitializePrimarySnmpInterface event so that this map
                // can be refreshed based on the most up to date information
                // in the database.
                else {
                    LOG.debug(
                            "generateSnmpDataCollectionEvents: Generating reinitializeSnmpInterface event for interface {}",
                            str(newPrimary));
                    createAndSendReinitializePrimarySnmpInterfaceEvent(nodeEntry.getNodeId(), newPrimary);
                }
            }
        }
    }
}