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

The following examples show how to use org.jboss.netty.handler.codec.http.HttpResponse. 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: ShuffleHandler.java    From tez with Apache License 2.0 6 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String jobId,
                               String dagId, String user,
                               Range reduceRange,
                               HttpResponse response,
                               boolean keepAliveParam,
                               Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  // Content-Length only needs calculated for keep-alive keep alive
  if (connectionKeepAliveEnabled || keepAliveParam) {
    contentLength = getContentLength(mapIds, jobId, dagId, user, reduceRange, mapOutputInfoMap);
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example #2
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, CorsConfig config) {
    if (!config.isCorsSupportEnabled()) {
        return;
    }
    String originHeader = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(originHeader)) {
        final String originHeaderVal;
        if (config.isAnyOriginSupported()) {
            originHeaderVal = ANY_ORIGIN;
        } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HOST))) {
            originHeaderVal = originHeader;
        } else {
            originHeaderVal = null;
        }
        if (originHeaderVal != null) {
            resp.headers().add(ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
        }
    }
    if (config.isCredentialsAllowed()) {
        resp.headers().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
}
 
Example #3
Source File: HttpServerRequestHandler.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
private void sendResponse(ChannelHandlerContext ctx, HttpResponse httpResponse){
    boolean close = false;
    ChannelFuture channelFuture = null;
    try {
        channelFuture = ctx.getChannel().write(httpResponse);
    } catch (Exception e) {
    	LOGGER.error("write response fail.", e);
        close = true;
    } finally {
        // close connection
        if (close || httpResponse == null || !Values.KEEP_ALIVE.equals(httpResponse.headers().get(HttpHeaders.Names.CONNECTION))) {
        	if (channelFuture.isSuccess()) {
    			channelFuture.getChannel().close();
    		}
        }
    }
}
 
Example #4
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 #5
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private boolean setOrigin(final HttpResponse response) {
    final String origin = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(origin)) {
        if ("null".equals(origin) && config.isNullOriginAllowed()) {
            setAnyOrigin(response);
            return true;
        }
        if (config.isAnyOriginSupported()) {
            if (config.isCredentialsAllowed()) {
                echoRequestOrigin(response);
                setVaryHeader(response);
            } else {
                setAnyOrigin(response);
            }
            return true;
        }
        if (config.isOriginAllowed(origin)) {
            setOrigin(response, origin);
            setVaryHeader(response);
            return true;
        }
    }
    return false;
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
Source File: RaopRtspChallengeResponseHandler.java    From Android-Airplay-Server with MIT License 6 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpResponse resp = (HttpResponse)evt.getMessage();

	synchronized(this) {
		if (m_challenge != null) {
			try {
				/* Get appropriate response to challenge and
				 * add to the response base-64 encoded. XXX
				 */
				final String sig = Base64.encodePadded(getSignature());

				resp.setHeader(HeaderSignature, sig);
			}
			finally {
				/* Forget last challenge */
				m_challenge = null;
				m_localAddress = null;
			}
		}
	}

	super.writeRequested(ctx, evt);
}
 
Example #11
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 #12
Source File: HttpInvoker.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpInvocationContext<Request, Response> httpInvocationContext = contexts.get(ctx.getChannel());
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<Request, Response> action = httpInvocationContext.getHttpAction();
            ActionListener<Response> listener = httpInvocationContext.getListener();
            httpInvocationContext.httpResponse = httpResponse;
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpInvocationContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        contexts.remove(ctx.getChannel());
    }
}
 
Example #13
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpInvocationContext<Request, Response> httpInvocationContext = contextMap.get(ctx.getChannel());
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<Request, Response> action = httpInvocationContext.getHttpAction();
            ActionListener<Response> listener = httpInvocationContext.getListener();
            httpInvocationContext.httpResponse = httpResponse;
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpInvocationContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        contextMap.remove(ctx.getChannel());
    }
}
 
Example #14
Source File: HttpRefreshIndexAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
protected RefreshResponse createResponse(HttpInvocationContext<RefreshRequest,RefreshResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        logger.info("{}", map);
        //  RefreshResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
        return new RefreshResponse();
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #15
Source File: HttpCreateIndexAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
protected CreateIndexResponse createResponse(HttpInvocationContext<CreateIndexRequest,CreateIndexResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        boolean acknowledged = map.containsKey("acknowledged") ? (Boolean)map.get("acknowledged") : false;
        return new CreateIndexResponse(acknowledged);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #16
Source File: HttpSearchAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpInvocationContext<SearchRequest,SearchResponse> httpInvocationContext) throws IOException {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String)map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String,?> shards = (Map<String,?>)map.get(SHARDS);
        totalShards =  shards.containsKey(TOTAL) ? (Integer)shards.get(TOTAL) : -1;
        successfulShards =  shards.containsKey(SUCCESSFUL) ? (Integer)shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer)map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = parseShardFailures(map);
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
Example #17
Source File: HttpBulkAction.java    From elasticsearch-helper with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected BulkResponse createResponse(HttpInvocationContext<BulkRequest,BulkResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        long tookInMillis = map.containsKey("took") ? (Integer)map.get("took") : -1L;
        BulkItemResponse[] responses = parseItems((List<Map<String,?>>)map.get("items"));
        return new BulkResponse(responses, tookInMillis);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example #18
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e.getMessage();
        HttpRequest request = (HttpRequest) ctx.getAttachment();

        LOG.debug("handler: {} is calling response-handler: {}", tag, responseHandler.getClass().getSimpleName());
        responseHandler.responseReceived(new HttpRequestFrameworkAdapter(request), new HttpResponseFrameworkAdapter(response));

        ctx.setAttachment(null);
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.writeRequested(ctx, e);
}
 
Example #19
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 #20
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 #21
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void setResponseHeaders(HttpResponse response, boolean keepAliveParam, long contentLength) {
  if (connectionKeepAliveEnabled || keepAliveParam) {
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(contentLength));
    response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    response.headers().set(HttpHeaders.Values.KEEP_ALIVE, "timeout=" + connectionKeepAliveTimeOut);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Content Length in shuffle : " + contentLength);
    }
  } else {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Setting connection close header...");
    }
    response.headers().set(HttpHeaders.Names.CONNECTION, CONNECTION_CLOSE);
  }
}
 
Example #22
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 #23
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 #24
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void addHeader(HttpResponse response, String name, String value)
        throws Exception {
    try {
        Object headers = HttpResponse.class.getMethod("headers").invoke(response);
        Class<?> httpHeadersClass =
                Class.forName("org.jboss.netty.handler.codec.http.HttpHeaders");
        httpHeadersClass.getMethod("add", String.class, Object.class).invoke(headers, name,
                value);
    } catch (Exception e) {
        // netty prior to 3.8.0
        HttpResponse.class.getMethod("addHeader", String.class, Object.class).invoke(response,
                name, value);
    }
}
 
Example #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: HttpUpdateSettingsAction.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@Override
protected UpdateSettingsResponse createResponse(HttpInvocationContext<UpdateSettingsRequest,UpdateSettingsResponse> httpInvocationContext) throws IOException {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
    return new UpdateSettingsResponse();
}