List of usage examples for io.netty.handler.codec.http HttpMethod equals
@Override public boolean equals(Object o)
From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java
License:Apache License
public HttpPostRequestDecoder getHttpPostRequestDecoder() { if (!httpPostRequestDecoderInit) { HttpMethod method = getMethod(); if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) { try { httpPostRequestDecoder = new HttpPostRequestDecoder(factory, this, charset4ContentDecoder); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { log.error("request postDataDecode error:{}", this, e); } catch (HttpPostRequestDecoder.IncompatibleDataDecoderException e) { }//w ww . j a v a 2 s . com } httpPostRequestDecoderInit = true; } return httpPostRequestDecoder; }
From source file:co.freeside.betamax.proxy.netty.PredicatedHttpFilters.java
License:Apache License
public static Predicate<HttpRequest> httpMethodPredicate(final HttpMethod method) { return new Predicate<HttpRequest>() { @Override// w w w . j a v a 2 s . c o m public boolean apply(HttpRequest input) { return method.equals(input.getMethod()); } }; }
From source file:com.github.ambry.rest.NettyResponseChannelTest.java
License:Open Source License
/** * Tests keep-alive for different HTTP methods and error statuses. *//*from www.j a v a 2s. c o m*/ @Test public void keepAliveTest() { HttpMethod[] HTTP_METHODS = { HttpMethod.POST, HttpMethod.GET, HttpMethod.HEAD, HttpMethod.DELETE }; EmbeddedChannel channel = createEmbeddedChannel(); for (HttpMethod httpMethod : HTTP_METHODS) { for (Map.Entry<RestServiceErrorCode, HttpResponseStatus> entry : REST_ERROR_CODE_TO_HTTP_STATUS .entrySet()) { HttpHeaders httpHeaders = new DefaultHttpHeaders(); httpHeaders.set(MockNettyMessageProcessor.REST_SERVICE_ERROR_CODE_HEADER_NAME, entry.getKey()); channel.writeInbound(RestTestUtils.createRequest(httpMethod, TestingUri.OnResponseCompleteWithRestException.toString(), httpHeaders)); HttpResponse response = (HttpResponse) channel.readOutbound(); assertEquals("Unexpected response status", entry.getValue(), response.getStatus()); if (!(response instanceof FullHttpResponse)) { // empty the channel while (channel.readOutbound() != null) { } } boolean shouldBeAlive = !httpMethod.equals(HttpMethod.POST) && !NettyResponseChannel.CLOSE_CONNECTION_ERROR_STATUSES.contains(entry.getValue()); assertEquals("Channel state (open/close) not as expected", shouldBeAlive, channel.isActive()); assertEquals("Connection header should be consistent with channel state", shouldBeAlive, HttpHeaders.isKeepAlive(response)); if (!shouldBeAlive) { channel = createEmbeddedChannel(); } } } channel.close(); }
From source file:com.linkedin.proxy.netty.MysqlQueryDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception { MysqlQuery result = new MysqlQuery(); try {//w w w . ja v a 2 s . co m HttpMethod met = msg.getMethod(); String uri = msg.getUri(); int s = 0; int e = uri.length(); if (uri.charAt(0) == '/') s = 1; if (uri.charAt(e - 1) == '/') e--; String parts[] = uri.substring(s, e).split("/"); result.setDbName(parts[0]); result.setTableName(parts[1]); result.setKeyColName(parts[2]); result.setValueColName(parts[3]); if (met.equals(HttpMethod.PUT)) { /* * If HttpRequest method is PUT, I interpret it as a WRITE query. * MysqlQuery instance's value is set as the value in the HttpRequest. */ result.setKey(parts[4]); byte[] tempData = new byte[msg.content().readableBytes()]; msg.content().readBytes(tempData); result.setValue(tempData); result.setType(QueryType.WRITE); } else if (met.equals(HttpMethod.GET)) { /* * If HttpRequest method is GET, I interpret it as a READ query. * Once the query is processed, the result value (if any) is written to MysqlQuery.value. */ result.setKey(parts[4]); result.setType(QueryType.READ); } else if (met.equals(HttpMethod.DELETE)) { /* * If HttpRequest method is DELETE, I interpret it as a DELETE query. */ result.setKey(parts[4]); result.setType(QueryType.DELETE); } else if (met.equals(HttpMethod.POST)) { /* * If HttpRequest method is POST, I interpret it as a CREATE TABLE query. * I store size of the value column in MysqlQuery.Value. * I store byte array of the string representation. */ result.setValue(parts[4].getBytes()); result.setType(QueryType.CREATE); } else { result.setType(QueryType.INVALID); _LOG.error("Unhandled HttpMethod: " + met); _LOG.error("Type=" + QueryType.INVALID); } } catch (Exception e) { _LOG.error("Exception occured during HttpRequest processing", e); result.setType(QueryType.INVALID); _LOG.error("Type=" + QueryType.INVALID); } out.add(result); }
From source file:com.linkedin.proxy.netty.RocksdbQueryDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, FullHttpRequest msg, List<Object> out) throws Exception { /*/*from w w w. j ava 2 s. co m*/ * Expected inputs: * PUT /dbName/key <value in content> * GET /dbName/key * DELETE /dbName/key */ Query result = new Query(); try { HttpMethod met = msg.getMethod(); String uri = msg.getUri(); int s = 0; int e = uri.length(); if (uri.charAt(0) == '/') s = 1; if (uri.charAt(e - 1) == '/') e--; String parts[] = uri.substring(s, e).split("/"); result.setDbName(parts[0]); _LOG.debug("DbName: " + parts[0]); result.setKey(parts[1]); _LOG.debug("Key: " + parts[1]); if (met.equals(HttpMethod.PUT)) { /* * If HttpRequest method is PUT, I interpret it as a WRITE query. * Query instance's value is set as the value in the HttpRequest. */ byte[] tempData = new byte[msg.content().readableBytes()]; msg.content().readBytes(tempData); result.setValue(tempData); _LOG.debug("Value size: " + tempData.length); result.setType(QueryType.WRITE); } else if (met.equals(HttpMethod.GET)) { /* * If HttpRequest method is GET, I interpret it as a READ query. * Once the query is processed, the result value (if any) is written to MysqlQuery.value. */ result.setType(QueryType.READ); } else if (met.equals(HttpMethod.DELETE)) { /* * If HttpRequest method is DELETE, I interpret it as a DELETE query. */ result.setType(QueryType.DELETE); } else { result.setType(QueryType.INVALID); _LOG.error("Unhandled HttpMethod: " + met); _LOG.error("Type=" + QueryType.INVALID); } _LOG.debug("Type: " + result.getType()); } catch (Exception e) { _LOG.error("Exception occured during HttpRequest processing", e); result.setType(QueryType.INVALID); _LOG.error("Type=" + QueryType.INVALID); } out.add(result); }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void doHttpRequest(ChannelHandlerContext ctx, HttpRequest httpRequest) throws URISyntaxException { HttpRequest request = this.request = httpRequest; HttpMethod httpMethod = request.getMethod(); if (httpMethod.equals(HttpMethod.GET)) { doGet(ctx, request);//from www . j av a2s . co m } else if (httpMethod.equals(HttpMethod.POST)) { doPost(ctx, request); } else { responseContent.setLength(0); responseContent.append(httpMethod.name()).append(" method not support!"); writeResponse(ctx.channel()); logger.error(responseContent.toString()); } }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
private static HttpRequest construct(AsyncHttpClientConfig config, Request request, HttpMethod m, URI uri, ByteBuf buffer, ProxyServer proxyServer) throws IOException { String host = AsyncHttpProviderUtils.getHost(uri); boolean webSocket = isWebSocket(uri); if (request.getVirtualHost() != null) { host = request.getVirtualHost(); }//from ww w.ja va2 s . c o m FullHttpRequest nettyRequest; if (m.equals(HttpMethod.CONNECT)) { nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m, AsyncHttpProviderUtils.getAuthority(uri)); } else { String path = null; if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies())) path = uri.toString(); else if (uri.getRawQuery() != null) path = uri.getRawPath() + "?" + uri.getRawQuery(); else path = uri.getRawPath(); nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, path); } if (webSocket) { nettyRequest.headers().add(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET); nettyRequest.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE); nettyRequest.headers().add("Origin", "http://" + uri.getHost() + ":" + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort())); nettyRequest.headers().add(WEBSOCKET_KEY, WebSocketUtil.getKey()); nettyRequest.headers().add("Sec-WebSocket-Version", "13"); } if (host != null) { if (uri.getPort() == -1) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else if (request.getVirtualHost() != null) { nettyRequest.headers().set(HttpHeaders.Names.HOST, host); } else { nettyRequest.headers().set(HttpHeaders.Names.HOST, host + ":" + uri.getPort()); } } else { host = "127.0.0.1"; } if (!m.equals(HttpMethod.CONNECT)) { FluentCaseInsensitiveStringsMap h = request.getHeaders(); if (h != null) { for (String name : h.keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : h.get(name)) { nettyRequest.headers().add(name, value); } } } } if (config.isCompressionEnabled()) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); } } else { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (isNonEmpty(auth) && auth.get(0).startsWith("NTLM")) { nettyRequest.headers().add(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0)); } } Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm(); if (realm != null && realm.getUsePreemptiveAuth()) { String domain = realm.getNtlmDomain(); if (proxyServer != null && proxyServer.getNtlmDomain() != null) { domain = proxyServer.getNtlmDomain(); } String authHost = realm.getNtlmHost(); if (proxyServer != null && proxyServer.getHost() != null) { host = proxyServer.getHost(); } switch (realm.getAuthScheme()) { case BASIC: nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(realm)); break; case DIGEST: if (isNonEmpty(realm.getNonce())) { try { nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, AuthenticatorUtils.computeDigestAuthentication(realm)); } catch (NoSuchAlgorithmException e) { throw new SecurityException(e); } } break; case NTLM: try { String msg = ntlmEngine.generateType1Msg("NTLM " + domain, authHost); nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } break; case KERBEROS: case SPNEGO: String challengeHeader = null; String server = proxyServer == null ? host : proxyServer.getHost(); try { challengeHeader = getSpnegoEngine().generateToken(server); } catch (Throwable e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } nettyRequest.headers().set(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challengeHeader); break; case NONE: break; default: throw new IllegalStateException("Invalid Authentication " + realm); } } if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) { nettyRequest.headers().set(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer != null) { if (!request.getHeaders().containsKey("Proxy-Connection")) { nettyRequest.headers().set("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config)); } if (proxyServer.getPrincipal() != null) { if (isNonEmpty(proxyServer.getNtlmDomain())) { List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION); if (!(isNonEmpty(auth) && auth.get(0).startsWith("NTLM"))) { try { String msg = ntlmEngine.generateType1Msg(proxyServer.getNtlmDomain(), proxyServer.getHost()); nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg); } catch (NTLMEngineException e) { IOException ie = new IOException(); ie.initCause(e); throw ie; } } } else { nettyRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, AuthenticatorUtils.computeBasicAuthentication(proxyServer)); } } } // Add default accept headers. if (request.getHeaders().getFirstValue("Accept") == null) { nettyRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*"); } if (request.getHeaders().getFirstValue("User-Agent") != null) { nettyRequest.headers().set("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { nettyRequest.headers().set("User-Agent", config.getUserAgent()); } else { nettyRequest.headers().set("User-Agent", AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config)); } if (!m.equals(HttpMethod.CONNECT)) { if (isNonEmpty(request.getCookies())) { CookieEncoder httpCookieEncoder = new CookieEncoder(false); Iterator<Cookie> ic = request.getCookies().iterator(); Cookie c; org.jboss.netty.handler.codec.http.Cookie cookie; while (ic.hasNext()) { c = ic.next(); cookie = new DefaultCookie(c.getName(), c.getValue()); cookie.setPath(c.getPath()); cookie.setMaxAge(c.getMaxAge()); cookie.setDomain(c.getDomain()); httpCookieEncoder.addCookie(cookie); } nettyRequest.headers().set(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); } String reqType = request.getMethod(); if (!"HEAD".equals(reqType) && !"OPTION".equals(reqType) && !"TRACE".equals(reqType)) { String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); // We already have processed the body. if (buffer != null && buffer.writerIndex() != 0) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, buffer.writerIndex()); nettyRequest.setContent(buffer); } else if (request.getByteData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getByteData().length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getByteData())); } else if (request.getStringData() != null) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getStringData().getBytes(bodyCharset).length)); nettyRequest.setContent(Unpooled.wrappedBuffer(request.getStringData().getBytes(bodyCharset))); } else if (request.getStreamData() != null) { int[] lengthWrapper = new int[1]; byte[] bytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper); int length = lengthWrapper[0]; nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(length)); nettyRequest.setContent(Unpooled.wrappedBuffer(bytes, 0, length)); } else if (isNonEmpty(request.getParams())) { StringBuilder sb = new StringBuilder(); for (final Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sb.length())); nettyRequest.setContent(Unpooled.wrappedBuffer(sb.toString().getBytes(bodyCharset))); if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) { nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } MultipartRequestEntity mre = AsyncHttpProviderUtils .createMultipartRequestEntity(request.getParts(), request.getParams()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType()); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(mre.getContentLength())); /** * TODO: AHC-78: SSL + zero copy isn't supported by the MultiPart class and pretty complex to implements. */ if (isSecure(uri)) { ByteBuf b = Unpooled.buffer(lenght); mre.writeRequest(new ByteBufOutputStream(b)); nettyRequest.setContent(b); } } else if (request.getEntityWriter() != null) { int lenght = computeAndSetContentLength(request, nettyRequest); if (lenght == -1) { lenght = MAX_BUFFERED_BYTES; } ByteBuf b = Unpooled.buffer(lenght); request.getEntityWriter().writeEntity(new ByteBufOutputStream(b)); nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, b.writerIndex()); nettyRequest.setContent(b); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format("File %s is not a file or doesn't exist", file.getAbsolutePath())); } nettyRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, file.length()); } } } return nettyRequest; }
From source file:divconq.http.multipart.HttpPostRequestEncoder.java
License:Apache License
/** * * @param factory//from w w w . j a va 2s . c om * the factory used to create InterfaceHttpData * @param request * the request to encode * @param multipart * True if the FORM is a ENCTYPE="multipart/form-data" * @param charset * the charset to use as default * @param encoderMode * the mode for the encoder to use. See {@link EncoderMode} for the details. * @throws NullPointerException * for request or charset or factory * @throws ErrorDataEncoderException * if the request is not a POST */ public HttpPostRequestEncoder(HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset, EncoderMode encoderMode) throws ErrorDataEncoderException { if (factory == null) { throw new NullPointerException("factory"); } if (request == null) { throw new NullPointerException("request"); } if (charset == null) { throw new NullPointerException("charset"); } HttpMethod method = request.getMethod(); if (!(method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH) || method.equals(HttpMethod.OPTIONS))) { throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST"); } this.request = request; this.charset = charset; this.factory = factory; // Fill default values bodyListDatas = new ArrayList<InterfaceHttpData>(); // default mode isLastChunk = false; isLastChunkSent = false; isMultipart = multipart; multipartHttpDatas = new ArrayList<InterfaceHttpData>(); this.encoderMode = encoderMode; if (isMultipart) { initDataMultipart(); } }
From source file:io.advantageous.conekt.http.impl.HttpServerRequestImpl.java
License:Open Source License
@Override public HttpServerRequest setExpectMultipart(boolean expect) { synchronized (conn) { checkEnded();/*w w w. j ava 2 s .com*/ if (expect) { if (decoder == null) { String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); if (contentType != null) { HttpMethod method = request.getMethod(); String lowerCaseContentType = contentType.toLowerCase(); boolean isURLEncoded = lowerCaseContentType .startsWith(HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED); if ((lowerCaseContentType.startsWith(HttpHeaders.Values.MULTIPART_FORM_DATA) || isURLEncoded) && (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH) || method.equals(HttpMethod.DELETE))) { decoder = new HttpPostRequestDecoder(new DataFactory(), request); } } } } else { decoder = null; } return this; } }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private boolean possibleRedirect(HttpRequest request, String index, String digest) { HttpMethod method = request.method(); if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.HEAD) || (method.equals(HttpMethod.PUT) && HttpUtil.is100ContinueExpected(request))) { String redirectAddress;/*www . jav a 2s . c om*/ try { redirectAddress = blobService.getRedirectAddress(index, digest); } catch (MissingHTTPEndpointException ex) { simpleResponse(HttpResponseStatus.BAD_GATEWAY); return true; } if (redirectAddress != null) { LOGGER.trace("redirectAddress: {}", redirectAddress); sendRedirect(activeScheme + redirectAddress); return true; } } return false; }