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

The following examples show how to use org.jboss.netty.handler.codec.http.HttpResponseStatus. 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: KafkaHttpRpcPlugin.java    From opentsdb-rpc-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Prints Version information for the various components.
 * @param query A non-null HTTP query to parse and respond to.
 */
private void handleVersion(final HttpRpcPluginQuery query) {
  final Map<String, Map<String, String>> versions = Maps.newHashMap();
  
  Map<String, String> version = Maps.newHashMap();
  version.put("version", BuildData.version);
  version.put("short_revision", BuildData.short_revision);
  version.put("full_revision", BuildData.full_revision);
  version.put("timestamp", Long.toString(BuildData.timestamp));
  version.put("repo_status", BuildData.repo_status.toString());
  version.put("user", BuildData.user);
  version.put("host", BuildData.host);
  version.put("repo", BuildData.repo);
  versions.put("tsdb", version);

  // TODO - plugin version
  
  query.sendBuffer(HttpResponseStatus.OK,
      ChannelBuffers.wrappedBuffer(JSON.serializeToBytes(versions)),
      "application/json");
}
 
Example #4
Source File: KafkaHttpRpcPlugin.java    From opentsdb-rpc-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Handles calls to print and/or adjust the rate per group
 * @param query The HTTP query to parse and respond to.
 */
private void handleRate(final HttpRpcPluginQuery query) {
  synchronized (tsdb) {
    if (KafkaRpcPlugin.KAFKA_RPC_REFERENCE == null) {
      throw new BadRequestException(HttpResponseStatus.CONFLICT, 
          "Consumers have not started yet");
    }
    // for now we'll just parse URI params to cheat
    final String group_id = query.getQueryStringParam("group");
    final double rate;
    if (group_id != null && !group_id.isEmpty()) {
      rate = Double.parseDouble(query.getRequiredQueryStringParam("rate"));
      KafkaRpcPlugin.KAFKA_RPC_REFERENCE.setRate(group_id, rate);
    } else {
      rate = 0;
    }
    
    final Map<String, Double> rates = 
        KafkaRpcPlugin.KAFKA_RPC_REFERENCE.getRates();
    query.sendBuffer(HttpResponseStatus.OK,
        ChannelBuffers.wrappedBuffer(JSON.serializeToBytes(rates)),
        "application/json");
  }
}
 
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: 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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: KafkaHttpRpcPlugin.java    From opentsdb-rpc-kafka with Apache License 2.0 5 votes vote down vote up
/** Publish per thread stats */
private void handlePerThreadStats(final HttpRpcPluginQuery query) {
  synchronized (tsdb) {
    if (KafkaRpcPlugin.KAFKA_RPC_REFERENCE == null) {
      throw new BadRequestException(HttpResponseStatus.CONFLICT, 
          "Consumers have not started yet");
    }
    final long ts = System.currentTimeMillis() / 1000;
    
    Map<String, Map<Integer, Map<String, Double>>> stats = 
        KafkaRpcPlugin.KAFKA_RPC_REFERENCE.getPerThreadStats();
    // TSD format for ingest
    final List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    for (final Entry<String, Map<Integer, Map<String, Double>>> group : stats.entrySet()) {
      for (final Entry<Integer, Map<String, Double>> thread : group.getValue().entrySet()) {
        for (final Entry<String, Double> counter : thread.getValue().entrySet()) {
          final Map<String, Object> entry = new HashMap<String, Object>(4);
          entry.put("metric", "KafkaRpcPlugin.perThread." + counter.getKey());
          entry.put("timestamp", ts);
          entry.put("value", counter.getValue());
          final Map<String, String> tags = new HashMap<String, String>(2);
          tags.put("host", KafkaRpcPlugin.KAFKA_RPC_REFERENCE.getHost());
          tags.put("consumer", group.getKey());
          tags.put("thread", Integer.toString(thread.getKey()));
          entry.put("tags", tags);
          results.add(entry);
        }
      }
      query.sendBuffer(HttpResponseStatus.OK,
          ChannelBuffers.wrappedBuffer(JSON.serializeToBytes(results)),
          "application/json");
    }
  }
}
 
Example #16
Source File: KafkaHttpRpcPlugin.java    From opentsdb-rpc-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Handles printing stats per namespace. Aggregated stats are included with 
 * the main tsdb /api/stats call. Users can filter by namespace if they want. 
 * @param query The HTTP query to parse and respond to.
 */
