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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopySourceDoesNotExist() throws Exception {
    exception.expect(FileOperationException.class);
    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/unknown.file"));
    when(aFileResource1.exists()).thenReturn(false);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-unknown.file"));
    when(aDestResource.exists()).thenReturn(false);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    assertFalse(aDestResource.getFile().exists());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();/*from w  ww. j  a  v  a2  s.  c  o  m*/
    aTasklet.execute(null, null);
}

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopyRecursiveDirectory() throws Exception {
    FileUtils.forceMkdir(new File("target/CP-testfiles/source/subdir"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/CP-testfiles/source/CP0-input.csv"));
    FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"),
            new File("target/CP-testfiles/source/subdir/CP1-input.csv"));

    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("target/CP-testfiles/source/"));
    when(aFileResource1.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-testfiles/destination/"));
    when(aDestResource.exists()).thenReturn(false);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target/CP-testfiles/destination/"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    assertFalse(aDestResource.getFile().exists());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.setRecursive(true);/* w  w  w .  j av a2 s . co  m*/
    aTasklet.afterPropertiesSet();
    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);
    assertTrue(aDestResource.getFile().exists());
    assertEquals(2, aDestResource.getFile().list().length);
    assertArrayEquals(aFileResource1.getFile().list(), aDestResource.getFile().list());
    assertArrayEquals(aFileResource1.getFile().listFiles()[0].list(),
            aDestResource.getFile().listFiles()[0].list());
}

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopyReplace() throws Exception {
    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/input.csv"));
    when(aFileResource1.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-input.csv"));
    when(aDestResource.exists()).thenReturn(true);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target/"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    FileUtils.copyFile(aFileResource1.getFile(), aDestResource.getFile());
    assertTrue(aDestResource.getFile().exists());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();//from   w  ww  .  j  ava  2s.  c  om
    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);
    assertTrue(aDestResource.getFile().exists());
}

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopyWithChunkContext() throws Exception {
    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/input.csv"));
    when(aFileResource1.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-input.csv"));
    when(aDestResource.exists()).thenReturn(false);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    assertFalse(aDestResource.getFile().exists());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();/* ww w  .j  a va 2  s  .  c om*/
    ChunkContext aChunkContext = mock(ChunkContext.class);
    StepContext aStepContext = mock(StepContext.class);
    when(aChunkContext.getStepContext()).thenReturn(aStepContext);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(null, aChunkContext));
    verify(aChunkContext, times(2)).getStepContext();
    verify(aStepContext, times(1)).getStepExecution();
    assertTrue(aDestResource.getFile().exists());
}

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopyFileToExistingDir() throws Exception {
    FileUtils.forceMkdir(new File("target/CP-testfiles"));
    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/input.csv"));
    when(aFileResource1.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource = mock(Resource.class);
    when(aDestResource.getFile()).thenReturn(new File("target/CP-testfiles/"));
    when(aDestResource.exists()).thenReturn(true);
    Resource aRelativeResource = mock(Resource.class);
    when(aRelativeResource.getFile()).thenReturn(new File("target/CP-testfiles/"));
    when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource);
    assertTrue(aDestResource.getFile().exists());
    assertTrue(aDestResource.getFile().isDirectory());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();/*from w w w .  ja  v  a 2  s . c  om*/
    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(1)).incrementReadCount();
    verify(aStepContribution, times(1)).incrementWriteCount(1);
    assertTrue(aDestResource.getFile().exists());
    assertTrue(aDestResource.getFile().isDirectory());
    assertEquals(1, aDestResource.getFile().list().length);
}

From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java

