Example usage for org.apache.wicket.util.resource IResourceStream close

List of usage examples for org.apache.wicket.util.resource IResourceStream close

Introduction

In this page you can find the example usage for org.apache.wicket.util.resource IResourceStream close.

Prototype

@Override
void close() throws IOException;

Source Link

Document

Closes the resource.

Usage

From source file:com.visural.wicket.util.lesscss.LessCSSResourceStreamLocator.java

License:Apache License

private CacheResponse getResponse(IResourceStream stream) throws ResourceStreamNotFoundException, IOException {
    byte[] data = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int r;//from   ww  w .  j a  va  2 s .  com
    InputStream in = stream.getInputStream();
    while ((r = in.read()) != -1) {
        baos.write(r);
    }
    stream.close();
    data = baos.toByteArray();
    LessCSS engine = new LessCSS();
    String lesscss = engine.less(new ByteArrayInputStream(data));
    CacheResponse cr = new CacheResponse(lesscss.getBytes().length, lesscss);
    return cr;
}

From source file:de.alpharogroup.wicket.js.addon.core.StringTextTemplate.java

License:Apache License

/**
 * Creates a new instance of a {@link StringTextTemplate}.
 * /*from   www. j a va2 s  .  co  m*/
 * @param content
 *            The content of the template.
 * @param contentType
 *            The content type.
 * @param encoding
 *            the file's encoding
 */
public StringTextTemplate(final String content, final String contentType, final String encoding) {
    super(contentType);
    final IResourceStream stream = new StringResourceStream(content, getContentType());
    try {
        if (encoding != null) {
            buffer.append(Streams.readString(stream.getInputStream(), encoding));
        } else {
            buffer.append(Streams.readString(stream.getInputStream()));
        }
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } catch (final ResourceStreamNotFoundException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            stream.close();
        } catch (final IOException e) {
            LOGGER.error("" + e.getMessage(), e);
        }
    }
}

From source file:de.inren.frontend.jqplot.JqplotPanel.java

License:Apache License

public static String convertStreamToString(IResourceStream is) {
    String res = null;/*from   ww  w  . java  2 s  . c  o  m*/
    try {
        @SuppressWarnings("resource")
        Scanner s = new Scanner(is.getInputStream(), "UTF-8").useDelimiter("\\A");
        res = s.hasNext() ? s.next() : null;
        is.close();
    } catch (ResourceStreamNotFoundException e) {
        log.error(e.getMessage(), e);
        res = null;
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        res = null;
    }
    return res;
}

From source file:fiftyfive.wicket.js.locator.SprocketDependencyCollector.java

License:Apache License

/**
 * Parse the given stream and translate any i/o exceptions into
 * WicketRuntimeException. Close the stream cleanly no matter what.
 *///  w w w .  j av  a2s  . c  om
