Example usage for java.net InetSocketAddress getAddress

List of usage examples for java.net InetSocketAddress getAddress

Introduction

In this page you can find the example usage for java.net InetSocketAddress getAddress.

Prototype

public final InetAddress getAddress() 

Source Link

Document

Gets the InetAddress .

Usage

From source file:org.openhab.binding.lifx.internal.LifxLightDiscovery.java

private void handlePacket(Packet packet, InetSocketAddress address) {
    logger.trace("Discovery : Packet type '{}' received from '{}' for '{}' with sequence '{}' and source '{}'",
            new Object[] { packet.getClass().getSimpleName(), address.toString(), packet.getTarget().getHex(),
                    packet.getSequence(), Long.toString(packet.getSource(), 16) });

    if (packet.getSource() == sourceId || packet.getSource() == 0) {
        MACAddress macAddress = packet.getTarget();
        DiscoveredLight light = discoveredLights.get(macAddress);

        if (packet instanceof StateServiceResponse) {
            int port = (int) ((StateServiceResponse) packet).getPort();
            if (port != 0) {
                try {
                    InetSocketAddress socketAddress = new InetSocketAddress(address.getAddress(), port);
                    if (light == null || (!socketAddress.equals(light.socketAddress))) {
                        if (light != null) {
                            light.cancelUnicastKey();
                        }/* w  w w. j  a  v a  2  s.  c  om*/

                        Selector lightSelector = selector;
                        if (lightSelector != null) {
                            String logId = getLogId(macAddress, socketAddress);
                            light = new DiscoveredLight(lightSelector, macAddress, socketAddress, logId,
                                    openUnicastChannel(lightSelector, logId, socketAddress));
                            discoveredLights.put(macAddress, light);
                        }
                    }
                } catch (Exception e) {
                    logger.warn("{} while connecting to IP address: {}", e.getClass().getSimpleName(),
                            e.getMessage());
                    return;
                }
            }
        } else if (light != null) {
            if (packet instanceof StateLabelResponse) {
                light.label = ((StateLabelResponse) packet).getLabel().trim();
            } else if (packet instanceof StateVersionResponse) {
                try {
                    light.product = Product
                            .getProductFromProductID(((StateVersionResponse) packet).getProduct());
                    light.productVersion = ((StateVersionResponse) packet).getVersion();
                } catch (IllegalArgumentException e) {
                    logger.debug("Discovered an unsupported light ({}): {}", light.macAddress.getAsLabel(),
                            e.getMessage());
                    light.supportedProduct = false;
                }
            }
        }

        if (light != null && light.isDataComplete()) {
            try {
                thingDiscovered(createDiscoveryResult(light));
            } catch (IllegalArgumentException e) {
                logger.trace("{} while creating discovery result of light ({})", e.getClass().getSimpleName(),
                        light.logId, e);
            }
        }
    }
}

From source file:org.openhab.binding.mart.handler.martHandler.java

/**
 * Reads a buffer from the channel and returns it
 * A buffer is essentially a block of memory into which you can write data, which
 * you can then later read again//from ww w  .  j av a2 s  .co  m
 *
 * @param theChannel
 * @param bufferSize
 * @param permittedClientAddress
 * @return
 */
