Java Code Examples for org.springframework.core.io.Resource#exists()

The following examples show how to use org.springframework.core.io.Resource#exists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileUtils.java    From casbin-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public InputStream getFileAsInputStream(String filePath) {
    File file = getFile(filePath);
    try {
        if (file != null && file.exists()) {
            return new FileInputStream(file);
        }
        Resource resource = new DefaultResourceLoader().getResource(filePath);
        if (resource.exists()) {
            return resource.getInputStream();
        }
        return null;
    } catch (Exception e) {
        logger.error("load file $filePath by inputStream error", e);
        return null;
    }
}
 
Example 2
Source File: MockServletContext.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public InputStream getResourceAsStream(String path) {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	if (!resource.exists()) {
		return null;
	}
	try {
		return resource.getInputStream();
	}
	catch (IOException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Could not open InputStream for " + resource, ex);
		}
		return null;
	}
}
 
Example 3
Source File: ConsoleLog.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Load and print the Spring banner (if one is configured) to UserConsole.
 *
 * @param environment the Spring environment
 */
public static void printBanner(final Environment environment) {
    try {
        final String bannerLocation = environment.getProperty(BANNER_LOCATION_SPRING_PROPERTY_KEY);
        if (StringUtils.isNotBlank(bannerLocation)) {
            final ResourceLoader resourceLoader = new DefaultResourceLoader();
            final Resource resource = resourceLoader.getResource(bannerLocation);
            if (resource.exists()) {
                final String banner = StreamUtils.copyToString(
                    resource.getInputStream(),
                    environment.getProperty(
                        BANNER_CHARSET_SPRING_PROPERTY_KEY,
                        Charset.class,
                        StandardCharsets.UTF_8
                    )
                );
                ConsoleLog.getLogger().info(banner);
            }
        }
    } catch (final Throwable t) {
        log.error("Failed to print banner", t);
    }
}
 
Example 4
Source File: DefaultModuleDefinition.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
protected void checkNameMatchesSelf() throws IOException {
    String expectedLocation = ModuleLocationUtils.getModuleLocation(baseDir, name);
    Resource self = resolver.getResource(expectedLocation);

    if (!self.exists()) {
        throw new IOException("Resource [" + location() + "] is expected to exist at [" + expectedLocation + "] please ensure the name property is correct");
    }

    String moduleUrl = moduleProperties.getURL().toExternalForm();
    String selfUrl = self.getURL().toExternalForm();

    if (!moduleUrl.equals(selfUrl)) {
        throw new IOException("Resource [" + location() + "] and [" + self.getURL() + "] do not appear to be the same resource, " +
            "please ensure the name property is correct or that the " + "module is not defined twice");
    }
}
 
Example 5
Source File: ElementSteps.java    From vividus with Apache License 2.0 6 votes vote down vote up
/**
 * This step uploads a file with the given relative path
 * <p>A <b>relative path</b> starts from some given working directory,
 * avoiding the need to provide the full absolute path
 * (i.e. <i>'about.jpeg'</i> is in the root directory
 * or <i>'/story/uploadfiles/about.png'</i>)</p>
 * @param locator The locator for the upload element
 * @param filePath relative path to the file to be uploaded
 * @see <a href="https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths"> <i>Absolute and
 * relative paths</i></a>
 * @throws IOException If an input or output exception occurred
 */
@When("I select element located `$locator` and upload file `$filePath`")
public void uploadFile(SearchAttributes locator, String filePath) throws IOException
{
    Resource resource = resourceLoader.getResource(ResourceLoader.CLASSPATH_URL_PREFIX + filePath);
    if (!resource.exists())
    {
        resource = resourceLoader.getResource(ResourceUtils.FILE_URL_PREFIX + filePath);
    }
    File fileForUpload = ResourceUtils.isFileURL(resource.getURL()) ? resource.getFile()
            : unpackFile(resource, filePath);
    if (highlightingSoftAssert.assertTrue("File " + filePath + " exists", fileForUpload.exists()))
    {
        String fullFilePath = fileForUpload.getAbsolutePath();
        if (isRemoteExecution())
        {
            webDriverProvider.getUnwrapped(RemoteWebDriver.class).setFileDetector(new LocalFileDetector());
        }
        locator.getSearchParameters().setVisibility(Visibility.ALL);
        WebElement browse = baseValidations.assertIfElementExists(AN_ELEMENT, locator);
        if (browse != null)
        {
            browse.sendKeys(fullFilePath);
        }
    }
}
 