private List<Sprocket> parseSprockets(IResourceStream stream) {
    try {
        InputStream is = stream.getInputStream();
        String enc = JavaScriptDependencySettings.get().getEncoding();
        return parseSprockets(new BufferedReader(new InputStreamReader(is, enc)));
    } catch (IOException ioe) {
        throw new WicketRuntimeException(ioe);
    } catch (ResourceStreamNotFoundException rsnfe) {
        throw new WicketRuntimeException(rsnfe);
    } finally {
        try {
            stream.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:fiftyfive.wicket.js.locator.SprocketsDependencyCollector.java

License:Apache License

/**
 * Parse the given stream and translate any i/o exceptions into
 * WicketRuntimeException. Close the stream cleanly no matter what.
 *//*from  ww w.  j  a va2 s.  c  o m*/
private List<Sprocket> parseSprocketsFromStream(IResourceStream stream) {
    try {
        InputStream is = stream.getInputStream();
        String enc = JavaScriptDependencySettings.get().getEncoding();
        return this.parser.parseSprockets(new BufferedReader(new InputStreamReader(is, enc)));
    } catch (IOException ioe) {
        throw new WicketRuntimeException(ioe);
    } catch (ResourceStreamNotFoundException rsnfe) {
        throw new WicketRuntimeException(rsnfe);
    } finally {
        try {
            stream.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.apache.openmeetings.web.util.RecordingResourceReference.java

License:Apache License

@Override
public IResource getResource() {
    return new AbstractResource() {
        private static final long serialVersionUID = 1L;
        private final static String ACCEPT_RANGES_HEADER = "Accept-Ranges";
        private final static String RANGE_HEADER = "Range";
        private final static String CONTENT_RANGE_HEADER = "Content-Range";
        private final static String RANGES_BYTES = "bytes";
        private File file;
        private boolean isRange = false;
        private long start = 0;
        private long end = 0;

        private long getChunkLength() {
            return isRange ? end - start + 1 : (file == null ? -1 : file.length());
        }/*w w  w .j ava 2s .c om*/

        private IResourceStream getResourceStream() {
            return file == null ? null : new FileResourceStream(file) {
                private static final long serialVersionUID = 2546785247219805747L;
                private transient BoundedInputStream bi;

                @Override
                public InputStream getInputStream() throws ResourceStreamNotFoundException {
                    if (bi == null) {
                        //bi = new BoundedInputStream(super.getInputStream(), end + 1);
                        bi = new BoundedInputStream(super.getInputStream(),
                                isRange ? end + 1 : (file == null ? -1 : file.length()));
                        try {
                            bi.skip(start);
                        } catch (IOException e) {
                            throw new ResourceStreamNotFoundException(e);
                        }
                    }
                    return bi;
                }

                @Override
                public Bytes length() {
                    return Bytes.bytes(getChunkLength());
                }

                @Override
                public void close() throws IOException {
                    if (bi != null) {
                        bi.close(); //also will close original stream
                        bi = null;
                    }
                }

                @Override
                public String getContentType() {
                    return RecordingResourceReference.this.getContentType();
                }
            };
        }

        @Override
        protected void setResponseHeaders(ResourceResponse data, Attributes attributes) {
            Response response = attributes.getResponse();
            if (response instanceof WebResponse) {
                WebResponse webResponse = (WebResponse) response;
                webResponse.setStatus(
                        isRange ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
            }
            super.setResponseHeaders(data, attributes);
        }

        @Override
        protected ResourceResponse newResourceResponse(Attributes attributes) {
            ResourceResponse rr = new ResourceResponse();
            FlvRecording r = getRecording(attributes);
            if (r != null) {
                isRange = false;
                file = getFile(r);
                rr.setFileName(getFileName(r));
                rr.setContentType(RecordingResourceReference.this.getContentType());
                rr.setContentDisposition(ContentDisposition.INLINE);
                rr.setLastModified(Time.millis(file.lastModified()));
                rr.getHeaders().addHeader(ACCEPT_RANGES_HEADER, RANGES_BYTES);
                String range = ((HttpServletRequest) attributes.getRequest().getContainerRequest())
                        .getHeader(RANGE_HEADER);
                if (range != null && range.startsWith(RANGES_BYTES)) {
                    String[] bounds = range.substring(RANGES_BYTES.length() + 1).split("-");
                    if (bounds != null && bounds.length > 0) {
                        long length = file.length();
                        isRange = true;
                        start = Long.parseLong(bounds[0]);
                        end = bounds.length > 1 ? Long.parseLong(bounds[1]) : length - 1;
                        //Content-Range: bytes 229376-232468/232469
                        rr.getHeaders().addHeader(CONTENT_RANGE_HEADER,
                                String.format("%s %d-%d/%d", RANGES_BYTES, start, end, length));
                    }
                }
                rr.setContentLength(getChunkLength());
                rr.setWriteCallback(new WriteCallback() {
                    @Override
                    public void writeData(Attributes attributes) throws IOException {
                        IResourceStream rStream = getResourceStream();
                        try {
                            writeStream(attributes, rStream.getInputStream());
                        } catch (ResourceStreamNotFoundException e1) {
                        } catch (ResponseIOException e) {
                            // in case of range operations we expecting such exceptions
                            if (!isRange) {
                                log.error("Error while playing the stream", e);
                            }
                        } finally {
                            rStream.close();
                        }
                    }
                });
            } else {
                rr.setError(HttpServletResponse.SC_NOT_FOUND);
            }
            return rr;
        }
    };
}

From source file:org.cast.cwm.ResourceDirectory.java

License:Open Source License

/**
 * creates a new resource response based on the request attributes
 * //from  w  ww .  ja v  a2  s.c om
 * @param attributes
 *            current request attributes from client
 * @return resource response for answering request
 */
@Override
protected ResourceResponse newResourceResponse(Attributes attributes) {
    String relativePath = "";
    PageParameters parameters = attributes.getParameters();
    for (int i = 0; i < parameters.getIndexedCount(); i++) {
        relativePath += parameters.get(i);
        relativePath += '/';
    }
    if (relativePath.endsWith("/"))
        relativePath = relativePath.substring(0, relativePath.length() - 1);
    log.trace("relativePath is {}", relativePath);

    String absolutePath = new File(sourceDirectory, relativePath).getAbsolutePath();

    final ResourceResponse resourceResponse = new ResourceResponse();

    final IResourceStream resourceStream = getResourceStream(absolutePath);

    // bail out if resource stream could not be found
    if (resourceStream == null) {
        return sendResourceError(absolutePath, resourceResponse, HttpServletResponse.SC_NOT_FOUND,
                "Unable to find resource");
    }

    // allow caching
    resourceResponse.setCacheScope(WebResponse.CacheScope.PUBLIC);
    resourceResponse.setCacheDuration(cacheDuration);

    // add Last-Modified header (to support HEAD requests and If-Modified-Since)
    resourceResponse.setLastModified(resourceStream.lastModifiedTime());

    if (resourceResponse.dataNeedsToBeWritten(attributes)) {
        String contentType = resourceStream.getContentType();

        if (contentType == null && Application.exists())
            contentType = Application.get().getMimeType(absolutePath);

        // set Content-Type (may be null)
        resourceResponse.setContentType(contentType);

        try {
            // read resource data
            final byte[] bytes;

            bytes = IOUtils.toByteArray(resourceStream.getInputStream());

            // send Content-Length header
            resourceResponse.setContentLength(bytes.length);

            // send response body with resource data
            resourceResponse.setWriteCallback(new WriteCallback() {
                @Override
                public void writeData(Attributes attributes) {
                    attributes.getResponse().write(bytes);
                }
            });
        } catch (IOException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(absolutePath, resourceResponse, 500, "Unable to read resource stream");
        } catch (ResourceStreamNotFoundException e) {
            log.debug(e.getMessage(), e);
            return sendResourceError(absolutePath, resourceResponse, 500, "Unable to open resource stream");
        } finally {
            try {
                resourceStream.close();
            } catch (IOException e) {
                log.warn("Unable to close the resource stream", e);
            }
        }
    }

    return resourceResponse;
}