org.jboss.netty.handler.codec.http.DefaultHttpResponse Java Examples

The following examples show how to use org.jboss.netty.handler.codec.http.DefaultHttpResponse. 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: HlsStreamsHandler.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	
	VelocityBuilder velocityBuilder = new VelocityBuilder();
	Map<String,Object> model = new HashMap<String, Object>();
	
	model.put("streams", HlsLiveStreamMagr.INSTANCE().getAllLiveStream()); 
	
	String htmlText = velocityBuilder.generate("streams.vm", "UTF8", model);
	
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length());
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");

	ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, Charset.defaultCharset());// CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
	
}
 
Example #2
Source File: WelcomeHandler.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) {

	VelocityBuilder velocityBuilder = new VelocityBuilder();
	String htmlText = velocityBuilder.generate("index.vm", "UTF8", null);	
	
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length());
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
	
	ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
}
 
Example #3
Source File: ShuffleHandler.java    From tez with Apache License 2.0 6 votes vote down vote up
private boolean deleteDagDirectories(MessageEvent evt,
                                     List<String> dagCompletedQ, List<String> jobQ,
                                     List<String> dagIdQ) {
  if (jobQ == null || jobQ.isEmpty()) {
    return false;
  }
  if (dagCompletedQ != null && !dagCompletedQ.isEmpty() && dagCompletedQ.get(0).contains("delete")
      && dagIdQ != null && !dagIdQ.isEmpty()) {
    String base = getDagLocation(jobQ.get(0), dagIdQ.get(0), userRsrc.get(jobQ.get(0)));
    try {
      FileContext lfc = FileContext.getLocalFSFileContext();
      for(Path dagPath : lDirAlloc.getAllLocalPathsToRead(base, conf)) {
        lfc.delete(dagPath, true);
      }
    } catch (IOException e) {
      LOG.warn("Encountered exception during dag delete "+ e);
    }
    evt.getChannel().write(new DefaultHttpResponse(HTTP_1_1, OK));
    evt.getChannel().close();
    return true;
  }
  return false;
}
 
Example #4
Source File: HttpServerHandler.java    From netty-servlet with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    if (event.getMessage() instanceof HttpRequest) {
        try {
            HttpServletRequest httpServletRequest = new NettyHttpServletRequestAdaptor((HttpRequest) event.getMessage(), ctx.getChannel());
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.setContent(new DynamicChannelBuffer(200));
            HttpServletResponse httpServletResponse = new NettyHttpServletResponseAdaptor(response, ctx.getChannel());
            dispatcher.dispatch(httpServletRequest,httpServletResponse);
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,response.getContent().writerIndex());
            ChannelFuture future = ctx.getChannel().write(response);
            future.addListener(ChannelFutureListener.CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example #5
Source File: FileServerHandler.java    From netty-file-parent with Apache License 2.0 6 votes vote down vote up
private void writeResponse(Channel channel) {
	ChannelBuffer buf = ChannelBuffers.copiedBuffer(
			this.responseContent.toString(), CharsetUtil.UTF_8);
	this.responseContent.setLength(0);

	boolean close = ("close".equalsIgnoreCase(this.request
			.getHeader("Connection")))
			|| ((this.request.getProtocolVersion()
					.equals(HttpVersion.HTTP_1_0)) && (!"keep-alive"
					.equalsIgnoreCase(this.request.getHeader("Connection"))));

	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.OK);
	response.setContent(buf);
	response.setHeader("Content-Type", "text/plain; charset=UTF-8");
	if (!close) {
		response.setHeader("Content-Length",
				String.valueOf(buf.readableBytes()));
	}
	ChannelFuture future = channel.write(response);
	if (close)
		future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #6
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #7
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #8
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
/**
 * Handles RECORD request. We did all the work during ANNOUNCE and SETUP, so there's nothing
 * more to do.
 * 
 * iTunes reports the initial RTP sequence and playback time here, which would actually be
 * helpful. But iOS doesn't, so we ignore it all together.
 */
public synchronized void recordReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws Exception {
	if (audioStreamInformationProvider == null){
		throw new ProtocolException("Audio stream not configured, cannot start recording");
	}		
	LOG.info("Client started streaming");
	
	audioOutputQueue.startAudioProcessing();
	timingHandler.startTimeSync();
	
	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	ctx.getChannel().write(response);
}
 
Example #9
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #10
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
/**
 * Handle FLUSH requests.
 * 
 * iTunes reports the last RTP sequence and playback time here, which would actually be
 * helpful. But iOS doesn't, so we ignore it all together.
 */
private synchronized void flushReceived(final ChannelHandlerContext ctx, final HttpRequest req) {
	if (audioOutputQueue != null){
		audioOutputQueue.flush();
	}

	LOG.info("Client paused streaming, flushed audio output queue");

	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	ctx.getChannel().write(response);
}
 
Example #11
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
/**
 * Handle TEARDOWN requests. 
 */
private synchronized void teardownReceived(final ChannelHandlerContext ctx, final HttpRequest req) {
	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	ctx.getChannel().setReadable(false);
	ctx.getChannel().write(response).addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(final ChannelFuture future) throws Exception {
			future.getChannel().close();
			LOG.info("RTSP connection closed after client initiated teardown");
		}
	});
}
 
