Example usage for org.springframework.core.io Resource contentLength

List of usage examples for org.springframework.core.io Resource contentLength

Introduction

In this page you can find the example usage for org.springframework.core.io Resource contentLength.

Prototype

long contentLength() throws IOException;

Source Link

Document

Determine the content length for this resource.

Usage

From source file:org.jahia.modules.external.test.db.WriteableMappedDatabaseProvider.java

private static void extract(JahiaTemplatesPackage p, org.springframework.core.io.Resource r, File f)
        throws Exception {
    if ((r instanceof BundleResource && r.contentLength() == 0)
            || (!(r instanceof BundleResource) && r.getFile().isDirectory())) {
        f.mkdirs();//from www  . ja v  a 2s  .  c o  m
        String path = r.getURI().getPath();
        for (org.springframework.core.io.Resource resource : p
                .getResources(path.substring(path.indexOf("/toursdb")))) {
            extract(p, resource, new File(f, resource.getFilename()));
        }
    } else {
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(f);
            IOUtils.copy(r.getInputStream(), output);
        } finally {
            IOUtils.closeQuietly(output);
        }
    }
}

From source file:com.intuit.cto.selfservice.service.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to/*  w  w w .  ja  va 2 s  . co  m*/
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    FileUtils.copyURLToFile(url, targetFile);
                    counter++;
                }
            }
        }
    }
    logger.info("Unpacked {} files from {} to {}", new Object[] { counter, locationPattern, toDir });
    return counter;
}

From source file:ch.vorburger.mariadb4j.Util.java

/**
 * Extract files from a package on the classpath into a directory.
 * //from   ww  w  .j ava  2 s  . c  om
 * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot)
 * @param toDir directory to extract to
 * @return int the number of files copied
 * @throws java.io.IOException if something goes wrong, including if nothing was found on
 *             classpath
 */
public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException {
    String locationPattern = "classpath*:" + packagePath + "/**";
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resourcePatternResolver.getResources(locationPattern);
    if (resources.length == 0) {
        throw new IOException("Nothing found at " + locationPattern);
    }
    int counter = 0;
    for (Resource resource : resources) {
        if (resource.isReadable()) { // Skip hidden or system files
            final URL url = resource.getURL();
            String path = url.toString();
            if (!path.endsWith("/")) { // Skip directories
                int p = path.lastIndexOf(packagePath) + packagePath.length();
                path = path.substring(p);
                final File targetFile = new File(toDir, path);
                long len = resource.contentLength();
                if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files
                    tryN(5, 500, new Procedure<IOException>() {

                        @Override
                        public void apply() throws IOException {
                            FileUtils.copyURLToFile(url, targetFile);
                        }
                    });
                    counter++;
                }
            }
        }
    }
    if (counter > 0) {
        Object[] info = new Object[] { counter, locationPattern, toDir };
        logger.info("Unpacked {} files from {} to {}", info);
    }
    return counter;
}

From source file:jails.http.converter.ResourceHttpMessageConverter.java

protected Long getContentLength(Resource resource, MediaType contentType) throws IOException {
    return resource.contentLength();
}

From source file:com.greglturnquist.HomeController.java

private ResponseEntity<?> getRawImage() {
    try {//  w  ww.  jav a2s. c  om
        Resource file = resourceLoader.getResource("file:upload-dir/keep-calm-and-learn-javascript.jpg");
        return ResponseEntity.ok().contentLength(file.contentLength()).contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't find it => " + e.getMessage());
    }
}

From source file:com.greglturnquist.springagram.fileservice.s3.ApplicationController.java