protected ByteBuffer Reader(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) {
    // The lock() method locks the Lock instance so that all threads calling lock() are blocked until unlock() is
    // executed.
    lock.lock();
    try {
        // retrieves the channel's key representing its registration with the selector
        SelectionKey theSelectionKey = theChannel.keyFor(selector);
        if (theSelectionKey != null) {
            synchronized (selector) {
                try {
                    // it selects a set of keys whose corresponding channels are ready for I/O operations.
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occured while selecting: {}", e.getMessage());
                } catch (ClosedSelectorException e) {
                    logger.error("An exception occured while selecting: {}", e.getMessage());
                }
            }

            // to iterate over the this selector's selected key set
            Iterator<SelectionKey> iterate = selector.selectedKeys().iterator();
            // if iterate has more elements
            while (iterate.hasNext()) {
                // represents the key representing the channel's registration with the Selector (selector).
                SelectionKey selectKey = iterate.next();
                iterate.remove();
                if (selectKey.isValid() && selectKey.isReadable() && selectKey == theSelectionKey) {
                    // allocate a new byte buffer with 1024 bytes capacity
                    ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize);
                    int numOfBytesRead = 0;
                    boolean error = false;

                    // if the current select key is the key representing the listener's channel registration
                    // with the selector, then read the byte buffer or data from the channel
                    if (selectKey == listenerKey) {
                        try {
                            // receive a datagram via this channel
                            // the channel writes data into the the readBuffer
                            InetSocketAddress clientAddress = (InetSocketAddress) theChannel
                                    .receive(readBuffer);
                            // if the returned address given by the receive() is == permitted address
                            if (clientAddress.getAddress().equals(permittedClientAddress)) {
                                logger.debug("Received {} on the listener port from {}",
                                        new String(readBuffer.array()), clientAddress);
                                // returns the buffer's position to help as check whether the buffer is
                                // full or not
                                numOfBytesRead = readBuffer.position();
                            } else {
                                logger.warn(
                                        "Received data from '{}' which is not the permitted remote address '{}'",
                                        clientAddress, permittedClientAddress);
                                // since it is not a permitted remote address return nothing
                                return null;
                            }

                        } catch (Exception e) {
                            logger.error(
                                    "An exception occurred while receiving data on the listener port: '{}'",
                                    e.getMessage());
                            error = true;
                        }
                        // if the selectKey != listenerKey
                    } else {

                        try {
                            // reads a datagram from this channel though the selectKey != listenerKey
                            // reads a data from this channel into the readBuffer or
                            // the channel writes data into the the buffer
                            numOfBytesRead = theChannel.read(readBuffer);
                        } catch (NotYetConnectedException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "The MART adapter is not yet connected");
                            error = true;
                        } catch (PortUnreachableException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                                    "This is probably not a MART adapter");
                            error = true;
                        } catch (IOException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "An IO exception occurred");
                            error = true;
                        }
                    }

                    // if numOfBytesRead == -1 then the channel has reached end of stream
                    if (numOfBytesRead == -1) {
                        error = true;
                    }
                    // if error == true , close the channel and re-establish connection
                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            // close the channel
                            theChannel.close();
                        } catch (IOException e) {
                            logger.error("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        // re-establish connection
                        onConnectionLost();
                        // if error == false,
                    } else {
                        // switch the buffer from writing mode into reading mode and return it
                        readBuffer.flip();
                        return readBuffer;

                    }
                }
            }
        }
        return null;

    } finally {
        lock.unlock();
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.AvatarNode.java

/**
 * Returns the hostname:port for the AvatarNode. The default
 * port for the AvatarNode is (the client RPC port 
 * of the underlying namenode + 1)//from  ww  w. j  a v a2  s .c  om
 */
public static InetSocketAddress getAddress(Configuration conf) {
    InetSocketAddress u = NameNode.getClientProtocolAddress(conf);
    int port = conf.getInt(AvatarNode.DFS_AVATARNODE_PORT_KEY, u.getPort() + 1);
    return new InetSocketAddress(u.getAddress(), port);
}

From source file:de.schildbach.wallet.service.BlockchainService.java

private void observeLiveDatasThatAreDependentOnWalletAndBlockchain() {
    final NewTransactionLiveData newTransaction = new NewTransactionLiveData(wallet.getValue());
    newTransaction.observe(this, new Observer<Transaction>() {
        @Override//from  www . j a  v  a2  s  .c o m
        public void onChanged(final Transaction tx) {
            final Wallet wallet = BlockchainService.this.wallet.getValue();
            transactionsReceived.incrementAndGet();
            final Coin amount = tx.getValue(wallet);
            if (amount.isPositive()) {
                final Address address = WalletUtils.getWalletAddressOfReceived(tx, wallet);
                final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
                final Sha256Hash hash = tx.getHash();
                final boolean replaying = blockChain.getBestChainHeight() < config.getBestChainHeightEver();
                final boolean isReplayedTx = confidenceType == ConfidenceType.BUILDING && replaying;
                if (!isReplayedTx)
                    notifyCoinsReceived(address, amount, hash);
            }
        }
    });
    final TimeLiveData time = new TimeLiveData(application);
    time.observe(this, new Observer<Date>() {
        private int lastChainHeight = 0;
        private final List<ActivityHistoryEntry> activityHistory = new LinkedList<ActivityHistoryEntry>();

        @Override
        public void onChanged(final Date time) {
            final int chainHeight = blockChain.getBestChainHeight();

            if (lastChainHeight > 0) {
                final int numBlocksDownloaded = chainHeight - lastChainHeight;
                final int numTransactionsReceived = transactionsReceived.getAndSet(0);

                // push history
                activityHistory.add(0, new ActivityHistoryEntry(numTransactionsReceived, numBlocksDownloaded));

                // trim
                while (activityHistory.size() > MAX_HISTORY_SIZE)
                    activityHistory.remove(activityHistory.size() - 1);

                // print
                final StringBuilder builder = new StringBuilder();
                for (final ActivityHistoryEntry entry : activityHistory) {
                    if (builder.length() > 0)
                        builder.append(", ");
                    builder.append(entry);
                }
                log.info("History of transactions/blocks: " + builder);

                // determine if block and transaction activity is idling
                boolean isIdle = false;
                if (activityHistory.size() >= MIN_COLLECT_HISTORY) {
                    isIdle = true;
                    for (int i = 0; i < activityHistory.size(); i++) {
                        final ActivityHistoryEntry entry = activityHistory.get(i);
                        final boolean blocksActive = entry.numBlocksDownloaded > 0
                                && i <= IDLE_BLOCK_TIMEOUT_MIN;
                        final boolean transactionsActive = entry.numTransactionsReceived > 0
                                && i <= IDLE_TRANSACTION_TIMEOUT_MIN;

                        if (blocksActive || transactionsActive) {
                            isIdle = false;
                            break;
                        }
                    }
                }

                // if idling, shutdown service
                if (isIdle) {
                    log.info("idling detected, stopping service");
                    stopSelf();
                }
            }

            lastChainHeight = chainHeight;
        }

        final class ActivityHistoryEntry {
            public final int numTransactionsReceived;
            public final int numBlocksDownloaded;

            public ActivityHistoryEntry(final int numTransactionsReceived, final int numBlocksDownloaded) {
                this.numTransactionsReceived = numTransactionsReceived;
                this.numBlocksDownloaded = numBlocksDownloaded;
            }

            @Override
            public String toString() {
                return numTransactionsReceived + "/" + numBlocksDownloaded;
            }
        }
    });
    impediments = new ImpedimentsLiveData(application);
    impediments.observe(this, new Observer<Set<Impediment>>() {
        @Override
        public void onChanged(final Set<Impediment> impediments) {
            if (impediments.isEmpty() && peerGroup == null && Constants.ENABLE_BLOCKCHAIN_SYNC)
                startup();
            else if (!impediments.isEmpty() && peerGroup != null)
                shutdown();
            broadcastBlockchainState();
        }

        private void startup() {
            log.debug("acquiring wakelock");
            wakeLock.acquire();
            final Wallet wallet = BlockchainService.this.wallet.getValue();

            // consistency check
            final int walletLastBlockSeenHeight = wallet.getLastBlockSeenHeight();
            final int bestChainHeight = blockChain.getBestChainHeight();
            if (walletLastBlockSeenHeight != -1 && walletLastBlockSeenHeight != bestChainHeight) {
                final String message = "wallet/blockchain out of sync: " + walletLastBlockSeenHeight + "/"
                        + bestChainHeight;
                log.error(message);
                CrashReporter.saveBackgroundTrace(new RuntimeException(message), application.packageInfo());
            }

            peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
            log.info("creating {}", peerGroup);
            peerGroup.setDownloadTxDependencies(0); // recursive implementation causes StackOverflowError
            peerGroup.addWallet(wallet);
            peerGroup.setUserAgent(Constants.USER_AGENT, application.packageInfo().versionName);
            peerGroup.addConnectedEventListener(peerConnectivityListener);
            peerGroup.addDisconnectedEventListener(peerConnectivityListener);

            final int maxConnectedPeers = application.maxConnectedPeers();

            final String trustedPeerHost = config.getTrustedPeerHost();
            final boolean hasTrustedPeer = trustedPeerHost != null;

            final boolean connectTrustedPeerOnly = hasTrustedPeer && config.getTrustedPeerOnly();
            peerGroup.setMaxConnections(connectTrustedPeerOnly ? 1 : maxConnectedPeers);
            peerGroup.setConnectTimeoutMillis(Constants.PEER_TIMEOUT_MS);
            peerGroup.setPeerDiscoveryTimeoutMillis(Constants.PEER_DISCOVERY_TIMEOUT_MS);

            peerGroup.addPeerDiscovery(new PeerDiscovery() {
                private final PeerDiscovery normalPeerDiscovery = MultiplexingDiscovery
                        .forServices(Constants.NETWORK_PARAMETERS, 0);

                @Override
                public InetSocketAddress[] getPeers(final long services, final long timeoutValue,
                        final TimeUnit timeoutUnit) throws PeerDiscoveryException {
                    final List<InetSocketAddress> peers = new LinkedList<InetSocketAddress>();

                    boolean needsTrimPeersWorkaround = false;

                    if (hasTrustedPeer) {
                        log.info("trusted peer '" + trustedPeerHost + "'"
                                + (connectTrustedPeerOnly ? " only" : ""));

                        final InetSocketAddress addr = new InetSocketAddress(trustedPeerHost,
                                Constants.NETWORK_PARAMETERS.getPort());
                        if (addr.getAddress() != null) {
                            peers.add(addr);
                            needsTrimPeersWorkaround = true;
                        }
                    }

                    if (!connectTrustedPeerOnly)
                        peers.addAll(Arrays
                                .asList(normalPeerDiscovery.getPeers(services, timeoutValue, timeoutUnit)));

                    // workaround because PeerGroup will shuffle peers
                    if (needsTrimPeersWorkaround)
                        while (peers.size() >= maxConnectedPeers)
                            peers.remove(peers.size() - 1);

                    return peers.toArray(new InetSocketAddress[0]);
                }

                @Override
                public void shutdown() {
                    normalPeerDiscovery.shutdown();
                }
            });

            // start peergroup
            log.info("starting {} asynchronously", peerGroup);
            peerGroup.startAsync();
            peerGroup.startBlockChainDownload(blockchainDownloadListener);
        }

        private void shutdown() {
            final Wallet wallet = BlockchainService.this.wallet.getValue();

            peerGroup.removeDisconnectedEventListener(peerConnectivityListener);
            peerGroup.removeConnectedEventListener(peerConnectivityListener);
            peerGroup.removeWallet(wallet);
            log.info("stopping {} asynchronously", peerGroup);
            peerGroup.stopAsync();
            peerGroup = null;

            log.debug("releasing wakelock");
            wakeLock.release();
        }
    });
}

From source file:org.jitsi.android.gui.call.CallInfoDialogFragment.java

/**
 * Updates audio video peer info./*from   ww w . j a v a2s.  co  m*/
 *
 * @param callPeerMediaHandler The <tt>CallPeerMadiaHandler</tt> containing
 * the AUDIO/VIDEO stream.
 * @param mediaType The media type used to determine which stream of the
 * media handler will be used.
 */
private void updateAudioVideoInfo(CallPeerMediaHandler<?> callPeerMediaHandler, MediaType mediaType) {
    View container = mediaType == MediaType.AUDIO ? getView().findViewById(R.id.audioInfo)
            : getView().findViewById(R.id.videoInfo);

    MediaStream mediaStream = callPeerMediaHandler.getStream(mediaType);

    MediaStreamStats mediaStreamStats = null;
    if (mediaStream != null) {
        mediaStreamStats = mediaStream.getMediaStreamStats();
    }

    // Hides the whole section if stats are not available.
    ensureVisible(getView(), container.getId(), mediaStreamStats != null);
    if (mediaStreamStats == null) {
        return;
    }

    // Sets the encryption status String.
    setTextViewValue(container, R.id.mediaTransport,
            getStreamEncryptionMethod(callPeerMediaHandler, mediaStream, mediaType));
    // Set the title label to Video info if it's a video stream.
    if (mediaType == MediaType.VIDEO) {
        setTextViewValue(container, R.id.audioVideoLabel, getString(R.string.service_gui_callinfo_VIDEO_INFO));
    }

    boolean hasVideoSize = false;

    if (mediaType == MediaType.VIDEO) {
        Dimension downloadVideoSize = mediaStreamStats.getDownloadVideoSize();
        Dimension uploadVideoSize = mediaStreamStats.getUploadVideoSize();
        // Checks that at least one video stream is active.
        if (downloadVideoSize != null || uploadVideoSize != null) {
            hasVideoSize = true;
            setTextViewValue(container, R.id.videoSize,
                    DOWN_ARROW + " " + this.videoSizeToString(downloadVideoSize) + " " + UP_ARROW + " "
                            + this.videoSizeToString(uploadVideoSize));
        }
        // Otherwise, quit the stats for this video stream.
        else {
            ensureVisible(container, container.getId(), false);
            return;
        }
    }

    // Shows video size if it's available(always false for AUDIO)
    ensureVisible(container, R.id.videoSize, hasVideoSize);
    ensureVisible(container, R.id.videoSizeLabel, hasVideoSize);

    // Codec.
    setTextViewValue(container, R.id.codec,
            mediaStreamStats.getEncoding() + " / " + mediaStreamStats.getEncodingClockRate() + " Hz");

    boolean displayedIpPort = false;

    // ICE candidate type.
    String iceCandidateExtendedType = callPeerMediaHandler.getICECandidateExtendedType(mediaType.toString());

    boolean iceCandidateExtVisible = iceCandidateExtendedType != null;

    ensureVisible(container, R.id.iceExtType, iceCandidateExtVisible);
    ensureVisible(container, R.id.iceExtTypeLabel, iceCandidateExtVisible);

    if (iceCandidateExtVisible) {
        setTextViewValue(container, R.id.iceExtType, iceCandidateExtendedType);
        displayedIpPort = true;
    }

    // Local host address.
    InetSocketAddress iceLocalHostAddress = callPeerMediaHandler.getICELocalHostAddress(mediaType.toString());

    boolean iceLocalHostVisible = iceLocalHostAddress != null;

    ensureVisible(container, R.id.iceLocalHost, iceLocalHostVisible);
    ensureVisible(container, R.id.localHostLabel, iceLocalHostVisible);

    if (iceLocalHostVisible) {
        setTextViewValue(container, R.id.iceLocalHost,
                iceLocalHostAddress.getAddress().getHostAddress() + "/" + iceLocalHostAddress.getPort());
        displayedIpPort = true;
    }

    // Local reflexive address.
    InetSocketAddress iceLocalReflexiveAddress = callPeerMediaHandler
            .getICELocalReflexiveAddress(mediaType.toString());

    boolean iceLocalReflexiveVisible = iceLocalReflexiveAddress != null;

    ensureVisible(container, R.id.iceLocalReflx, iceLocalReflexiveVisible);
    ensureVisible(container, R.id.iceLocalReflxLabel, iceLocalReflexiveVisible);

    if (iceLocalReflexiveVisible) {
        setTextViewValue(container, R.id.iceLocalReflx, iceLocalReflexiveAddress.getAddress().getHostAddress()
                + "/" + iceLocalReflexiveAddress.getPort());
        displayedIpPort = true;
    }

    // Local relayed address.
    InetSocketAddress iceLocalRelayedAddress = callPeerMediaHandler
            .getICELocalRelayedAddress(mediaType.toString());
    boolean iceLocalRelayedVisible = iceLocalRelayedAddress != null;

    ensureVisible(container, R.id.iceLocalRelayed, iceLocalRelayedVisible);
    ensureVisible(container, R.id.iceLocalRelayedLabel, iceLocalRelayedVisible);

    if (iceLocalRelayedAddress != null) {
        setTextViewValue(container, R.id.iceLocalRelayed,
                iceLocalRelayedAddress.getAddress().getHostAddress() + "/" + iceLocalRelayedAddress.getPort());
        displayedIpPort = true;
    }

    // Remote relayed address.
    InetSocketAddress iceRemoteRelayedAddress = callPeerMediaHandler
            .getICERemoteRelayedAddress(mediaType.toString());

    boolean isIceRemoteRelayed = iceRemoteRelayedAddress != null;

    ensureVisible(container, R.id.iceRemoteRelayed, isIceRemoteRelayed);
    ensureVisible(container, R.id.iceRemoteRelayedLabel, isIceRemoteRelayed);

    if (isIceRemoteRelayed) {
        setTextViewValue(container, R.id.iceRemoteRelayed, iceRemoteRelayedAddress.getAddress().getHostAddress()
                + "/" + iceRemoteRelayedAddress.getPort());
        displayedIpPort = true;
    }

    // Remote reflexive address.
    InetSocketAddress iceRemoteReflexiveAddress = callPeerMediaHandler
            .getICERemoteReflexiveAddress(mediaType.toString());

    boolean isIceRemoteReflexive = iceRemoteReflexiveAddress != null;

    ensureVisible(container, R.id.iceRemoteReflexive, isIceRemoteReflexive);
    ensureVisible(container, R.id.iceRemoteReflxLabel, isIceRemoteReflexive);

    if (isIceRemoteReflexive) {
        setTextViewValue(container, R.id.iceRemoteReflexive,
                iceRemoteReflexiveAddress.getAddress().getHostAddress() + "/"
                        + iceRemoteReflexiveAddress.getPort());
        displayedIpPort = true;
    }

    // Remote host address.
    InetSocketAddress iceRemoteHostAddress = callPeerMediaHandler.getICERemoteHostAddress(mediaType.toString());

    boolean isIceRemoteHost = iceRemoteHostAddress != null;

    ensureVisible(container, R.id.iceRemoteHostLabel, isIceRemoteHost);
    ensureVisible(container, R.id.iceRemoteHost, isIceRemoteHost);

    if (isIceRemoteHost) {
        setTextViewValue(container, R.id.iceRemoteHost,
                iceRemoteHostAddress.getAddress().getHostAddress() + "/" + iceRemoteHostAddress.getPort());
        displayedIpPort = true;
    }

    // If the stream does not use ICE, then show the transport IP/port.
    ensureVisible(container, R.id.localIp, !displayedIpPort);
    ensureVisible(container, R.id.localIpLabel, !displayedIpPort);
    ensureVisible(container, R.id.remoteIp, !displayedIpPort);
    ensureVisible(container, R.id.remoteIpLabel, !displayedIpPort);
    if (!displayedIpPort) {
        setTextViewValue(container, R.id.localIp,
                mediaStreamStats.getLocalIPAddress() + " / " + String.valueOf(mediaStreamStats.getLocalPort()));
        setTextViewValue(container, R.id.remoteIp, mediaStreamStats.getRemoteIPAddress() + " / "
                + String.valueOf(mediaStreamStats.getRemotePort()));
    }

    // Bandwidth.
    String bandwidthStr = DOWN_ARROW + " " + (int) mediaStreamStats.getDownloadRateKiloBitPerSec() + " Kbps "
            + " " + UP_ARROW + " " + (int) mediaStreamStats.getUploadRateKiloBitPerSec() + " Kbps";
    setTextViewValue(container, R.id.bandwidth, bandwidthStr);

    // Loss rate.
    String lossRateStr = DOWN_ARROW + " " + (int) mediaStreamStats.getDownloadPercentLoss() + "% " + UP_ARROW
            + " " + (int) mediaStreamStats.getUploadPercentLoss() + "%";
    setTextViewValue(container, R.id.lossRate, lossRateStr);

    // Decoded with FEC.
    setTextViewValue(container, R.id.decodedWithFEC, String.valueOf(mediaStreamStats.getNbFec()));

    // Discarded percent.
    setTextViewValue(container, R.id.discardedPercent,
            String.valueOf((int) mediaStreamStats.getPercentDiscarded() + "%"));

    // Discarded total.
    String discardedTotalStr = String.valueOf(mediaStreamStats.getNbDiscarded()) + " ("
            + mediaStreamStats.getNbDiscardedLate() + " late, " + mediaStreamStats.getNbDiscardedFull()
            + " full, " + mediaStreamStats.getNbDiscardedShrink() + " shrink, "
            + mediaStreamStats.getNbDiscardedReset() + " reset)";
    setTextViewValue(container, R.id.discardedTotal, discardedTotalStr);

    // Adaptive jitter buffer.
    setTextViewValue(container, R.id.adaptiveJitterBuffer,
            mediaStreamStats.isAdaptiveBufferEnabled() ? "enabled" : "disabled");

    // Jitter buffer delay.
    String jitterDelayStr = "~" + mediaStreamStats.getJitterBufferDelayMs() + "ms; currently in queue: "
            + mediaStreamStats.getPacketQueueCountPackets() + "/" + mediaStreamStats.getPacketQueueSize()
            + " packets";
    setTextViewValue(container, R.id.jitterBuffer, jitterDelayStr);

    // RTT
    String naStr = getString(R.string.service_gui_callinfo_NA);
    long rttMs = mediaStreamStats.getRttMs();
    String rttStr = rttMs != -1 ? rttMs + " ms" : naStr;
    setTextViewValue(container, R.id.RTT, rttStr);

    // Jitter.
    setTextViewValue(container, R.id.jitter, DOWN_ARROW + " " + (int) mediaStreamStats.getDownloadJitterMs()
            + " ms " + UP_ARROW + (int) mediaStreamStats.getUploadJitterMs() + " ms");
}

From source file:org.apache.bookkeeper.client.TestRegionAwareEnsemblePlacementPolicy.java

@Test(timeout = 60000)
public void testNewEnsembleWithEnoughRegions() throws Exception {
    InetSocketAddress addr1 = new InetSocketAddress("127.0.0.2", 3181);
    InetSocketAddress addr2 = new InetSocketAddress("127.0.0.3", 3181);
    InetSocketAddress addr3 = new InetSocketAddress("127.0.0.4", 3181);
    InetSocketAddress addr4 = new InetSocketAddress("127.0.0.5", 3181);
    InetSocketAddress addr5 = new InetSocketAddress("127.0.0.6", 3181);
    InetSocketAddress addr6 = new InetSocketAddress("127.0.0.7", 3181);
    InetSocketAddress addr7 = new InetSocketAddress("127.0.0.8", 3181);
    InetSocketAddress addr8 = new InetSocketAddress("127.0.0.9", 3181);
    // update dns mapping
    StaticDNSResolver.addNodeToRack(addr1.getAddress().getHostAddress(), "/default-region/default-rack1");
    StaticDNSResolver.addNodeToRack(addr2.getAddress().getHostAddress(), "/region1/r2");
    StaticDNSResolver.addNodeToRack(addr3.getAddress().getHostAddress(), "/region2/r3");
    StaticDNSResolver.addNodeToRack(addr4.getAddress().getHostAddress(), "/region3/r4");
    StaticDNSResolver.addNodeToRack(addr5.getAddress().getHostAddress(), "/default-region/default-rack2");
    StaticDNSResolver.addNodeToRack(addr6.getAddress().getHostAddress(), "/region1/r12");
    StaticDNSResolver.addNodeToRack(addr7.getAddress().getHostAddress(), "/region2/r13");
    StaticDNSResolver.addNodeToRack(addr8.getAddress().getHostAddress(), "/region3/r14");
    // Update cluster
    Set<InetSocketAddress> addrs = new HashSet<InetSocketAddress>();
    addrs.add(addr1);/*from   www .  j a va  2s.com*/
    addrs.add(addr2);
    addrs.add(addr3);
    addrs.add(addr4);
    addrs.add(addr5);
    addrs.add(addr6);
    addrs.add(addr7);
    addrs.add(addr8);
    repp.onClusterChanged(addrs, new HashSet<InetSocketAddress>());
    try {
        ArrayList<InetSocketAddress> ensemble1 = repp.newEnsemble(3, 2, new HashSet<InetSocketAddress>());
        assertEquals(3, getNumCoveredRegionsInWriteQuorum(ensemble1, 2));
        ArrayList<InetSocketAddress> ensemble2 = repp.newEnsemble(4, 2, new HashSet<InetSocketAddress>());
        assertEquals(4, getNumCoveredRegionsInWriteQuorum(ensemble2, 2));
    } catch (BKNotEnoughBookiesException bnebe) {
        fail("Should not get not enough bookies exception even there is only one rack.");
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.Standby.java

/**
 * Initialize the webserver so that the primary namenode can fetch
 * transaction logs from standby via http.
 *///  w ww  .ja va2s  .c o  m
void initSecondary(Configuration conf) throws IOException {

    fsName = AvatarNode.getRemoteNamenodeHttpName(conf, avatarNode.getInstanceId());

    // Initialize other scheduling parameters from the configuration
    checkpointEnabled = conf.getBoolean("fs.checkpoint.enabled", false);
    checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600);
    checkpointTxnCount = NNStorageConfiguration.getCheckpointTxnCount(conf);
    delayedScheduledCheckpointTime = conf.getBoolean("fs.checkpoint.delayed", false)
            ? AvatarNode.now() + checkpointPeriod * 1000
            : 0;

    // initialize the webserver for uploading files.
    String infoAddr = NetUtils.getServerAddress(conf, "dfs.secondary.info.bindAddress",
            "dfs.secondary.info.port", "dfs.secondary.http.address");
    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr);
    String infoBindIpAddress = infoSocAddr.getAddress().getHostAddress();
    int tmpInfoPort = infoSocAddr.getPort();
    infoServer = new HttpServer("secondary", infoBindIpAddress, tmpInfoPort, tmpInfoPort == 0, conf);
    infoServer.setAttribute("name.system.image", fsImage);
    this.infoServer.setAttribute("name.conf", conf);
    infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class);
    infoServer.start();
    avatarNode.httpServer.setAttribute("avatar.node", avatarNode);
    avatarNode.httpServer.addInternalServlet("outstandingnodes", "/outstandingnodes",
            OutStandingDatanodesServlet.class);

    // The web-server port can be ephemeral... ensure we have the correct info
    infoPort = infoServer.getPort();
    conf.set("dfs.secondary.http.address", infoBindIpAddress + ":" + infoPort);
    LOG.info("Secondary Web-server up at: " + infoBindIpAddress + ":" + infoPort);
    LOG.warn("Checkpoint Period   :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)");
    if (delayedScheduledCheckpointTime > 0) {
        LOG.warn("Standby: Checkpointing will be delayed by: " + checkpointPeriod + " seconds");
    }
    LOG.warn("Log Size Trigger    :" + checkpointTxnCount + " transactions.");
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

/**
 * @since 4.1/*from w  ww  .  j  a v  a2s .c  o m*/
 */
@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : new Socket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(
                "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        sslsock = (SSLSocket) getSocketFactory().createSocket(sock, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
        sslsock = enableSocket(sslsock);
    }
    // do we need it? trust all hosts
    //      if( getHostnameVerifier() != null )
    //      {
    //         try
    //         {
    //            getHostnameVerifier().verify( remoteAddress.getHostName(), sslsock );
    //            // verifyHostName() didn't blowup - good!
    //         }
    //         catch( IOException iox )
    //         {
    //            // close the socket before re-throwing the exception
    //            try
    //            {
    //               sslsock.close();
    //            }
    //            catch( Exception x )
    //            { /* ignore */
    //            }
    //            throw iox;
    //         }
    //      }
    return sslsock;
}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testStartTlsNotSupported() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//from  ww w. j av  a2 s . c  om
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.sendCommand("STARTTLS");
        assertTrue(SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();
        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.apache.james.protocols.smtp.AbstractSMTPServerTest.java

@Test
public void testUnknownCommand() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;/*from  ww  w . ja  va 2 s .c o m*/
    try {
        server = createServer(createProtocol(hook), address);
        server.bind();

        SMTPClient client = createClient();
        client.connect(address.getAddress().getHostAddress(), address.getPort());
        assertTrue(SMTPReply.isPositiveCompletion(client.getReplyCode()));

        client.sendCommand("UNKNOWN");
        assertTrue(SMTPReply.isNegativePermanent(client.getReplyCode()));

        client.quit();
        assertTrue("Reply=" + client.getReplyString(), SMTPReply.isPositiveCompletion(client.getReplyCode()));
        client.disconnect();
        Iterator<MailEnvelope> queued = hook.getQueued().iterator();
        assertFalse(queued.hasNext());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}