Java Code Examples for org.jboss.netty.channel.Channel#isOpen()

The following examples show how to use org.jboss.netty.channel.Channel#isOpen() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 6 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception {
	
	/* Get audio channel from the enclosing RaopAudioHandler */
	Channel tempAudioChannel = null;
	synchronized(RaopAudioHandler.this) {
		tempAudioChannel = audioChannel;
	}

	if ((tempAudioChannel != null) && tempAudioChannel.isOpen() && tempAudioChannel.isReadable()) {
		tempAudioChannel.getPipeline().sendUpstream(new UpstreamMessageEvent(
			tempAudioChannel,
			evt.getMessage(),
			evt.getRemoteAddress())
		);
	}
}
 
Example 2
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 6 votes vote down vote up
private Channel lookupInCache(URI uri) {
	Channel channel = connectionsPool.remove(getBaseUrl(uri));
	if (channel != null) {
		/**
		 * The Channel will eventually be closed by Netty and will becomes invalid.
		 * We might suffer a memory leak if we don't scan for closed channel. The
		 * AsyncHttpClientConfig.reaper() will always make sure those are cleared.
		 */
		if (channel.isOpen()) {
			channel.setReadable(true);
		} else {
			return null;
		}
	}
	return channel;
}
 
Example 3
Source File: NettyTransport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public synchronized void close() {
    List<ChannelFuture> futures = new ArrayList<>();
    for (Channel channel : allChannels) {
        try {
            if (channel != null && channel.isOpen()) {
                futures.add(channel.close());
            }
        } catch (Exception e) {
            //ignore
        }
    }
    for (ChannelFuture future : futures) {
        future.awaitUninterruptibly();
    }
}
 
Example 4
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception {
	final RaopRtpPacket packet = (RaopRtpPacket)evt.getMessage();

	/* Get control and timing channel from the enclosing RaopAudioHandler */
	Channel tempControlChannel = null;
	Channel tempTimingChannel = null;
	
	synchronized(RaopAudioHandler.this) {
		tempControlChannel = controlChannel;
		tempTimingChannel = timingChannel;
	}

	if (packet instanceof RaopRtpPacket.RetransmitRequest) {
		if ((tempControlChannel != null) && tempControlChannel.isOpen() && tempControlChannel.isWritable()){
			tempControlChannel.write(evt.getMessage());
		}
	}
	else if (packet instanceof RaopRtpPacket.TimingRequest) {
		if ((tempTimingChannel != null) && tempTimingChannel.isOpen() && tempTimingChannel.isWritable()){
			tempTimingChannel.write(evt.getMessage());
		}
	}
	else {
		super.writeRequested(ctx, evt);
	}
}
 
Example 5
Source File: DefaultIsisInterface.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sends LS PDU message to channel.
 *
 * @param lsp     LS PDU message instance
 * @param channel channel instance
 */
private void sendLsp(LsPdu lsp, Channel channel) {
    byte[] lspBytes = lsp.asBytes();
    lspBytes = IsisUtil.addLengthAndMarkItInReserved(lspBytes, IsisConstants.LENGTHPOSITION,
                                                     IsisConstants.LENGTHPOSITION + 1,
                                                     IsisConstants.RESERVEDPOSITION);
    lspBytes = IsisUtil.addChecksum(lspBytes, IsisConstants.CHECKSUMPOSITION,
                                    IsisConstants.CHECKSUMPOSITION + 1);
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(lspBytes, interfaceIndex));
    }
}
 
Example 6
Source File: DefaultIsisInterface.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the partial sequence number PDU.
 *
 * @param lspEntryRequestList list of lsp entry request
 * @param isisPduType         intermediate system PDU type
 * @param channel             netty channel instance
 */
private void sendPsnPduMessage(List<LspEntry> lspEntryRequestList, IsisPduType isisPduType, Channel channel) {
    IsisHeader isisHeader = new LspGenerator().getHeader(isisPduType);
    Psnp psnp = new Psnp(isisHeader);
    psnp.setSourceId(lspKeyP2P(this.systemId));
    TlvHeader tlvHeader = new TlvHeader();
    tlvHeader.setTlvType(TlvType.LSPENTRY.value());
    tlvHeader.setTlvLength(0);
    LspEntriesTlv lspEntriesTlv = new LspEntriesTlv(tlvHeader);
    for (LspEntry lspEntry : lspEntryRequestList) {
        lspEntry.setLspChecksum(0);
        lspEntry.setLspSequenceNumber(0);
        lspEntry.setRemainingTime(0);
        lspEntriesTlv.addLspEntry(lspEntry);
    }
    psnp.addTlv(lspEntriesTlv);
    //write it to channel buffer.
    byte[] psnpBytes = psnp.asBytes();
    psnpBytes = IsisUtil.addLengthAndMarkItInReserved(psnpBytes, IsisConstants.LENGTHPOSITION,
                                                      IsisConstants.LENGTHPOSITION + 1,
                                                      IsisConstants.RESERVEDPOSITION);
    flagValue = false;
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(psnpBytes, interfaceIndex));
    }
}
 