private void handlePerNamespaceStats(final HttpRpcPluginQuery query) {
  synchronized (tsdb) {
    if (KafkaRpcPlugin.KAFKA_RPC_REFERENCE == null) {
      throw new BadRequestException(HttpResponseStatus.CONFLICT, 
          "Consumers have not started yet");
    }
    
    final String filter = query.getQueryStringParam("namespace");
    final Map<String, Map<String, AtomicLong>> counters = 
        KafkaRpcPlugin.KAFKA_RPC_REFERENCE.getNamespaceCounters();
    final long ts = System.currentTimeMillis() / 1000;
    
    // TSD format for ingest
    final List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    for (final Entry<String, Map<String, AtomicLong>> counter : 
      counters.entrySet()) {
      
      for (final Entry<String, AtomicLong> metric : counter.getValue().entrySet()) {
        if (filter != null && !filter.isEmpty() && 
            !filter.toLowerCase().equals(metric.getKey().toLowerCase())) {
          continue;
        }
        
        final Map<String, Object> entry = new HashMap<String, Object>(4);
        entry.put("metric", "KafkaRpcPlugin.perNamespace." + counter.getKey());
        entry.put("timestamp", ts);
        entry.put("value", metric.getValue().get());
        final Map<String, String> tags = new HashMap<String, String>(2);
        tags.put("host", KafkaRpcPlugin.KAFKA_RPC_REFERENCE.getHost());
        tags.put("namespace", metric.getKey());
        entry.put("tags", tags);
        results.add(entry);
      }
    }
    query.sendBuffer(HttpResponseStatus.OK,
        ChannelBuffers.wrappedBuffer(JSON.serializeToBytes(results)),
        "application/json");
  }
}
 
Example #17
Source File: KafkaHttpRpcPlugin.java    From opentsdb-rpc-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(final TSDB tsdb, final HttpRpcPluginQuery query) throws IOException {
  // only accept GET/POST for now
  if (query.request().getMethod() != HttpMethod.GET && 
      query.request().getMethod() != HttpMethod.POST) {
    throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
        "Method not allowed", "The HTTP method [" + query.method().getName() +
        "] is not permitted for this endpoint");
  }
  
  final String[] uri = query.explodePath();
  final String endpoint = uri.length > 1 ? uri[2].toLowerCase() : "";
  
  if ("version".equals(endpoint)) {
    handleVersion(query);
  } else if ("rate".equals(endpoint)) {
    handleRate(query);
  } else if ("namespace".equals(endpoint)) {
    handlePerNamespaceStats(query);
  } else if ("perthread".equals(endpoint)) {
    handlePerThreadStats(query);
  } else {
    throw new BadRequestException(HttpResponseStatus.NOT_IMPLEMENTED, 
        "Hello. You have reached an API that has been disconnected. "
        + "Please call again.");
  }
}
 
Example #18
Source File: ShuffleHandler.java    From hadoop with Apache License 2.0 4 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx,
    HttpResponseStatus status) {
  sendError(ctx, "", status);
}
 
