Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceImpl.java

@Override
public String createXdmContainer(Patient patient, Mandant mandant, List<File> attachments, String xdmPath) {
    if (patient != null && mandant != null && attachments != null && xdmPath != null) {
        ConvenienceCommunication conCom = new ConvenienceCommunication();
        org.ehealth_connector.common.Patient ehealthPatient = EhcCoreMapper.getEhcPatient(patient);
        StringBuilder retInfo = new StringBuilder();
        retInfo.append(xdmPath);/*from  w  w  w .  ja va  2  s. co m*/
        for (File f : attachments) {
            try {
                if (f.exists()) {
                    String attachmentPath = f.getAbsolutePath();
                    DocumentDescriptor dc = null;
                    if (attachmentPath.toLowerCase().endsWith("xml")) {
                        if (isCdaDocument(f)) {
                            dc = DocumentDescriptor.CDA_R2;
                        } else {
                            dc = DocumentDescriptor.XML;
                        }
                    } else if (attachmentPath.toLowerCase().endsWith("pdf")) {
                        dc = DocumentDescriptor.PDF;
                    } else {
                        dc = new DocumentDescriptor(FilenameUtils.getExtension(attachmentPath),
                                Files.probeContentType(f.toPath()));
                    }

                    FileInputStream in = FileUtils.openInputStream(f);
                    DocumentMetadata metaData = conCom.addDocument(dc, in);
                    metaData.setPatient(ehealthPatient);
                    IOUtils.closeQuietly(in);
                    retInfo.append(":::");
                    retInfo.append(attachmentPath);

                } else {
                    LoggerFactory.getLogger(EhcCoreService.class).warn(
                            "creating xdm - patient [{}] - file does not exists [{}]", patient.getId(),
                            f.getAbsolutePath());
                }
            } catch (IOException e) {
                LoggerFactory.getLogger(EhcCoreService.class).error(
                        "creating xdm - patient [{}] - cannot add file [{}]", patient.getId(),
                        f.getAbsolutePath(), e);
            }
        }
        try {
            conCom.createXdmContents(xdmPath);
            if (retInfo.toString().contains(":::")) {
                return retInfo.toString();
            }
        } catch (Exception e) {
            LoggerFactory.getLogger(EhcCoreService.class)
                    .error("creating xdm - patient [{}] - cannot create xdm contents", patient.getId(), e);
        }
    }
    return null;
}

From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java

/**
 * Validates that a subset of a compact reads file can be written.
 *
 * @throws IOException if there is a problem reading or writing to the files
 *///from   w  ww.j  av a  2  s.c om
@Test
public void reformatStartOfCompactFile() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/s_1_sequence_short_1_per_chunk.compact-reads";
    reformat.setInputFilenames(inputFilename);
    reformat.setStartPosition(0);
    reformat.setEndPosition(10);
    final String outputFilename = "test-results/reformat-test-start.compact-reads";
    reformat.setOutputFile(outputFilename);
    reformat.execute();

    final File inputFile = new File(inputFilename);
    final File outputFile = new File(outputFilename);
    assertFalse("The reformatted file should not be the same as the original",
            FileUtils.contentEquals(inputFile, outputFile));

    final ReadsReader reader = new ReadsReader(FileUtils.openInputStream(outputFile));
    assertTrue("There should be reads in this file", reader.hasNext());
    final Reads.ReadEntry entry = reader.next();
    assertNotNull("Entry should not be null", entry);
    assertEquals("Reader returned the wrong sequence string", "CTCATGTTCATACACCTNTCCCCCATTCTCCTCCT",
            entry.getSequence().toString(Charset.defaultCharset().name()));
    assertFalse("There should be no other reads in this file", reader.hasNext());
}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

