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:objective.taskboard.controller.FollowUpController.java

@RequestMapping("generic-template")
public ResponseEntity<Object> genericTemplate() {
    try {/*  www .j a  v a 2 s. c  o m*/
        Resource resource = followUpFacade.getGenericTemplate();
        return ResponseEntity.ok().contentLength(resource.contentLength())
                .header("Content-Disposition", "attachment; filename=generic-followup-template.xlsm")
                .body(resource);
    } catch (Exception e) {
        log.warn("Error while serving genericTemplate", e);
        return new ResponseEntity<>(e.getMessage() == null ? e.toString() : e.getMessage(),
                INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

public void bootstrapFormats() throws InterruptedException, IOException {

    if (isDisabled) {
        log.info("MetadataFormatRegistryBootstrap is disabled; not executing bootstrapping process.");
        return;//  w w w  . j  a  va 2  s .  c om
    }

    long bootStart = System.currentTimeMillis();
    log.info("Bootstrapping the DCS... ");
    MetadataSchemeMapper schemeMapper = new MetadataSchemeMapper();

    MetadataFormatMapper mapper = new MetadataFormatMapper(schemeMapper);

    Iterator<RegistryEntry<DcsMetadataFormat>> iter = memoryRegistry.iterator();

    List<DepositInfo> depositStatus = new ArrayList<DepositInfo>();

    while (iter.hasNext()) {
        RegistryEntry<DcsMetadataFormat> registryEntry = iter.next();

        try {
            if (queryService.lookup(registryEntry.getId()) != null) {
                // The archive already has the entry
                log.debug("Not bootstrapping registry entry {}: it is already in the archive.",
                        registryEntry.getId());
                continue;
            }
        } catch (QueryServiceException e) {
            log.warn("Error depositing DCP (skipping it): " + e.getMessage(), e);
            continue;
        }

        final Dcp entryDcp = mapper.to(registryEntry, null);

        for (DcsFile dcsFile : entryDcp.getFiles()) {
            final Resource r;
            if (dcsFile.getSource().startsWith(FILE_PREFIX)) {
                r = new FileSystemResource(new URL(dcsFile.getSource()).getPath());
            } else if (dcsFile.getSource().startsWith(CLASSPATH_PREFIX)) {
                r = new ClassPathResource(dcsFile.getSource().substring(CLASSPATH_PREFIX.length()));
            } else {
                throw new RuntimeException(
                        "Unknown file source " + dcsFile.getSource() + " for file name " + dcsFile.getName());
            }

            if (!r.exists()) {
                throw new RuntimeException("Resource " + r.getFilename() + " doesn't exist.");
            }

            Map<String, String> metadata = new HashMap<String, String>();
            HttpHeaderUtil.addDigest("SHA-1", calculateChecksum("SHA-1", r), metadata);
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_DISPOSITION, "filename=" + r.getFilename());
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Long.toString(r.contentLength()));
            DepositInfo info = fileManager.deposit(r.getInputStream(), APPLICATION_XML, null, metadata);
            dcsFile.setSource(info.getMetadata().get(SRC_HEADER));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        modelBuilder.buildSip(entryDcp, baos);
        try {
            Map<String, String> metadata = new HashMap<String, String>();
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Integer.toString(baos.size()));
            final ByteArrayInputStream byteIn = new ByteArrayInputStream(baos.toByteArray());
            depositStatus.add(manager.deposit(byteIn, APPLICATION_XML, DCP_PACKAGING, metadata));
        } catch (PackageException e) {
            log.warn("Error depositing DCP: " + e.getMessage(), e);
            continue;
        }
    }

    Iterator<DepositInfo> statusItr = depositStatus.iterator();

    while (statusItr.hasNext()) {
        DepositInfo info = statusItr.next();
        try {
            if (!checkStatusUntilTimeout(info, 600000)) {
                File f;
                FileOutputStream fos = null;
                try {
                    f = File.createTempFile("bootstrap-", ".xml");
                    fos = new FileOutputStream(f);
                    IOUtils.copy(info.getDepositStatus().getInputStream(), fos);
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
                log.warn(
                        "Error bootstrapping the DCS; error depositing package {}: see {} for more information.",
                        info.getDepositID(), f.getAbsolutePath());
            }
        } catch (Exception e) {
            log.warn("Error bootstrapping the DCS; error depositing package {}: {}",
                    new Object[] { info.getDepositID(), e.getMessage(), e });
        }
    }

    log.info("Bootstrap complete in {} ms", System.currentTimeMillis() - bootStart);
}

From source file:org.dataconservancy.ui.dcpmap.DataSetMapper.java

/**
 * Maps a File (from a DataItem) to a DcsFile; includes the generation of fixity.  TODO: format.
 *
 * @param dataFile the data file to map//from  w w  w.  j a va 2s  .c om
 * @return the DcsFile containing the DataFile
 * @throws DcpMappingException if there is an error performing the mapping
 */
private DcsFile mapDataFile(DataFile dataFile) throws DcpMappingException {
    DcsFile dcsFile = new DcsFile();

    dcsFile.setId(dataFile.getId());
    // Map File name and source to DcsFile name and source
    dcsFile.setSource(dataFile.getSource());
    dcsFile.setName(dataFile.getName());

    // add ui generated format to use as mime type: identify this format by setting version to "dcs-ui"
    // we need this version specified to correctly do the inverse mapping
    if (dataFile.getFormat() != null && !dataFile.getFormat().isEmpty()) {//have to check this, some DcsFormat fields
        //may not be null or empty
        DcsFormat format = new DcsFormat();
        format.setName(dataFile.getFormat());
        format.setFormat(dataFile.getFormat());
        format.setSchemeUri("http://www.iana.org/assignments/media-types/");
        format.setVersion("dcs-ui");
        dcsFile.addFormat(format);
    }

    // Mapped DcsFiles automatically have extant set to 'true'
    dcsFile.setExtant(true);

    // Map the business id to an alternate id.
    dcsFile.addAlternateId(
            new DcsResourceIdentifier(Id.getAuthority(), dataFile.getId(), Types.DATA_FILE.name()));

    try {
        Resource r = new UrlResource(dcsFile.getSource());

        if (dataFile.getSize() > 0) {
            dcsFile.setSizeBytes(dataFile.getSize());
        } else {
            dcsFile.setSizeBytes(r.contentLength());
        }

        dcsFile.addFixity(calculateFixity(r.getInputStream(), MessageDigest.getInstance("MD5")));
        dcsFile.addFixity(calculateFixity(r.getInputStream(), MessageDigest.getInstance("SHA1")));
    } catch (Exception e) {
        throw new DcpMappingException("Error calculating file length or fixity: " + e.getMessage(), e);
    }

    return dcsFile;
}

From source file:org.dataconservancy.ui.it.ArchiveServiceIT.java

private DataFile addFile(DataItem ds, String name) throws Exception {
    DataFile file = new DataFile();
    file.setParentId(ds.getId());/*from   w ww.  j  a  va 2 s.  c o  m*/

    CreateIdApiRequest fileIdRequest = reqFactory.createIdApiRequest(Types.DATA_FILE);
    file.setId(fileIdRequest.execute(hc));
    file.setName(name);

    java.io.File tmp = java.io.File.createTempFile(this.getClass().getName() + "-", ".txt");
    FileUtils.writeStringToFile(tmp, "ArchiveServiceIT temp file.");
    tmp.deleteOnExit();
    file.setSource(tmp.toURI().toString());
    file.setPath(System.getProperty("java.io.tmpdir"));

    Resource r = new UrlResource(file.getSource());
    file.setSize(r.contentLength());

    ds.addFile(file);

    return file;
}

From source file:org.dataconservancy.ui.it.ArchiveServiceIT.java

private MetadataFile addMetadataFile(String id, String name) throws IOException {
    final MetadataFile file = new MetadataFile();
    file.setId(id);//  w w w  .  j a va2 s.com
    file.setName(name);
    file.setMetadataFormatId("format:id");
    java.io.File tmp = java.io.File.createTempFile(this.getClass().getName() + "-", ".txt");
    tmp.deleteOnExit();
    file.setSource(tmp.toURI().toString());
    file.setPath(System.getProperty("java.io.tmpdir"));

    Resource r = new UrlResource(file.getSource());
    file.setSize(r.contentLength());

    return file;
}

From source file:org.mifos.reports.MifosViewerServletContextListener.java

private void copyFromClassPathToDirectory(String directoryToScan, File rootDirectory) throws IOException {
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources(LOCATION_PATTERN);
    LOGGER.info("Found " + resources.length + " Resources on " + LOCATION_PATTERN);
    for (Resource resource : resources) {
        if (resource.exists() & resource.isReadable() && resource.contentLength() > 0) {
            URL url = resource.getURL();
            String urlString = url.toExternalForm();
            String targetName = urlString.substring(urlString.indexOf(directoryToScan));
            File destination = new File(rootDirectory, targetName);
            FileUtils.copyURLToFile(url, destination);
            LOGGER.info("Copied " + url + " to " + destination.getAbsolutePath());
        } else {/* w  w w . j  a  v a  2s  .c  o m*/
            LOGGER.debug("Did not copy, seems to be directory: " + resource.getDescription());
        }
    }
}

From source file:org.springframework.http.codec.ResourceHttpMessageWriter.java

private static long lengthOf(Resource resource) {
    // Don't consume InputStream...
    if (InputStreamResource.class != resource.getClass()) {
        try {//from w w w .  j  a v  a2s . c  o m
            return resource.contentLength();
        } catch (IOException ignored) {
        }
    }
    return -1;
}

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

/**
 * Set headers on the response. Called for both GET and HEAD requests.
 * @param exchange current exchange/*from   www  .ja  v a 2s .co m*/
 * @param resource the identified resource (never {@code null})
 * @param mediaType the resource's media type (never {@code null})
 */
protected void setHeaders(ServerWebExchange exchange, Resource resource, @Nullable MediaType mediaType)
        throws IOException {

    HttpHeaders headers = exchange.getResponse().getHeaders();

    long length = resource.contentLength();
    headers.setContentLength(length);

    if (mediaType != null) {
        headers.setContentType(mediaType);
    }
    if (resource instanceof HttpResource) {
        HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
        exchange.getResponse().getHeaders().putAll(resourceHeaders);
    }
}

From source file:org.springframework.web.servlet.resource.ResourceHttpRequestHandler.java

/**
 * Processes a resource request.//from  w ww  .j  a  v a 2  s . co m
 * <p>Checks for the existence of the requested resource in the configured list of locations.
 * If the resource does not exist, a {@code 404} response will be returned to the client.
 * If the resource exists, the request will be checked for the presence of the
 * {@code Last-Modified} header, and its value will be compared against the last-modified
 * timestamp of the given resource, returning a {@code 304} status code if the
 * {@code Last-Modified} value  is greater. If the resource is newer than the
 * {@code Last-Modified} value, or the header is not present, the content resource
 * of the resource will be written to the response with caching headers
 * set to expire one year in the future.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // For very general mappings (e.g. "/") we need to check 404 first
    Resource resource = getResource(request);
    if (resource == null) {
        logger.trace("No matching resource found - returning 404");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (HttpMethod.OPTIONS.matches(request.getMethod())) {
        response.setHeader("Allow", getAllowHeader());
        return;
    }

    // Supported methods and required session
    checkRequest(request);

    // Header phase
    if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
        logger.trace("Resource not modified - returning 304");
        return;
    }

    // Apply cache settings, if any
    prepareResponse(response);

    // Check the media type for the resource
    MediaType mediaType = getMediaType(request, resource);
    if (mediaType != null) {
        if (logger.isTraceEnabled()) {
            logger.trace("Determined media type '" + mediaType + "' for " + resource);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("No media type found for " + resource + " - not sending a content-type header");
        }
    }

    // Content phase
    if (METHOD_HEAD.equals(request.getMethod())) {
        setHeaders(response, resource, mediaType);
        logger.trace("HEAD request - skipping content");
        return;
    }

    ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
    if (request.getHeader(HttpHeaders.RANGE) == null) {
        Assert.state(this.resourceHttpMessageConverter != null, "Not initialized");
        setHeaders(response, resource, mediaType);
        this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
    } else {
        Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
        ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
        try {
            List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            this.resourceRegionHttpMessageConverter.write(HttpRange.toResourceRegions(httpRanges, resource),
                    mediaType, outputMessage);
        } catch (IllegalArgumentException ex) {
            response.setHeader("Content-Range", "bytes */" + resource.contentLength());
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
        }
    }
}

From source file:org.springframework.web.servlet.resource.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
 *//*  w w w  .  j a  va2s .  co  m*/
protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType)
        throws IOException {

    long length = resource.contentLength();
    if (length > Integer.MAX_VALUE) {
        response.setContentLengthLong(length);
    } else {
        response.setContentLength((int) length);
    }

    if (mediaType != null) {
        response.setContentType(mediaType.toString());
    }
    if (resource instanceof HttpResource) {
        HttpHeaders resourceHeaders = ((HttpResource) resource).getResponseHeaders();
        for (Map.Entry<String, List<String>> entry : resourceHeaders.entrySet()) {
            String headerName = entry.getKey();
            boolean first = true;
            for (String headerValue : entry.getValue()) {
                if (first) {
                    response.setHeader(headerName, headerValue);
                } else {
                    response.addHeader(headerName, headerValue);
                }
                first = false;
            }
        }
    }
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
}