Example 6
Source File: DefaultPersistenceUnitManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine JPA's default "META-INF/orm.xml" resource for use with Spring's default
 * persistence unit, if any.
 * <p>Checks whether a "META-INF/orm.xml" file exists in the classpath and uses it
 * if it is not co-located with a "META-INF/persistence.xml" file.
 */
@Nullable
private Resource getOrmXmlForDefaultPersistenceUnit() {
	Resource ormXml = this.resourcePatternResolver.getResource(
			this.defaultPersistenceUnitRootLocation + DEFAULT_ORM_XML_RESOURCE);
	if (ormXml.exists()) {
		try {
			Resource persistenceXml = ormXml.createRelative(PERSISTENCE_XML_FILENAME);
			if (!persistenceXml.exists()) {
				return ormXml;
			}
		}
		catch (IOException ex) {
			// Cannot resolve relative persistence.xml file - let's assume it's not there.
			return ormXml;
		}
	}
	return null;
}
 
Example 7
Source File: MockServletContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public InputStream getResourceAsStream(String path) {
	Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
	if (!resource.exists()) {
		return null;
	}
	try {
		return resource.getInputStream();
	}
	catch (IOException ex) {
		if (logger.isWarnEnabled()) {
			logger.warn("Could not open InputStream for " + resource, ex);
		}
		return null;
	}
}
 
Example 8
Source File: WebExternalUIComponentsSource.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void _registerAppComponents() {
    String configNames = AppContext.getProperty(WEB_COMPONENTS_CONFIG_XML_PROP);

    if (Strings.isNullOrEmpty(configNames)) {
        return;
    }

    log.debug("Loading UI components from {}", configNames);

    StringTokenizer tokenizer = new StringTokenizer(configNames);
    for (String location : tokenizer.getTokenArray()) {
        Resource resource = resources.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                _registerComponent(stream);
            } catch (ClassNotFoundException | IOException e) {
                throw new RuntimeException("Unable to load components config " + location, e);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        } else {
            log.warn("Resource {} not found, ignore it", location);
        }
    }
}
 
Example 9
Source File: SchemaBootstrap.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Collate differences and validation problems with the schema with respect to an appropriate
 * reference schema.
 * 
 * @param outputFileNameTemplate String
 * @param out PrintWriter
 * @return the number of potential problems found.
 */
public synchronized int validateSchema(String outputFileNameTemplate, PrintWriter out)
{
    int totalProblems = 0;
    
    // Discover available reference files (e.g. for prefixes alf_, etc.)
    // and process each in turn.
    for (String schemaReferenceUrl : schemaReferenceUrls)
    {
        Resource referenceResource = DialectUtil.getDialectResource(rpr, dialect.getClass(), schemaReferenceUrl);
        
        if (referenceResource == null || !referenceResource.exists())
        {
            String resourceUrl = DialectUtil.resolveDialectUrl(dialect.getClass(), schemaReferenceUrl);
            LogUtil.debug(logger, DEBUG_SCHEMA_COMP_NO_REF_FILE, resourceUrl);
        }
        else
        {
            // Validate schema against each reference file
            int problems = validateSchema(referenceResource, outputFileNameTemplate, out);
            totalProblems += problems;
        }
    }
    
    // Return number of problems found across all reference files.
    return totalProblems;
}
 
