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

The following examples show how to use org.jboss.netty.handler.codec.http.DefaultHttpResponse. These examples are extracted from open source projects. 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 Project: feeyo-hlsserver   Source File: HlsStreamsHandler.java    License: 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 Project: feeyo-hlsserver   Source File: WelcomeHandler.java    License: 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 Project: netty-file-parent   Source File: FileServerHandler.java    License: 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 4
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 5
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 6
Source Project: netty-servlet   Source File: HttpServerHandler.java    License: 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 7
Source Project: tez   Source File: ShuffleHandler.java    License: 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 8
Source Project: Elasticsearch   Source File: CorsHandler.java    License: 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 9
Source Project: hadoop   Source File: ShuffleHandler.java    License: 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 10
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 11
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 12
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 13
Source Project: big-c   Source File: ShuffleHandler.java    License: 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 14
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 15
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 16
Source Project: big-c   Source File: TestDelegationTokenRemoteFetcher.java    License: 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 17
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: 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 18
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: 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 19
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: 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 20
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: 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 21
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: 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 22
Source Project: incubator-tajo   Source File: HttpDataServerHandler.java    License: 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 23
Source Project: glowroot   Source File: HttpServerHandler.java    License: 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 24
Source Project: RDFS   Source File: ShuffleHandler.java    License: 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 25
Source Project: tez   Source File: ShuffleHandler.java    License: 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 26
Source Project: tez   Source File: ShuffleHandler.java    License: 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 27
Source Project: feeyo-hlsserver   Source File: HlsVodHandler.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	
    HttpRequest request = (DefaultHttpRequest) e.getMessage();
    if ( !request.getUri().matches(regex) ) {
        LOGGER.warn("bad request: " + request.getUri());
        HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }

    
    String[] path = request.getUri().split("/");
    String alias = path[3];
    final String reqFileName = path[4];
    
    Long streamId = HlsLiveStreamMagr.INSTANCE().getStreamIdByAlias(alias);
    if( streamId == null ) {
        LOGGER.warn(" aac vod, lookup alias failed: " + alias);
        HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
        return;
    }
    
    
    OssUtil ossOperation = new OssUtil();
    byte[] content = null;

    if (reqFileName.endsWith(".m3u8")) {
    	
        if ( !ossOperation.doesObjectExist(reqFileName, streamId) ) {
        	
            boolean needWaite = false;
            // the very first listener of a specific m3u8 will create the m3u8 file and the ts file
            // the reset will be in a waiter set
            synchronized (m3u8WaiteSet) {
                if (!m3u8WaiteSet.add(reqFileName)) {
                    needWaite = true;
                }
            }

            if (needWaite) {
                synchronized (m3u8WaiteSet) {
                    while (m3u8WaiteSet.contains(reqFileName)) {
                        m3u8WaiteSet.wait(1000);
                    }
                }
            } else {
                content = generateTsFiles(reqFileName, streamId);
            }
        }
    }

    if (content == null) {
        content = cachedVodTsFiles.get(reqFileName);
        if (content == null) {
            if (ossOperation.doesObjectExist(reqFileName, streamId)){
                InputStream inputStream = ossOperation.readObject(reqFileName, streamId);

                ObjectMetadata objectMetadata = ossOperation.getObjectMetadata(reqFileName,streamId);
                int len = (int)objectMetadata.getContentLength();
                content = new byte[len];

                int writePtr = 0;
                for (;;) {
                    int ret = inputStream.read(content, writePtr,len-writePtr);
                    if ((ret == -1) || (writePtr += ret) >= len)
                        break;
                }
            } else {
                LOGGER.warn("request file not on OSS: " + request.getUri());
                HttpUtil.sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
        }
    }

    ossOperation.closeOSSClient();

    long timeMillis = System.currentTimeMillis();

    DefaultHttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    response.headers().set(HttpHeaders.Names.DATE, HttpUtil.getDateString(timeMillis));
    response.headers().set(HttpHeaders.Names.CONTENT_TYPE, HttpUtil.getMimeType(reqFileName));
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.length);
    response.headers().set(HttpHeaders.Names.LAST_MODIFIED, HttpUtil.getDateString(timeMillis));
    response.headers().set(HttpHeaders.Names.EXPIRES, HttpUtil.getDateString(timeMillis + VOD_CACHE_TIME));
    response.headers().set(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + (VOD_CACHE_TIME/1000));

    response.setContent(ChannelBuffers.copiedBuffer(content));

    e.getChannel().write(response);
}
 
Example 28
Source Project: feeyo-hlsserver   Source File: HttpServerRequestHandler.java    License: Apache License 2.0 4 votes vote down vote up
private HttpResponse buildDefaultResponse(String msg, HttpResponseStatus status){
	HttpResponse errorResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
	errorResponse.setContent( ChannelBuffers.copiedBuffer(msg, Charset.defaultCharset())  );
    return errorResponse;
}
 
Example 29
Source Project: feeyo-hlsserver   Source File: HttpServerRequestHandler.java    License: Apache License 2.0 4 votes vote down vote up
private void sendRedirect(ChannelHandlerContext ctx, String newUri) {
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND);
    response.headers().set(HttpHeaders.Names.LOCATION, newUri);
    ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 30
Source Project: Elasticsearch   Source File: CorsHandler.java    License: 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);
}