Example 7
Source File: RaopRtpRetransmitRequestHandler.java    From Android-Airplay-Server with MIT License 4 votes vote down vote up
/**
 * Scan the list of in-flight retransmit requests and send
 * {@link RetransmitRequest} packets if it's past the time
 * at which we expected the packet to arrive
 * 
 * @param channel channel used to send retransmit requests
 * @param nextSecondsTime
 */
private synchronized void requestRetransmits(final Channel channel, final double nextSecondsTime) {
	/* The retransmit request we're currently building */
	RaopRtpPacket.RetransmitRequest retransmitRequest = null;

	/* Run through open retransmit requests */
	final Iterator<MissingPacket> missingPacketIterator = m_missingPackets.iterator();
	while (missingPacketIterator.hasNext()) {
		final MissingPacket missingPacket = missingPacketIterator.next();

		/* If it's past the time at which the packet would have needed to be queued,
		 * warn and forget about it
		 */
		if (missingPacket.requiredUntilSecondsTime <= nextSecondsTime) {
			s_logger.warning("Packet " + missingPacket.sequence + " was required " + (nextSecondsTime - missingPacket.requiredUntilSecondsTime) + " secons ago, giving up");

			missingPacketIterator.remove();
			continue;
		}

		/* If the packet isn't expected until later,
		 * skip it for now */
		if (missingPacket.expectedUntilSecondsTime > nextSecondsTime)
			continue;

		/* Ok, the packet is overdue */
		
		if (missingPacket.retransmitRequestCount >= RetransmitAttempts) {
			/* If the packet was already requests too often,
			 * warn and forget about it */
			s_logger.warning("Packet " + missingPacket.sequence + " overdue " + (nextSecondsTime - missingPacket.expectedUntilSecondsTime) + " seconds after " + missingPacket.retransmitRequestCount + " retransmit requests, giving up");

			missingPacketIterator.remove();
			continue;
		}
		else {
			/* Log that we're about to request retransmission */
			final int retransmitRequestCountPrevious = missingPacket.retransmitRequestCount;
			final double expectedUntilSecondsTimePrevious = missingPacket.expectedUntilSecondsTime;
			missingPacket.sentRetransmitRequest(nextSecondsTime);

			s_logger.fine("Packet " + missingPacket.sequence + " overdue " + (nextSecondsTime - expectedUntilSecondsTimePrevious) + " seconds after " + retransmitRequestCountPrevious + " retransmit requests, requesting again expecting response in " + (missingPacket.expectedUntilSecondsTime - nextSecondsTime) + " seconds");
		}

		/* Ok, really request re-transmission */
		
		if (
			(retransmitRequest != null) &&
			(sequenceAdd(retransmitRequest.getSequenceFirst(), retransmitRequest.getSequenceCount()) != missingPacket.sequence)
		) {
			/* There is a current retransmit request, but the sequence cannot be appended.
			 * We transmit the current request and start building a new one
			 */
			if (channel.isOpen() && channel.isWritable())
				channel.write(retransmitRequest);
			retransmitRequest = null;
		}
		
		/* If there still is a current retransmit request, the sequence can be appended */

		if (retransmitRequest == null) {
			/* Create new retransmit request */
			m_retransmitRequestSequence = sequenceSuccessor(m_retransmitRequestSequence);
			retransmitRequest = new RaopRtpPacket.RetransmitRequest();
			retransmitRequest.setSequence(m_retransmitRequestSequence);
			retransmitRequest.setSequenceFirst(missingPacket.sequence);
			retransmitRequest.setSequenceCount(1);
		}
		else {
			/* Append sequnce to current retransmit request */
			retransmitRequest.setSequenceCount(retransmitRequest.getSequenceCount() + 1);
		}
	}
	if (retransmitRequest != null) {
		/* Send the retransmit request we were building when the loop ended */
		if (channel.isOpen() && channel.isWritable())
			channel.write(retransmitRequest);
	}
}
 