Example #19
Source File: NettyHttpChannel.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private HttpResponseStatus getStatus(RestStatus status) {
    switch (status) {
        case CONTINUE:
            return HttpResponseStatus.CONTINUE;
        case SWITCHING_PROTOCOLS:
            return HttpResponseStatus.SWITCHING_PROTOCOLS;
        case OK:
            return HttpResponseStatus.OK;
        case CREATED:
            return HttpResponseStatus.CREATED;
        case ACCEPTED:
            return HttpResponseStatus.ACCEPTED;
        case NON_AUTHORITATIVE_INFORMATION:
            return HttpResponseStatus.NON_AUTHORITATIVE_INFORMATION;
        case NO_CONTENT:
            return HttpResponseStatus.NO_CONTENT;
        case RESET_CONTENT:
            return HttpResponseStatus.RESET_CONTENT;
        case PARTIAL_CONTENT:
            return HttpResponseStatus.PARTIAL_CONTENT;
        case MULTI_STATUS:
            // no status for this??
            return HttpResponseStatus.INTERNAL_SERVER_ERROR;
        case MULTIPLE_CHOICES:
            return HttpResponseStatus.MULTIPLE_CHOICES;
        case MOVED_PERMANENTLY:
            return HttpResponseStatus.MOVED_PERMANENTLY;
        case FOUND:
            return HttpResponseStatus.FOUND;
        case SEE_OTHER:
            return HttpResponseStatus.SEE_OTHER;
        case NOT_MODIFIED:
            return HttpResponseStatus.NOT_MODIFIED;
        case USE_PROXY:
            return HttpResponseStatus.USE_PROXY;
        case TEMPORARY_REDIRECT:
            return HttpResponseStatus.TEMPORARY_REDIRECT;
        case BAD_REQUEST:
            return HttpResponseStatus.BAD_REQUEST;
        case UNAUTHORIZED:
            return HttpResponseStatus.UNAUTHORIZED;
        case PAYMENT_REQUIRED:
            return HttpResponseStatus.PAYMENT_REQUIRED;
        case FORBIDDEN:
            return HttpResponseStatus.FORBIDDEN;
        case NOT_FOUND:
            return HttpResponseStatus.NOT_FOUND;
        case METHOD_NOT_ALLOWED:
            return HttpResponseStatus.METHOD_NOT_ALLOWED;
        case NOT_ACCEPTABLE:
            return HttpResponseStatus.NOT_ACCEPTABLE;
        case PROXY_AUTHENTICATION:
            return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
        case REQUEST_TIMEOUT:
            return HttpResponseStatus.REQUEST_TIMEOUT;
        case CONFLICT:
            return HttpResponseStatus.CONFLICT;
        case GONE:
            return HttpResponseStatus.GONE;
        case LENGTH_REQUIRED:
            return HttpResponseStatus.LENGTH_REQUIRED;
        case PRECONDITION_FAILED:
            return HttpResponseStatus.PRECONDITION_FAILED;
        case REQUEST_ENTITY_TOO_LARGE:
            return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
        case REQUEST_URI_TOO_LONG:
            return HttpResponseStatus.REQUEST_URI_TOO_LONG;
        case UNSUPPORTED_MEDIA_TYPE:
            return HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
        case REQUESTED_RANGE_NOT_SATISFIED:
            return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
        case EXPECTATION_FAILED:
            return HttpResponseStatus.EXPECTATION_FAILED;
        case UNPROCESSABLE_ENTITY:
            return HttpResponseStatus.BAD_REQUEST;
        case LOCKED:
            return HttpResponseStatus.BAD_REQUEST;
        case FAILED_DEPENDENCY:
            return HttpResponseStatus.BAD_REQUEST;
        case TOO_MANY_REQUESTS:
            return TOO_MANY_REQUESTS;
        case INTERNAL_SERVER_ERROR:
            return HttpResponseStatus.INTERNAL_SERVER_ERROR;
        case NOT_IMPLEMENTED:
            return HttpResponseStatus.NOT_IMPLEMENTED;
        case BAD_GATEWAY:
            return HttpResponseStatus.BAD_GATEWAY;
        case SERVICE_UNAVAILABLE:
            return HttpResponseStatus.SERVICE_UNAVAILABLE;
        case GATEWAY_TIMEOUT:
            return HttpResponseStatus.GATEWAY_TIMEOUT;
        case HTTP_VERSION_NOT_SUPPORTED:
            return HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
        default:
            return HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
}
 
Example #20
Source File: ShuffleHandler.java    From big-c with Apache License 2.0 4 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx,
    HttpResponseStatus status) {
  sendError(ctx, "", status);
}
 
Example #21
Source File: HttpServerRequestHandler.java    From feeyo-hlsserver with 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 #22
Source File: ShuffleHandler.java    From RDFS with Apache License 2.0 4 votes vote down vote up
private void sendError(ChannelHandlerContext ctx,
    HttpResponseStatus status) {
  sendError(ctx, "", status);
}
 
Example #23
Source File: HttpServerRequestHandler.java    From feeyo-hlsserver with 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 #24
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 ) );
}
 
Example #25
Source File: ShuffleHandler.java    From tez with Apache License 2.0 4 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx,
    HttpResponseStatus status) {
  sendError(ctx, "", status);
}
 
Example #26
Source File: HttpServerRequestHandler.java    From feeyo-hlsserver with Apache License 2.0 4 votes vote down vote up
private HttpResponse buildErrorResponse(String errMsg) {
    return buildDefaultResponse(errMsg, HttpResponseStatus.SERVICE_UNAVAILABLE);
}
 
Example #27
Source File: ShuffleHandler.java    From tez with Apache License 2.0 4 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx,
    HttpResponseStatus status) {
  sendError(ctx, "", status);
}
 
Example #28
Source File: HlsVodHandler.java    From feeyo-hlsserver with 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);
}