Example usage for org.springframework.core.io InputStreamSource getInputStream

List of usage examples for org.springframework.core.io InputStreamSource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io InputStreamSource getInputStream.

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream for the content of an underlying resource.

Usage

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * checks if image file is image.//  w w w. j  av  a 2s . co m
 *
 * @param item file upload item
 * @return true if file is image.
 */
public static boolean isValid(InputStreamSource item) {
    BufferedImage bi;
    try (InputStream is = item.getInputStream()) {
        bi = ImageIO.read(is);
    } catch (IOException e) {
        return false;
    }
    return bi != null;
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * Uploads image and if the image size is larger than maximum allowed it
 * resizes the image.//from  w w w.jav  a 2s  .c o  m
 *
 * @param part servlet part
 * @param file file name
 * @param fileName name of file
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 */
public static void createTmpThumb(InputStreamSource part, Path file, String fileName, CKFinderContext context)
        throws IOException {
    BufferedImage image;
    try (InputStream stream = part.getInputStream()) {
        image = ImageIO.read(stream);
        if (image == null) {
            throw new IOException("Wrong file");
        }
    }
    ImageProperties imageProperties = context.getImage();
    Dimension dimension = createThumbDimension(image, imageProperties.getMaxWidth(),
            imageProperties.getMaxHeight());
    if (dimension.width == 0 || dimension.height == 0
            || (image.getHeight() <= dimension.height && image.getWidth() <= dimension.width)) {
        try (InputStream stream = part.getInputStream()) {
            Files.copy(stream, file, StandardCopyOption.REPLACE_EXISTING);
        }
    } else {
        resizeImage(image, dimension.width, dimension.height, imageProperties.getQuality(), file);
    }
    if (log.isTraceEnabled()) {
        log.trace("thumb size: {}", Files.size(file));
    }
}

From source file:com.github.zhanhb.ckfinder.connector.utils.ImageUtils.java

/**
 * check if image size isn't bigger then biggest allowed.
 *
 * @param part servlet part/*from w  w  w  . j a  v  a 2 s.  c  o  m*/
 * @param context ckfinder context.
 * @return true if image size isn't bigger then biggest allowed.
 * @throws IOException when IO Exception occurs during reading image.
 */
public static boolean checkImageSize(InputStreamSource part, CKFinderContext context) throws IOException {
    ImageProperties image = context.getImage();
    final int maxWidth = image.getMaxWidth();
    final int maxHeight = image.getMaxHeight();
    if (maxHeight == 0 && maxWidth == 0) {
        return true;
    }
    BufferedImage bi;
    try (InputStream stream = part.getInputStream()) {
        bi = ImageIO.read(stream);
    }
    if (bi != null) {
        log.debug("image size: {} {}", bi.getWidth(), bi.getHeight());
        return (maxHeight == 0 || bi.getHeight() <= maxHeight) && (maxWidth == 0 || bi.getWidth() <= maxWidth);
    }
    return false;
}

From source file:org.haedus.io.ClassPathFileHandler.java

@Override
public List<String> readLines(String path) {

    List<String> lines = new ArrayList<String>();

    InputStreamSource resource = new ClassPathResource(path);
    try {//from   w w  w  .  j  a va 2  s  .c  o  m
        InputStream inputStream = resource.getInputStream();
        lines.addAll(IOUtils.readLines(inputStream, encoding));
        inputStream.close();
    } catch (IOException e) {
        LOGGER.error("Error when reading from path \"{}\"!", path);
    }
    return lines;
}

From source file:ru.anr.cmdline.base.plugins.CustomBannerProvider.java

/**
 * {@inheritDoc}//from www.j a va 2s. c o m
 */
@Override
public String getBanner() {

    StringBuilder sb = new StringBuilder();

    try {

        InputStreamSource iss = new ClassPathResource("welcome.text.txt");
        sb.append(FileUtils.readBanner(new InputStreamReader(iss.getInputStream())));

    } catch (IOException ex) {
        logger.info("File 'welcome.text.txt' not found in classpath");
    }

    sb.append(OsUtils.LINE_SEPARATOR);
    return sb.toString();
}

From source file:com.github.zhanhb.ckfinder.connector.plugins.WatermarkProcessor.java

/**
 * Extracts image location from settings or uses default image if none is
 * provided./*w ww . j  a va2s . c  o m*/
 *
 * @param settings
 * @return the parameter
 * @throws IOException when IO Exception occurs.
 */
private BufferedImage getWatermarkImage(WatermarkSettings settings) throws IOException {
    final InputStreamSource source = settings.getSource();
    if (source == null) {
        return null;
    }
    try (InputStream is = source.getInputStream()) {
        return is == null ? null : ImageIO.read(is);
    }

}

From source file:org.mitre.mpf.wfm.pipeline.PipelineManager.java

private <T> T fromXStream(InputStreamSource resource, Class<T> type) throws IOException {
    try (InputStream inputStream = resource.getInputStream()) {
        Object obj = xStream.fromXML(inputStream);
        if (type.isInstance(obj)) {
            //noinspection unchecked
            return (T) obj;
        } else {//  w  ww.  jav a  2  s .  c om
            throw new IllegalArgumentException(String.format("Expected type to be %s but was %s",
                    type.getCanonicalName(), obj.getClass().getCanonicalName()));
        }
    }
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

private static void copyResource(WritableResource target, InputStreamSource source) throws IOException {
    createParentDir(target);/*from  w ww . j  ava2s.c o  m*/
    try (InputStream inStream = source.getInputStream(); OutputStream outStream = target.getOutputStream()) {
        IOUtils.copy(inStream, outStream);
    }
}

From source file:us.fatehi.schemacrawler.webapp.SchemaCrawlerControllerHappyPathTest.java

@Test
public void happyPath() throws Exception {
    final InputStreamSource testDbStreamSource = new ClassPathResource("/test.db");
    final MockMultipartFile multipartFile = new MockMultipartFile("file", "test.db", "application/octet-stream",
            testDbStreamSource.getInputStream());

    final MvcResult result1 = mvc
            .perform(fileUpload("/schemacrawler").file(multipartFile).param("name", "Sualeh").param("email",
                    "sualeh@hotmail.com"))
            .andExpect(view().name("SchemaCrawlerDiagramResult")).andExpect(status().is2xxSuccessful())
            .andReturn();//from  www.java2  s .c om

    final SchemaCrawlerDiagramRequest diagramRequest = (SchemaCrawlerDiagramRequest) result1.getModelAndView()
            .getModel().get("diagramRequest");
    final String key = diagramRequest.getKey();

    final Optional<Path> sqlitePathOptional = storageService.resolve(key, FileExtensionType.SQLITE_DB);
    assertThat(sqlitePathOptional.isPresent(), is(equalTo(true)));
    final Optional<Path> pngPathOptional = storageService.resolve(key, FileExtensionType.PNG);
    assertThat(pngPathOptional.isPresent(), is(equalTo(true)));
    final Optional<Path> jsonPathOptional = storageService.resolve(key, FileExtensionType.JSON);
    assertThat(jsonPathOptional.isPresent(), is(equalTo(true)));

    final SchemaCrawlerDiagramRequest schemaCrawlerDiagramRequestFromJson = SchemaCrawlerDiagramRequest
            .fromJson(IOUtils.toString(new FileReader(jsonPathOptional.get().toFile())));
    assertThat(diagramRequest, is(equalTo(schemaCrawlerDiagramRequestFromJson)));

    final MvcResult result2 = mvc.perform(get("/schemacrawler/" + key))
            .andExpect(view().name("SchemaCrawlerDiagram")).andExpect(status().is2xxSuccessful()).andReturn();
    assertThat(result2.getResponse().getContentAsString(), containsString("/schemacrawler/images/" + key));

    final MvcResult result3 = mvc.perform(get("/schemacrawler/images/" + key).accept(MediaType.IMAGE_PNG))
            .andExpect(status().isOk()).andReturn();
    final int contentLength = result3.getResponse().getContentLength();
    assertThat(contentLength, is(greaterThan(0)));
    // assertThat(contentLength, is(greaterThan(14_500)));
    // assertThat(contentLength, is(lessThan(15_500)));

}

From source file:us.fatehi.schemacrawler.webapp.service.storage.FileSystemStorageService.java

/**
 * {@inheritDoc}//ww w .  j a  va2  s  .c  o m
 */
@Override
public void store(final InputStreamSource streamSource, final String filenameKey,
        final FileExtensionType extension) throws Exception {
    validateFilenameKey(filenameKey);
    if (streamSource == null || extension == null) {
        throw new Exception(String.format("Failed to store file %s%s", filenameKey, extension));
    }

    // Save stream to a file
    final Path filePath = storageRoot.resolve(filenameKey + "." + extension.getExtension());
    copy(streamSource.getInputStream(), filePath);

    // Check that the file is not empty
    if (Files.size(filePath) == 0) {
        Files.delete(filePath);
        throw new Exception(String.format("No data for file %s.%s", filenameKey, extension));
    }
}