Example 10
Source File: SQLErrorCodesFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new instance of the {@link SQLErrorCodesFactory} class.
 * <p>Not public to enforce Singleton design pattern. Would be private
 * except to allow testing via overriding the
 * {@link #loadResource(String)} method.
 * <p><b>Do not subclass in application code.</b>
 * @see #loadResource(String)
 */
protected SQLErrorCodesFactory() {
	Map<String, SQLErrorCodes> errorCodes;

	try {
		DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
		lbf.setBeanClassLoader(getClass().getClassLoader());
		XmlBeanDefinitionReader bdr = new XmlBeanDefinitionReader(lbf);

		// Load default SQL error codes.
		Resource resource = loadResource(SQL_ERROR_CODE_DEFAULT_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
		}
		else {
			logger.info("Default sql-error-codes.xml not found (should be included in spring-jdbc jar)");
		}

		// Load custom SQL error codes, overriding defaults.
		resource = loadResource(SQL_ERROR_CODE_OVERRIDE_PATH);
		if (resource != null && resource.exists()) {
			bdr.loadBeanDefinitions(resource);
			logger.debug("Found custom sql-error-codes.xml file at the root of the classpath");
		}

		// Check all beans of type SQLErrorCodes.
		errorCodes = lbf.getBeansOfType(SQLErrorCodes.class, true, false);
		if (logger.isTraceEnabled()) {
			logger.trace("SQLErrorCodes loaded: " + errorCodes.keySet());
		}
	}
	catch (BeansException ex) {
		logger.warn("Error loading SQL error codes from config file", ex);
		errorCodes = Collections.emptyMap();
	}

	this.errorCodesMap = errorCodes;
}
 
Example 11
Source File: EncodedResourceResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Resource resolveResourceInternal(@Nullable HttpServletRequest request, String requestPath,
		List<? extends Resource> locations, ResourceResolverChain chain) {

	Resource resource = chain.resolveResource(request, requestPath, locations);
	if (resource == null || request == null) {
		return resource;
	}

	String acceptEncoding = getAcceptEncoding(request);
	if (acceptEncoding == null) {
		return resource;
	}

	for (String coding : this.contentCodings) {
		if (acceptEncoding.contains(coding)) {
			try {
				String extension = getExtension(coding);
				Resource encoded = new EncodedResource(resource, coding, extension);
				if (encoded.exists()) {
					return encoded;
				}
			}
			catch (IOException ex) {
				if (logger.isTraceEnabled()) {
					logger.trace("No " + coding + " resource for [" + resource.getFilename() + "]", ex);
				}
			}
		}
	}

	return resource;
}
 
Example 12
Source File: CommonsFileUploadSupport.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Set the temporary directory where uploaded files get stored.
 * Default is the servlet container's temporary directory for the web application.
 * @see org.springframework.web.util.WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE
 */
public void setUploadTempDir(Resource uploadTempDir) throws IOException {
	if (!uploadTempDir.exists() && !uploadTempDir.getFile().mkdirs()) {
		throw new IllegalArgumentException("Given uploadTempDir [" + uploadTempDir + "] could not be created");
	}
	this.fileItemFactory.setRepository(uploadTempDir.getFile());
	this.uploadTempDirSpecified = true;
}
 
Example 13
Source File: DefaultEnvironmentPostProcessor.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
private static void contributeDefaults(Map<String, Object> defaults, Resource resource) {
	if (resource.exists()) {
		YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
		yamlPropertiesFactoryBean.setResources(resource);
		yamlPropertiesFactoryBean.afterPropertiesSet();
		Properties p = yamlPropertiesFactoryBean.getObject();
		for (Object k : p.keySet()) {
			String key = k.toString();
			defaults.put(key, p.get(key));
		}
	}
}
 
Example 14
Source File: LocalStorage.java    From mall with MIT License 5 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            return null;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 15
Source File: ResourceWithFallbackLoader.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Resource getResource(final String location) {
    Resource resource = resolver.getResource(primary + location);
    if (!resource.exists()) {
        resource = resolver.getResource(fallback + location);
    }

    return resource;
}
 
Example 16
Source File: ScriptTemplateView.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
protected Resource getResource(String location) {
	if (this.resourceLoaderPaths != null) {
		for (String path : this.resourceLoaderPaths) {
			Resource resource = obtainApplicationContext().getResource(path + location);
			if (resource.exists()) {
				return resource;
			}
		}
	}
	return null;
}
 
Example 17
Source File: License.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @return The full OLAT licencse as a string
 */
public static String getOlatLicense() {
    Resource license = new ClassPathResource("NOTICE.TXT");
    String licenseS = "";
    if (license.exists()) {
        licenseS = FileUtils.load(license, "UTF-8");
    }
    Resource copyLicense = new ClassPathResource("COPYING");
    String copyLicenseS = "";
    if (copyLicense.exists()) {
        copyLicenseS = FileUtils.load(copyLicense, "UTF-8");
    }
    return licenseS + "<br /><br />" + copyLicenseS;
}
 
Example 18
Source File: ResourceFinder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private static List<Resource> makeResources(List<String> paths) {
   List<Resource> rs = new ArrayList<Resource>();
   if (paths != null && !paths.isEmpty()) {
      ClassLoader cl = ResourceFinder.class.getClassLoader();
      for (String path : paths) {
         Resource r = new ClassPathResource(path, cl);
         if (r.exists()) {
            rs.add(r);
         }
      }
   }
   return rs;
}
 
Example 19
Source File: AbstractDeployerStateMachine.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(StateContext<String, String> context) {
	Resource artifact = (Resource) context.getMessageHeader(HEADER_ARTIFACT);
	String artifactDir = (String) context.getMessageHeader(HEADER_ARTIFACT_DIR);
	if (!isHdfsResource(artifact)) {
		yarnCloudAppService.pushArtifact(artifact, artifactDir);
	} else {
		if (!artifact.exists()) {
			context.getExtendedState().getVariables().put(VAR_ERROR, new RuntimeException("hdfs artifact missing"));
		}
	}
}
 
Example 20
Source File: PackageMetadataService.java    From spring-cloud-skipper with Apache License 2.0 4 votes vote down vote up
/**
 * Download package metadata from all repositories.
 * @return A list of package metadata, not yet persisted in the PackageMetadataRepository.
 */
@Transactional
public List<PackageMetadata> downloadPackageMetadata() {
	List<PackageMetadata> finalMetadataList = new ArrayList<>();
	Path targetPath = null;
	try {
		targetPath = TempFileUtils.createTempDirectory("skipperIndex");
		for (Repository packageRepository : this.repositoryRepository.findAll()) {
			try {
				if (!packageRepository.isLocal()) {
					Resource resource = resourceLoader.getResource(packageRepository.getUrl()
							+ "/index.yml");
					if (resource.exists()) {
						logger.info("Downloading package metadata from " + resource);
						File downloadedFile = new File(targetPath.toFile(), computeFilename(resource));
						StreamUtils.copy(resource.getInputStream(), new FileOutputStream(downloadedFile));
						List<File> downloadedFileAsList = new ArrayList<>();
						downloadedFileAsList.add(downloadedFile);
						List<PackageMetadata> downloadedPackageMetadata = deserializeFromIndexFiles(
								downloadedFileAsList);
						for (PackageMetadata packageMetadata : downloadedPackageMetadata) {
							packageMetadata.setRepositoryId(packageRepository.getId());
							packageMetadata.setRepositoryName(packageRepository.getName());
						}
						finalMetadataList.addAll(downloadedPackageMetadata);
					}
					else {
						logger.info("Package metadata index resource does not exist: "
								+ resource.getDescription());
					}
				}
			}
			catch (Exception e) {
				logger.warn("Could not process package file from " + packageRepository.getName(), e.getMessage());
			}
		}
	}
	finally {
		if (targetPath != null && !FileSystemUtils.deleteRecursively(targetPath.toFile())) {
			logger.warn("Temporary directory can not be deleted: " + targetPath);
		}
	}
	return finalMetadataList;
}