Example usage for org.springframework.core.io.buffer DataBufferUtils release

List of usage examples for org.springframework.core.io.buffer DataBufferUtils release

Introduction

In this page you can find the example usage for org.springframework.core.io.buffer DataBufferUtils release.

Prototype

public static boolean release(@Nullable DataBuffer dataBuffer) 

Source Link

Document

Release the given data buffer, if it is a PooledDataBuffer and has been PooledDataBuffer#isAllocated() allocated .

Usage

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

@Override
public Flux<Part> read(ResolvableType elementType, ReactiveHttpInputMessage message,
        Map<String, Object> hints) {
    byte[] boundary = boundary(message);
    if (boundary == null) {
        return Flux.error(new CodecException("No multipart boundary found in Content-Type: \""
                + message.getHeaders().getContentType() + "\""));
    }/*from w  w w  .ja  v  a  2 s.c o  m*/
    if (logger.isTraceEnabled()) {
        logger.trace("Boundary: " + toString(boundary));
    }

    byte[] boundaryNeedle = concat(BOUNDARY_PREFIX, boundary);
    Flux<DataBuffer> body = skipUntilFirstBoundary(message.getBody(), boundary);

    return DataBufferUtils.split(body, boundaryNeedle).takeWhile(DefaultMultipartMessageReader::notLastBoundary)
            .map(DefaultMultipartMessageReader::toPart)
            .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release)
            .doOnDiscard(DefaultPart.class, part -> DataBufferUtils.release(part.body));
}

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

/**
 * Finds the fist occurrence of the boundary in the given stream of data buffers, and skips
 * all data until then. Note that the first boundary of a multipart message does not contain
 * the initial \r\n, hence the need for a special boundary matcher.
 *///from  w ww.  j  a v  a 2s  . c om
private static Flux<DataBuffer> skipUntilFirstBoundary(Flux<DataBuffer> dataBuffers, byte[] boundary) {
    byte[] needle = concat(FIRST_BOUNDARY_PREFIX, boundary);
    DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(needle);
    AtomicBoolean found = new AtomicBoolean();

    return dataBuffers.concatMap(dataBuffer -> {
        if (found.get()) {
            return Mono.just(dataBuffer);
        } else {
            int endIdx = matcher.match(dataBuffer);
            if (endIdx != -1) {
                found.set(true);
                int length = dataBuffer.writePosition() - 1 - endIdx;
                DataBuffer slice = dataBuffer.retainedSlice(endIdx + 1, length);
                DataBufferUtils.release(dataBuffer);
                if (logger.isTraceEnabled()) {
                    logger.trace("Found first boundary at " + endIdx + " in " + toString(dataBuffer));
                }
                return Mono.just(slice);
            } else {
                DataBufferUtils.release(dataBuffer);
                return Mono.empty();
            }
        }
    });
}

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

/**
 * Indicates whether the given data buffer is not the last boundary, i.e. it does not start
 * with two hyphens./*from  w  ww.  j  a  v  a 2s .  c o  m*/
 */
private static boolean notLastBoundary(DataBuffer dataBuffer) {
    if (dataBuffer.readableByteCount() >= 2) {
        int readPosition = dataBuffer.readPosition();
        if (dataBuffer.getByte(readPosition) == HYPHEN && dataBuffer.getByte(readPosition + 1) == HYPHEN) {
            DataBufferUtils.release(dataBuffer);
            return false;
        }
    }
    return true;
}

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

/**
 * Convert the given data buffer into a Part. All data up until the header separator (\r\n\r\n)
 * is passed to {@link #toHeaders(DataBuffer)}, the remaining data is considered to be the
 * body./* w w w.j a v  a  2  s.co  m*/
 */
