Example usage for io.netty.handler.codec.http HttpMethod PUT

List of usage examples for io.netty.handler.codec.http HttpMethod PUT

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpMethod PUT.

Prototype

HttpMethod PUT

To view the source code for io.netty.handler.codec.http HttpMethod PUT.

Click Source Link

Document

The PUT method requests that the enclosed entity be stored under the supplied Request-URI.

Usage

From source file:reactor.ipc.netty.http.server.HttpPredicate.java

License:Open Source License

/**
 * An alias for {@link HttpPredicate#http}.
 * <p>//from w ww . j  av a  2  s  .co  m
 * Creates a {@link Predicate} based on a URI template filtering .
 * <p>
 * This will listen for PUT Method.
 *
 * @param uri The string to compile into a URI template and use for matching
 *
 * @return The new {@link Predicate}.
 *
 * @see Predicate
 */
public static Predicate<HttpServerRequest> put(String uri) {
    return http(uri, null, HttpMethod.PUT);
}

From source file:storage.netty.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *///from  ww w  . j  a  v a2s .c o m
private void formpost(Bootstrap bootstrap, String host, int port, URI uriSimple, String resourceUrl, File file,
        HttpDataFactory factory) throws Exception {
    // Start the connection attempt.
    Channel channel = bootstrap.connect(host, port).sync().channel();
    // Wait until the connection attempt succeeds or fails.
    //Channel channel = future.sync().channel();

    // Prepare the HTTP request.        
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            uriSimple.toASCIIString());
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().add("x-ms-version", "2016-05-31");

    final DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateTime = formatter.format(new Date());

    request.headers().set("x-ms-date", dateTime);
    request.headers().set("x-ms-blob-type", "BlockBlob");
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    RandomAccessFile raf = new RandomAccessFile(file, "r");
    long fileLength = raf.length();
    HttpUtil.setContentLength(request, fileLength);
    setContentTypeHeader(request, file);

    // Use the PostBody encoder
    //HttpPostRequestEncoder bodyRequestEncoder =
    //        new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // add Form attribute
    //bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
    request.headers().set("Authorization", "SharedKey " + account_name + ":"
            + AuthorizationHeader(account_name, account_key, "PUT", dateTime, request, resourceUrl, "", ""));

    channel.write(request);
    // ByteBuf buffer = Unpooled.copiedBuffer(Files.readAllBytes(file.toPath()));                //ByteBuf buffer = Unpooled.buffer(new FileInputStream(file), (int) file.length());

    ChannelFuture sendFileFuture = channel.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
            channel.newProgressivePromise());

    // Write the end marker.
    ChannelFuture lastContentFuture = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println(future.channel() + " Transfer progress: " + progress);
            } else {
                System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) {
            System.err.println(future.channel() + " Transfer complete.");
        }
    });

}

From source file:storage.netty.HTTPUploadClientAsync.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*from  w w w. ja v  a2s . co m*/
private HttpRequest formpost(String host, int port, String uriSimple, File file, HttpDataFactory factory)
        throws Exception {

    long fileLength;

    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, uriSimple);
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().add("x-ms-version", "2016-05-31");

    final DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateTime = formatter.format(new Date());

    request.headers().set("x-ms-date", dateTime);
    request.headers().set("x-ms-blob-type", "BlockBlob");

    //connection will not close but needed
    // headers.set("Connection","keep-alive");
    // headers.set("Keep-Alive","300");
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    fileLength = file.length();

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    request.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
    HttpUtil.setContentLength(request, fileLength);

    request.headers().add("Authorization", "SharedKey " + account_name + ":"
            + AuthorizationHeader(account_name, account_key, "PUT", dateTime, request, uriSimple, "", ""));

    return request;
}

From source file:storage.netty.HttpUploadClientHandler.java

License:Apache License

private HttpRequest createRequest() throws IOException, InvalidKeyException {
    String url = this.url.toString();
    String host = this.url.getHost();

    this.resourceUrl = "/mycontainer/" + randomString(5);

    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, url);

    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().set("x-ms-version", "2016-05-31");

    final DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateTime = formatter.format(new Date());

    request.headers().set("x-ms-date", dateTime);
    request.headers().set("x-ms-blob-type", "BlockBlob");

    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    RandomAccessFile raf = new RandomAccessFile(this.file, "r");
    long fileLength = raf.length();

    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    request.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(this.file.getPath()));
    HttpUtil.setContentLength(request, fileLength);
    request.headers().set("Authorization", "SharedKey " + account_name + ":"
            + AuthorizationHeader(account_name, account_key, "PUT", dateTime, request, resourceUrl, "", ""));

    return request;
}