@RequestMapping(method = RequestMethod.GET, value = "/files/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename) throws IOException {

    Resource file = this.fileService.findOne(filename);

    try {//from  w  w  w.ja va  2 s  .  c  o m
        return ResponseEntity.ok().contentLength(file.contentLength()).contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}

From source file:cn.im47.cloud.storage.utilities.RangingResourceHttpRequestHandler.java

public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String requestPath = requestURI.substring(contextPath.length());

    //locations are set up for delegation if desired
    /*//from   ww  w .  ja va 2  s .c o  m
    if (!requestPath.startsWith("/media/"))  {
    super.handleRequest(request, response);
    }
    */

    boolean useRanges = false;
    int rangeStart = 0;
    int rangeEnd = 0;

    String rangeHeader = request.getHeader(RANGE);
    if (null != rangeHeader) {
        try {
            if (rangeHeader.startsWith(BYTES_PREFIX)) {
                String range = rangeHeader.substring(BYTES_PREFIX.length());
                int splitIndex = range.indexOf("-");
                String startString = range.substring(0, splitIndex);
                String endString = range.substring(splitIndex + 1);
                rangeStart = Integer.parseInt(startString);
                rangeEnd = Integer.parseInt(endString);
                useRanges = true;
            }
        } catch (Exception e) {
            useRanges = false;
            if (log.isLoggable(Level.FINE)) {
                log.fine("Unable to decode range header " + rangeHeader);
            }
        }
    }

    response.setContentType(context.getServletContext().getMimeType(requestPath));
    response.setHeader("Accept-Ranges", "bytes");

    Resource theResource = context.getResource(requestPath);
    String contentLength = Long.toString(theResource.contentLength());
    InputStream in = context.getResource(requestPath).getInputStream();
    OutputStream out = response.getOutputStream();

    if (useRanges) {
        response.setHeader(CONTENT_RANGE, "bytes " + rangeStart + "-" + rangeEnd + "/" + contentLength);
        response.setContentLength(1 + rangeEnd - rangeStart);
        copyStream(in, out, rangeStart, rangeEnd);
    } else {
        copyStream(in, out);
    }
}

From source file:it.tidalwave.northernwind.frontend.ui.component.DefaultStaticHtmlFragmentViewController.java

protected void populate(final @Nonnull String htmlResourceName, final @Nonnull Map<String, String> attributes)
        throws IOException {
    final Resource htmlResource = new ClassPathResource(htmlResourceName, getClass());
    final @Cleanup Reader r = new InputStreamReader(htmlResource.getInputStream());
    final CharBuffer charBuffer = CharBuffer.allocate((int) htmlResource.contentLength());
    final int length = r.read(charBuffer);
    r.close();/*from w w w  .j a  v  a  2  s .com*/
    final String html = new String(charBuffer.array(), 0, length);

    ST template = new ST(html, '$', '$');

    for (final Entry<String, String> entry : attributes.entrySet()) {
        template = template.add(entry.getKey(), entry.getValue());
    }

    view.setContent(template.render());
}

From source file:it.tidalwave.northernwind.frontend.ui.component.gallery.spi.GalleryAdapterSupport.java

/*******************************************************************************************************************
 *
 *
 *
 ******************************************************************************************************************/
@Nonnull//www .  j  ava2 s .c o  m
private String loadDefaultTemplate(final @Nonnull String templateName) throws IOException {
    final String packagePath = getClass().getPackage().getName().replace('.', '/');
    final Resource resource = new ClassPathResource("/" + packagePath + "/" + templateName);
    final @Cleanup Reader r = new InputStreamReader(resource.getInputStream());
    final char[] buffer = new char[(int) resource.contentLength()];
    r.read(buffer);
    return new String(buffer);
}

From source file:com.civilizer.web.handler.ResourceHttpRequestHandler.java

/**
 * Set headers on the given servlet response.
 * Called for GET requests as well as HEAD requests.
 * @param response current servlet response
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 * @throws IOException in case of errors while setting the headers
 *//*from  w  ww . j  a  v a 2s.co m*/
protected void setHeaders(HttpServletResponse response, Resource resource, MediaType mediaType)
        throws IOException {
    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("Resource content too long (beyond Integer.MAX_VALUE): " + resource);
    }
    response.setContentLength((int) length);

    if (mediaType != null) {
        response.setContentType(mediaType.toString());
    }
}