public InputStream getAttachmentImageThumbnailInputStream(Attachment image, int width, int height) {
    try {//from  w  ww .  j ava  2  s.  co m

        File file = getThumbnailFromCacheIfExist(image, width, height);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:com.silverpeas.gallery.web.AbstractGalleryResource.java

/**
 * Centralization of getting of media content.
 * @param expectedMediaType// w  w  w . j  a  v a2  s.  c  om
 * @param mediaId
 * @param requestedMediaResolution
 * @return
 */
protected Response getMediaContent(final MediaType expectedMediaType, final String mediaId,
        final MediaResolution requestedMediaResolution) {
    try {
        final Media media = getMediaService().getMedia(new MediaPK(mediaId, getComponentId()));
        checkNotFoundStatus(media);
        verifyUserMediaAccess(media);
        // Adjusting the resolution according to the user rights
        MediaResolution mediaResolution = ORIGINAL;
        if (media.getType().isPhoto()) {
            mediaResolution = requestedMediaResolution;
            if (ORIGINAL == requestedMediaResolution && !isUserPrivileged() && !media.isDownloadable()) {
                mediaResolution = MediaResolution.PREVIEW;
            }
        }
        // Verifying the physical file exists and that the type of media is the one expected
        final SilverpeasFile file = media.getFile(mediaResolution);
        if (!file.exists() || expectedMediaType != media.getType()) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        return Response.ok(new StreamingOutput() {
            @Override
            public void write(final OutputStream output) throws IOException, WebApplicationException {
                final InputStream mediaStream;
                try {
                    mediaStream = FileUtils.openInputStream(file);
                } catch (IOException e) {
                    throw new WebApplicationException(Status.NOT_FOUND);
                }
                try {
                    IOUtils.copy(mediaStream, output);
                } finally {
                    IOUtils.closeQuietly(mediaStream);
                }
            }
        }).header("Content-Type", ((InternalMedia) media).getFileMimeType().getMimeType())
                .header("Content-Length", file.length())
                .header("Content-Disposition", "inline; filename=\"" + file.getName() + "\"").build();
    } catch (final WebApplicationException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new WebApplicationException(ex, Status.SERVICE_UNAVAILABLE);
    }
}

From source file:com.sangupta.httpd.HttpdHandler.java

/**
 * Send file contents back to client//from   w ww.  j a  v  a2  s  . co  m
 * 
 * @param request
 * @param response
 * @param uri
 * @throws IOException
 */
private void sendFileContents(HttpServletRequest request, HttpServletResponse response, String uri)
        throws IOException {
    File file = new File(documentRoot, uri);
    if (!file.exists() || file.isHidden()) {
        response.sendError(HttpStatusCode.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        response.sendRedirect("/" + uri + "/");
        return;
    }

    if (!file.isFile()) {
        response.sendError(HttpStatusCode.FORBIDDEN);
        return;
    }

    String etag = null;
    if (!this.httpdConfig.noEtag) {
        // compute the weak ETAG based on file time and size
        final long time = file.lastModified();
        final long size = file.length();
        final String name = file.getName();

        etag = "w/" + HashUtils.getMD5Hex(name + ":" + size + ":" + time);
    }

    // check for if-modified-since header name
    String ifModifiedSince = request.getHeader("If-Modified-Since");
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // Only compare up to the second because the datetime format we send to the client
            // does not have milliseconds
            long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
            long fileLastModifiedSeconds = file.lastModified() / 1000;

            if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
                response.setStatus(HttpStatusCode.NOT_MODIFIED);
                return;
            }
        }
    }

    // add mime-header - based on the file extension
    response.setContentType(MimeUtils.getMimeTypeForFileExtension(FilenameUtils.getExtension(file.getName())));
    response.setDateHeader("Last-Modified", file.lastModified());

    // check for no cache
    if (this.httpdConfig.noCache) {
        response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    }

    // check for no-sniff
    if (this.httpdConfig.noSniff) {
        response.addHeader("X-Content-Type-Options", "nosniff");
    }

    // etag
    if (!this.httpdConfig.noEtag) {
        response.addHeader("Etag", etag);
    }

    // send back file contents
    response.setContentLength((int) file.length());
    IOUtils.copyLarge(FileUtils.openInputStream(file), response.getOutputStream());
}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

public InputStream getImageThumbnailInputStream(Attachment image, int width, int height) {
    try {/*from   w w w .jav  a  2s.  c om*/

        File file = getThumbnailFromCacheIfExist(image, width, height);
        return FileUtils.openInputStream(file);
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:architecture.ee.web.attachment.DefaultImageManager.java

public Image createImage(int objectType, long objectId, String name, String contentType, File file) {
    Date now = new Date();
    ImageImpl image = new ImageImpl();
    image.setCreationDate(now);/* ww  w.j av a  2 s. co m*/
    image.setModifiedDate(now);
    image.setObjectType(objectType);
    image.setObjectId(objectId);
    image.setContentType(contentType);
    image.setName(name);
    image.setImageId(-1L);

    try {
        image.setSize((int) FileUtils.sizeOf(file));
        image.setInputStream(FileUtils.openInputStream(file));
    } catch (IOException e) {
        log.debug(e);
    }
    return image;
}

From source file:at.medevit.elexis.ehc.core.internal.EhcCoreServiceImpl.java

@Override
public boolean isCdaDocument(File file) {
    if (file != null) {
        try {/*from   w  w  w  .jav  a 2  s.  com*/
            FileInputStream in = FileUtils.openInputStream(file);
            ClinicalDocument c = CDAUtil.load(in);
            IOUtils.closeQuietly(in);
            return c != null;
        } catch (Exception e) {
            /* ignore */
        }
    }
    return false;
}

From source file:edu.cornell.med.icb.goby.modes.TestReformatCompactReadsMode.java

/**
 * Validates that a subset of a compact reads file can be written.
 *
 * @throws IOException if there is a problem reading or writing to the files
 *//*from  w  w w . ja v  a  2  s  .  com*/
@Test
public void reformatSubsetOfCompactFile() throws IOException {
    final ReformatCompactReadsMode reformat = new ReformatCompactReadsMode();

    final String inputFilename = "test-data/compact-reads/s_1_sequence_short_1_per_chunk.compact-reads";
    reformat.setInputFilenames(inputFilename);
    reformat.setStartPosition(11);
    final String outputFilename = "test-results/reformat-test-subset.compact-reads";
    reformat.setOutputFile(outputFilename);
    reformat.execute();

    final File inputFile = new File(inputFilename);
    final File outputFile = new File(outputFilename);
    assertFalse("The reformatted file should not be the same as the original",
            FileUtils.contentEquals(inputFile, outputFile));

    final ReadsReader reader = new ReadsReader(FileUtils.openInputStream(outputFile));
    assertTrue("There should be reads in this file", reader.hasNext());

    int numberOfEntries = 0;
    for (final Reads.ReadEntry entry : reader) {
        assertNotNull("Entry should not be null: " + numberOfEntries, entry);
        numberOfEntries++;
    }

    // we should have skipped the first entry
    assertEquals("There should be 72 entries in the test file", 72, numberOfEntries);
}

From source file:com.iisigroup.cap.rule.handler.RuleTbMntHandler.java

@HandlerType(HandlerTypeEnum.FileDownload)
public Result dwnload(Request request) throws CapException {
    File file = createDecisionTable(request);
    FileInputStream is = null;//from ww w.  j  av a  2s  .c  om
    try {
        is = FileUtils.openInputStream(file);
        // return new FileDownloadResult(request, file.getPath(), file.getName(), "xls/plain");
        return new ByteArrayDownloadResult(request, IOUtils.toByteArray(is), "xls/plain", file.getName());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
    return new AjaxFormResult();
}