Example 8
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 4 votes vote down vote up
private <T> Future<T> doConnect(final Request request, final AsyncHandler<T> asyncHandler, NettyResponseFuture<T> f) throws IOException{

		if (isClose.get()){
			throw new IOException("Closed");
		}

		if (activeConnectionsCount.getAndIncrement() >= config.getMaxTotalConnections()) {
			throw new IOException("Too many connections");
		}
		URI uri = createUri(request.getUrl());

		if (log.isDebugEnabled())
			log.debug("Lookup cache: " + uri.toString());

		Channel channel = lookupInCache(uri);
		if (channel != null && channel.isOpen()) {
			HttpRequest nettyRequest = buildRequest(config,request,uri);
			if (f == null) {
				f = new NettyResponseFuture<T>(uri, request, asyncHandler,
						nettyRequest, config.getRequestTimeoutInMs());
			}
			executeRequest(channel, config,f,nettyRequest);
			return f;
		}
		ConnectListener<T> c = new ConnectListener.Builder<T>(config, request, asyncHandler,f).build();
		configure(uri.getScheme().compareToIgnoreCase("https") == 0, c);

		ChannelFuture channelFuture;
		try{
			if (config.getProxyServer() == null) {
				channelFuture = bootstrap.connect(new InetSocketAddress(uri.getHost(), getPort(uri)));
			} else {
				channelFuture = bootstrap.connect(
						new InetSocketAddress(config.getProxyServer().getHost(), config.getProxyServer().getPort()));
			}
			bootstrap.setOption("connectTimeout", config.getConnectionTimeoutInMs());
		} catch (Throwable t){
			activeConnectionsCount.decrementAndGet();
			log.error(t);
			c.future().abort(t.getCause());
			return c.future();
		}
		channelFuture.addListener(c);
		openChannels.add(channelFuture.getChannel());
		return c.future();
	}
 
Example 9
Source File: DefaultIsisInterface.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Processes LS PDU message.
 *
 * @param isisMessage LS pdu message instance
 * @param channel     channel instance
 */
public void processLsPduMessage(IsisMessage isisMessage, Channel channel) {
    log.debug("Enters processLsPduMessage ...!!!");
    IsisNeighbor neighbor = neighbouringRouter(isisMessage.sourceMac());
    if (networkType == IsisNetworkType.BROADCAST && neighbor == null) {
        return;
    }

    LsPdu lsPdu = (LsPdu) isisMessage;
    LspWrapper wrapper = isisLsdb.findLsp(lsPdu.isisPduType(), lsPdu.lspId());
    if (wrapper == null || isisLsdb.isNewerOrSameLsp(lsPdu, wrapper.lsPdu()).equalsIgnoreCase("latest")) {
        if (wrapper != null) {               // verify if the LSA - is your own LSA - get system ID and compare LSP
            String lspKey = isisLsdb.lspKey(systemId);
            if (lsPdu.lspId().equals(lspKey)) {
                lsPdu.setSequenceNumber(lsPdu.sequenceNumber() + 1);
                if (lsPdu.pduType() == IsisPduType.L1LSPDU.value()) {
                    // setting the ls sequence number
                    isisLsdb.setL1LspSeqNo(lsPdu.sequenceNumber());
                } else if (lsPdu.pduType() == IsisPduType.L2LSPDU.value()) {
                    // setting the ls sequence number
                    isisLsdb.setL2LspSeqNo(lsPdu.sequenceNumber());
                }
                isisLsdb.addLsp(lsPdu, true, this);
                sendLsp(lsPdu, channel);
            } else {
                isisLsdb.addLsp(lsPdu, false, this);
            }


        } else {
            //not exist in the database or latest, then add it in database
            isisLsdb.addLsp(lsPdu, false, this);
        }
    }

    //If network type is P2P, acknowledge with a PSNP
    if (networkType() == IsisNetworkType.P2P) {
        IsisPduType psnpType = null;
        if (IsisPduType.get(lsPdu.pduType()) == IsisPduType.L1LSPDU) {
            psnpType = IsisPduType.L1PSNP;
        } else if (IsisPduType.get(lsPdu.pduType()) == IsisPduType.L2LSPDU) {
            psnpType = IsisPduType.L2PSNP;
        }
        IsisHeader isisHeader = new LspGenerator().getHeader(psnpType);
        Psnp psnp = new Psnp(isisHeader);
        psnp.setSourceId(lspKeyP2P(this.systemId));
        TlvHeader tlvHeader = new TlvHeader();
        tlvHeader.setTlvType(TlvType.LSPENTRY.value());
        tlvHeader.setTlvLength(0);
        LspEntriesTlv lspEntriesTlv = new LspEntriesTlv(tlvHeader);
        LspEntry lspEntry = new LspEntry();
        lspEntry.setLspChecksum(lsPdu.checkSum());
        lspEntry.setLspId(lsPdu.lspId());
        lspEntry.setLspSequenceNumber(lsPdu.sequenceNumber());
        lspEntry.setRemainingTime(lsPdu.remainingLifeTime());
        lspEntriesTlv.addLspEntry(lspEntry);
        psnp.addTlv(lspEntriesTlv);

        //write it to channel buffer.
        byte[] psnpBytes = psnp.asBytes();
        psnpBytes = IsisUtil.addLengthAndMarkItInReserved(psnpBytes, IsisConstants.LENGTHPOSITION,
                                                          IsisConstants.LENGTHPOSITION + 1,
                                                          IsisConstants.RESERVEDPOSITION);
        flagValue = false;
        //write to the channel
        if (channel != null && channel.isConnected() && channel.isOpen()) {
            channel.write(IsisUtil.framePacket(psnpBytes, interfaceIndex));
        }
    }
}