@Test
public void testExecuteCopyTwoFiles() throws Exception {
    FilesOperationTasklet aTasklet = new FilesOperationTasklet();
    ResourcesFactory aSourceFactory = mock(ResourcesFactory.class);
    Resource aFileResource1 = mock(Resource.class);
    when(aFileResource1.getFile()).thenReturn(new File("src/test/resources/testFiles/input.csv"));
    when(aFileResource1.exists()).thenReturn(true);
    Resource aFileResource2 = mock(Resource.class);
    when(aFileResource2.getFile()).thenReturn(new File("src/test/resources/testFiles/input1000.csv"));
    when(aFileResource2.exists()).thenReturn(true);
    when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class)))
            .thenReturn(new Resource[] { aFileResource1, aFileResource2 });
    ResourceFactory aDestinationFactory = mock(ResourceFactory.class);
    Resource aDestResource1 = mock(Resource.class);
    when(aDestResource1.getFile()).thenReturn(new File("target/CP-input.csv"));
    when(aDestResource1.exists()).thenReturn(false);
    Resource aRelativeResource1 = mock(Resource.class);
    when(aRelativeResource1.getFile()).thenReturn(new File("target"));
    when(aDestResource1.createRelative("/.")).thenReturn(aRelativeResource1);
    Resource aDestResource2 = mock(Resource.class);
    when(aDestResource2.getFile()).thenReturn(new File("target/CP-input1000.csv"));
    when(aDestResource2.exists()).thenReturn(false);
    Resource aRelativeResource2 = mock(Resource.class);
    when(aRelativeResource2.getFile()).thenReturn(new File("target"));
    when(aDestResource2.createRelative("/.")).thenReturn(aRelativeResource2);
    when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource1,
            aDestResource2);/*ww w .  j a  v a  2  s . com*/
    assertFalse(aDestResource1.getFile().exists());
    assertFalse(aDestResource2.getFile().exists());
    aTasklet.setSourceFactory(aSourceFactory);
    aTasklet.setDestinationFactory(aDestinationFactory);
    aTasklet.setOperation(Operation.COPY);
    aTasklet.afterPropertiesSet();
    StepContribution aStepContribution = mock(StepContribution.class);
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null));
    verify(aStepContribution, times(2)).incrementReadCount();
    verify(aStepContribution, times(2)).incrementWriteCount(1);
    assertTrue(aDestResource1.getFile().exists());
    assertTrue(aDestResource2.getFile().exists());
}

From source file:com.agiletec.apsadmin.portal.WidgetTypeAction.java

private boolean checkGui() throws Throwable {
    if (this.getStrutsAction() == NEW_USER_WIDGET || this.getStrutsAction() == ApsAdminSystemConstants.PASTE) {
        return true;
    }/*w  w  w .  j a  v  a2s  . c  o  m*/
    boolean isValuedGui = StringUtils.isNotBlank(this.getGui());
    if (this.getStrutsAction() == ApsAdminSystemConstants.ADD) {
        return isValuedGui;
    }
    if (this.getStrutsAction() != ApsAdminSystemConstants.EDIT) {
        throw new RuntimeException("Invalid Struts Action " + this.getStrutsAction());
    }
    WidgetType type = this.getWidgetType(this.getWidgetTypeCode());
    if (type.isLogic() || this.isInternalServletWidget(this.getWidgetTypeCode())) {
        return true;
    }
    String pluginCode = type.getPluginCode();
    String jspPath = WidgetType.getJspPath(this.getWidgetTypeCode(), pluginCode);
    String folderPath = this.getRequest().getSession().getServletContext().getRealPath("/");
    boolean existsJsp = (new File(folderPath + jspPath)).exists();
    if (existsJsp) {
        return true;
    }
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource[] resources = resolver.getResources("file:**" + jspPath);
    for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        if (resource.exists()) {
            return true;
        }
    }
    GuiFragment guiFragment = this.extractUniqueGuiFragment(this.getWidgetTypeCode());
    if (!isValuedGui && (guiFragment == null || StringUtils.isBlank(guiFragment.getDefaultGui()))) {
        return false;
    } else {
        return true;
    }
}

From source file:it.geosolutions.httpproxy.service.impl.ProxyConfigImpl.java

/**
 * Reload proxy configuration reading {@link ProxyConfigImpl#locations}
 */// ww w  .j  a  v a 2 s .co  m