From source file:uapi.web.http.netty.internal.NettyHttpRequest.java

License:Open Source License

NettyHttpRequest(final ILogger logger, final HttpRequest httpRequest) {
    this._logger = logger;
    this._request = httpRequest;

    HttpHeaders headers = this._request.headers();
    Looper.from(headers.iteratorAsString())
            .foreach(entry -> this._headers.put(entry.getKey().toLowerCase(), entry.getValue()));

    this._uri = this._request.uri();
    QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this._uri);
    Map<String, List<String>> params = queryStringDecoder.parameters();
    Looper.from(params.entrySet()).foreach(entry -> this._params.put(entry.getKey(), entry.getValue()));

    HttpVersion version = this._request.protocolVersion();
    if (HttpVersion.HTTP_1_0.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_0;
    } else if (HttpVersion.HTTP_1_1.equals(version)) {
        this._version = uapi.web.http.HttpVersion.V_1_1;
    } else {//from  ww  w .  j a  va2s  .  c  om
        throw new KernelException("Unsupported Http version - {}", version);
    }

    HttpMethod method = this._request.method();
    if (HttpMethod.GET.equals(method)) {
        this._method = uapi.web.http.HttpMethod.GET;
    } else if (HttpMethod.PUT.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PUT;
    } else if (HttpMethod.POST.equals(method)) {
        this._method = uapi.web.http.HttpMethod.POST;
    } else if (HttpMethod.PATCH.equals(method)) {
        this._method = uapi.web.http.HttpMethod.PATCH;
    } else if (HttpMethod.DELETE.equals(method)) {
        this._method = uapi.web.http.HttpMethod.DELETE;
    } else {
        throw new KernelException("Unsupported http method {}", method.toString());
    }

    // Decode content type
    String contentTypeString = this._headers.get(HttpHeaderNames.CONTENT_TYPE.toString());
    if (contentTypeString == null) {
        this._conentType = ContentType.TEXT;
        this._charset = Charset.forName("UTF-8");
    } else {
        String[] contentTypeInfo = contentTypeString.split(";");
        if (contentTypeInfo.length < 0) {
            this._conentType = ContentType.TEXT;
            this._charset = CharsetUtil.UTF_8;
        } else if (contentTypeInfo.length == 1) {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = CharsetUtil.UTF_8;
        } else {
            this._conentType = ContentType.parse(contentTypeInfo[0].trim());
            this._charset = Looper.from(contentTypeInfo).map(info -> info.split("="))
                    .filter(kv -> kv.length == 2).filter(kv -> kv[0].trim().equalsIgnoreCase("charset"))
                    .map(kv -> kv[1].trim()).map(Charset::forName).first(CharsetUtil.UTF_8);
        }
    }
}

From source file:weatherAlarm.endpoints.WeatherAlarmEndpoint.java

License:Apache License

@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
    if (alarmService == null) {
        response.setStatus(HttpResponseStatus.SERVICE_UNAVAILABLE);
        return response.close();
    }/*from w w  w .  j a  v a  2  s  .c o  m*/
    if (HttpMethod.GET.equals(request.getHttpMethod())) {
        handleGet(response, request.getUri());
    } else if (HttpMethod.PUT.equals(request.getHttpMethod())) {
        handlePut(response, request.getContent());
    } else if (HttpMethod.DELETE.equals(request.getHttpMethod())) {
        handleDelete(response, request.getUri());
    } else {
        response.setStatus(HttpResponseStatus.NOT_IMPLEMENTED);
    }
    return response.close();
}

From source file:weatherAlarm.endpoints.WeatherAlarmEndpointTest.java

License:Apache License

@Test
public void testHandleRequestForAddAlarm() throws Exception {
    IWeatherAlarmService alarmService = getEmptyAlarmService();
    WeatherAlarmEndpoint alarmEndpoint = new WeatherAlarmEndpoint();
    alarmEndpoint.setAlarmService(alarmService);

    WeatherAlarm alarm = createWeatherAlarm();

    Capture<byte[]> written = EasyMock.newCapture();
    Capture<HttpResponseStatus> status = EasyMock.newCapture();
    HttpServerRequest<ByteBuf> request = createMockHttpServerRequest(HttpMethod.PUT, URI,
            createContent(new ObjectMapper().writeValueAsBytes(alarm)));
    HttpServerResponse<ByteBuf> response = createMockHttpResponse(status, written);
    alarmEndpoint.handle(request, response);
    Assert.assertTrue("Alarm not added from list " + alarm, alarmService.getAlarm(alarm.getName()) != null);
}