Example #12
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
/**
 * Handle SET_PARAMETER request. Currently only {@code volume} is supported
 */
public synchronized void setParameterReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException {
	/* Body in ASCII encoding with unix newlines */
	final String body = req.getContent().toString(Charset.forName("ASCII")).replace("\r", "");

	/* Handle parameters */
	for(final String line: body.split("\n")) {
		try {
			/* Split parameter into name and value */
			final Matcher m_parameter = s_pattern_parameter.matcher(line);
			if (!m_parameter.matches()){
				throw new ProtocolException("Cannot parse line " + line);
			}

			final String name = m_parameter.group(1);
			final String value = m_parameter.group(2);

			if ("volume".equals(name)) {
				if (audioOutputQueue != null){
					float vol = Math.abs(Float.parseFloat(value));
					vol = (float) (1.0 - (vol / 29.0));
					audioOutputQueue.setRequestedVolume(vol);
				}
			}
		}
		catch (final Throwable e) {
			throw new ProtocolException("Unable to parse line " + line);
		}
	}

	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	ctx.getChannel().write(response);
}
 
Example #13
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 5 votes vote down vote up
/**
 * Handle GET_PARAMETER request. Currently only {@code volume} is supported
 */
public synchronized void getParameterReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException {
	final StringBuilder body = new StringBuilder();

	if (audioOutputQueue != null) {
		/* Report output gain */
		body.append("volume: ");
		body.append(audioOutputQueue.getRequestedVolume());
		body.append("\r\n");
	}

	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	response.setContent(ChannelBuffers.wrappedBuffer(body.toString().getBytes(Charset.forName("ASCII"))));
	ctx.getChannel().write(response);
}
 
Example #14
Source File: HttpDataServerHandler.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #15
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void writeResponse(MessageEvent e) throws Exception {
    HttpResponse response =
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.setContent(ChannelBuffers.copiedBuffer("Hello world", CharsetUtil.UTF_8));
    addHeader(response, HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example #16
Source File: ShuffleHandler.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(
      ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #17
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.headers().set(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.headers().set(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #18
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #19
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
      HttpResponseStatus.METHOD_NOT_ALLOWED);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #20
Source File: TestDelegationTokenRemoteFetcher.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #21
Source File: ShuffleHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #22
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #23
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
      HttpResponseStatus.METHOD_NOT_ALLOWED);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #24
Source File: TestDelegationTokenRemoteFetcher.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #25
Source File: ShuffleHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example #26
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
    final HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), OK);
    if (setOrigin(response)) {
        setAllowMethods(response);
        setAllowHeaders(response);
        setAllowCredentials(response);
        setMaxAge(response);
        setPreflightHeaders(response);
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        forbidden(ctx, request);
    }
}
 
Example #27
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
    ctx.getChannel().write(new DefaultHttpResponse(request.getProtocolVersion(), FORBIDDEN))
        .addListener(ChannelFutureListener.CLOSE);
}
 
Example #28
Source File: InterruptsImpl.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void movedPermanently(String location) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, MOVED_PERMANENTLY);
    response.addHeader("Location", location);
    write(response);
}
 
Example #29
Source File: InterruptsImpl.java    From zuul-netty with Apache License 2.0 4 votes vote down vote up
@Override
public void temporaryRedirect(String location) {
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, TEMPORARY_REDIRECT);
    response.addHeader("Location", location);
    write(response);
}
 
Example #30
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private void sendHttpResponse( ChannelHandlerContext ctx, HttpRequest req, HttpResponseStatus status ) {
    sendHttpResponse( ctx, req, new DefaultHttpResponse( HTTP_1_1, status ) );
}