public void reloadProxyConfig() {
    if (locations != null) {
        for (Resource location : locations) {
            try {
                if (location.exists()) {
                    trackLocation(location);
                } else {
                    // Try to load from file system:
                    String path = null;
                    if (location instanceof ClassPathResource) {
                        // This instance is running without web context
                        path = ((ClassPathResource) location).getPath();
                    } else if (location instanceof ServletContextResource) {
                        // This instance is running in a web context
                        path = ((ServletContextResource) location).getPath();
                    }
                    if (path != null) {
                        Resource alternative = new UrlResource("file:/" + path);
                        if (alternative.exists()) {
                            trackLocation(alternative);
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Error overriding the proxy configuration ", e);
            }
        }
    } else {
        LOGGER.log(Level.SEVERE, "Can't observe locations for proxy configuration");
    }
}

From source file:org.parancoe.web.util.ReloadableResourceBundleMessageSource.java

/**
 * Refresh the PropertiesHolder for the given bundle filename. The holder can be
 * <code>null</code> if not cached before, or a timed-out cache entry (potentially getting
 * re-validated against the current last-modified timestamp).
 *
 * @param filename the bundle filename (basename + Locale)
 * @param propHolder the current PropertiesHolder for the bundle
 */// www.j a v  a  2 s . c om
protected ReloadableResourceBundleMessageSource.PropertiesHolder refreshProperties(String filename,
        ReloadableResourceBundleMessageSource.PropertiesHolder propHolder) {
    long refreshTimestamp = (this.cacheMillis < 0) ? -1 : System.currentTimeMillis();

    Resource[] resources = null;
    try {
        if (this.resourceLoader instanceof ResourcePatternResolver) {
            resources = ((ResourcePatternResolver) this.resourceLoader)
                    .getResources(filename + PROPERTIES_SUFFIX);
            if (resources == null || resources.length == 0) {
                resources = ((ResourcePatternResolver) this.resourceLoader).getResources(filename + XML_SUFFIX);
            }
        } else {
            Resource resource = this.resourceLoader.getResource(filename + PROPERTIES_SUFFIX);
            if (!resource.exists()) {
                resource = this.resourceLoader.getResource(filename + XML_SUFFIX);
            }
            resources = new Resource[1];
            resources[0] = resource;
        }
        if (resources != null && resources.length > 0) {
            propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
            for (Resource resource : resources) {
                if (resource.exists()) {
                    long fileTimestamp = -1;
                    if (this.cacheMillis >= 0) {
                        // Last-modified timestamp of file will just be read if caching with timeout.
                        try {
                            fileTimestamp = resource.lastModified();
                            if (propHolder != null && propHolder.getFileTimestamp() == fileTimestamp) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Re-caching properties for filename [" + filename
                                            + "] - file hasn't been modified");
                                }
                                propHolder.setRefreshTimestamp(refreshTimestamp);
                                return propHolder;
                            }
                        } catch (IOException ex) {
                            // Probably a class path resource: cache it forever.
                            if (logger.isDebugEnabled()) {
                                logger.debug(resource
                                        + " could not be resolved in the file system - assuming that is hasn't changed",
                                        ex);
                            }
                            fileTimestamp = -1;
                        }
                    }
                    try {
                        Properties props = loadProperties(resource, filename);
                        if (propHolder.getProperties() != null) {
                            propHolder.getProperties().putAll(props);
                        } else {
                            propHolder.properties = props;
                        }
                        propHolder.fileTimestamp = fileTimestamp;
                    } catch (IOException ex) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Could not parse properties file [" + resource.getFilename() + "]", ex);
                        }
                    }
                } else {
                    // Resource does not exist.
                    if (logger.isDebugEnabled()) {
                        logger.debug("No properties file found for [" + resource.getFilename()
                                + "] - neither plain properties nor XML");
                    }
                }
            }
        } else {
            // Resource does not exist.
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "No properties files found for [" + filename + "] - neither plain properties nor XML");
            }
            // Empty holder representing "not found".
            propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
        }
    } catch (IOException iOException) {
        if (logger.isWarnEnabled()) {
            logger.warn("Could not match pattern [" + filename + "]", iOException);
        }
        // Empty holder representing "not valid".
        propHolder = new ReloadableResourceBundleMessageSource.PropertiesHolder();
    }

    propHolder.setRefreshTimestamp(refreshTimestamp);
    this.cachedProperties.put(filename, propHolder);
    return propHolder;
}

From source file:fr.acxio.tools.agia.file.pdf.SplitPDFTasklet.java

private int splitFile(Resource sSourceResource, ChunkContext sChunkContext) throws Exception {
    Map<String, Object> aDestinationParams = new HashMap<String, Object>();
    aDestinationParams.put(ResourceFactoryConstants.PARAM_SOURCE, sSourceResource);
    aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC,
            ((sChunkContext != null) && (sChunkContext.getStepContext() != null))
                    ? sChunkContext.getStepContext().getStepExecution()
                    : null);// w  ww . j  av  a 2 s . co m
    Resource aDestination = null;
    int aResult = 0;

    PDDocumentContainer aDocumentContainer = null;

    try {
        aDocumentContainer = documentFactory.getDocument(sSourceResource.getFile());
        List<PDDocument> documents = aDocumentContainer.getParts();

        for (int i = 0; i < documents.size(); i++) {
            PDDocument doc = documents.get(i);
            // Output file factory
            int aTryCount = 10;
            do {
                aDestination = destinationFactory.getResource(aDestinationParams);
                aTryCount--;
            } while (!forceReplace && (aTryCount > 0) && (aDestination != null) && aDestination.exists());
            if ((aTryCount == 0) && !forceReplace) {
                throw new SplitPDFException("Cannot create a new destination filename");
            }
            if (aDestination != null) {
                if (aDestination.exists() && LOGGER.isWarnEnabled()) {
                    LOGGER.warn("Replacing {}", aDestination.getFile().getAbsolutePath());
                }
                writeDocument(doc, aDestination.getFile().getAbsolutePath());
                doc.close();
            } else {
                throw new SplitPDFException("No destination specified");
            }
            aResult++;
        }

    } finally {
        if (aDocumentContainer != null) {
            aDocumentContainer.close();
        }
    }
    return aResult;
}