private static Part toPart(DataBuffer dataBuffer) {
    int readPosition = dataBuffer.readPosition();
    if (dataBuffer.readableByteCount() >= 2) {
        if (dataBuffer.getByte(readPosition) == CR && dataBuffer.getByte(readPosition + 1) == LF) {
            dataBuffer.readPosition(readPosition + 2);
        }
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Part data: " + toString(dataBuffer));
    }
    int endIdx = HEADER_MATCHER.match(dataBuffer);

    HttpHeaders headers;
    DataBuffer body;
    if (endIdx > 0) {
        readPosition = dataBuffer.readPosition();
        int headersLength = endIdx + 1 - (readPosition + HEADER_BODY_SEPARATOR.length);
        DataBuffer headersBuffer = dataBuffer.retainedSlice(readPosition, headersLength);
        int bodyLength = dataBuffer.writePosition() - (1 + endIdx);
        body = dataBuffer.retainedSlice(endIdx + 1, bodyLength);
        headers = toHeaders(headersBuffer);
    } else {
        headers = new HttpHeaders();
        body = DataBufferUtils.retain(dataBuffer);
    }
    DataBufferUtils.release(dataBuffer);

    ContentDisposition cd = headers.getContentDisposition();
    MediaType contentType = headers.getContentType();
    if (StringUtils.hasLength(cd.getFilename())) {
        return new DefaultFilePart(headers, body);
    } else if (StringUtils.hasLength(cd.getName())
            && (contentType == null || MediaType.TEXT_PLAIN.isCompatibleWith(contentType))) {
        return new DefaultFormPart(headers, body);
    } else {
        return new DefaultPart(headers, body);
    }
}

From source file:org.springframework.http.codec.multipart.DefaultMultipartMessageReader.java

/**
 * Convert the given data buffer into a {@link HttpHeaders} instance. The given string is read
 * as US-ASCII, then split along \r\n line boundaries, each line containing a header name and
 * value(s).//from  w  ww  . j ava2 s .  c  om
 */
private static HttpHeaders toHeaders(DataBuffer dataBuffer) {
    byte[] bytes = new byte[dataBuffer.readableByteCount()];
    dataBuffer.read(bytes);
    DataBufferUtils.release(dataBuffer);
    String string = new String(bytes, StandardCharsets.US_ASCII);
    String[] lines = string.split(HEADER_SEPARATOR);
    HttpHeaders result = new HttpHeaders();
    for (String line : lines) {
        int idx = line.indexOf(':');
        if (idx != -1) {
            String name = line.substring(0, idx);
            String value = line.substring(idx + 1);
            while (value.startsWith(" ")) {
                value = value.substring(1);
            }
            String[] tokens = StringUtils.tokenizeToStringArray(value, ",");
            for (String token : tokens) {
                result.add(name, token);
            }
        }
    }
    return result;
}

From source file:org.springframework.http.server.reactive.AbstractResponseBodyProcessor.java

/**
 * Called when the current buffer should be
 * {@linkplain DataBufferUtils#release(DataBuffer) released}.
 *///from ww  w . j ava 2s .  com
protected void releaseBuffer() {
    if (logger.isTraceEnabled()) {
        logger.trace("releaseBuffer: " + this.currentBuffer);
    }
    DataBufferUtils.release(this.currentBuffer);
    this.currentBuffer = null;
}

From source file:org.springframework.web.reactive.resource.AppCacheManifestTransformer.java

@Override
public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource,
        ResourceTransformerChain chain) {

    return chain.transform(exchange, inputResource).flatMap(outputResource -> {
        String name = outputResource.getFilename();
        if (!this.fileExtension.equals(StringUtils.getFilenameExtension(name))) {
            return Mono.just(outputResource);
        }//from w w w  .  ja  va2  s .co m
        DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
        Flux<DataBuffer> flux = DataBufferUtils.read(outputResource, bufferFactory, StreamUtils.BUFFER_SIZE);
        return DataBufferUtils.join(flux).flatMap(dataBuffer -> {
            CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer());
            DataBufferUtils.release(dataBuffer);
            String content = charBuffer.toString();
            return transform(content, outputResource, chain, exchange);
        });
    });
}

From source file:org.springframework.web.reactive.resource.CssLinkResourceTransformer.java

@Override
public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource,
        ResourceTransformerChain transformerChain) {

    return transformerChain.transform(exchange, inputResource).flatMap(ouptputResource -> {
        String filename = ouptputResource.getFilename();
        if (!"css".equals(StringUtils.getFilenameExtension(filename))
                || inputResource instanceof GzipResourceResolver.GzippedResource) {
            return Mono.just(ouptputResource);
        }/*from w  w w  .  jav a  2s . c  o  m*/

        if (logger.isTraceEnabled()) {
            logger.trace("Transforming resource: " + ouptputResource);
        }

        DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
        Flux<DataBuffer> flux = DataBufferUtils.read(ouptputResource, bufferFactory, StreamUtils.BUFFER_SIZE);
        return DataBufferUtils.join(flux).flatMap(dataBuffer -> {
            CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer());
            DataBufferUtils.release(dataBuffer);
            String cssContent = charBuffer.toString();
            return transformContent(cssContent, ouptputResource, transformerChain, exchange);
        });
    });
}