下面列出了org.springframework.core.io.ClassPathResource#exists ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Detect a default properties file for the supplied class, as specified
* in the class-level Javadoc for {@link TestPropertySource}.
*/
private static String detectDefaultPropertiesFile(Class<?> testClass) {
String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
prefixedResourcePath, testClass.getName()));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default properties file for test [%s]: " +
"%s does not exist. Either declare the 'locations' or 'properties' attributes " +
"of @TestPropertySource or make the default properties file available.", testClass.getName(),
classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
/**
* complie the report template xml file into a Jasper report file if the compiled file does not exist or is out of update
*
* @param template the name of the template file, without an extension
* @return an input stream where the intermediary report was written
*/
protected File compileReportTemplate(String template) throws JRException, IOException {
ClassPathResource designTemplateResource = new ClassPathResource(template);
if (!designTemplateResource.exists()) {
throw new RuntimeException("The design template file does not exist: "+template);
}
File tempJasperDir = new File(System.getProperty("java.io.tmpdir")+File.separator+template.replaceAll("\\/[^\\/]+$", ""));
if (!tempJasperDir.exists()) {
FileUtils.forceMkdir(tempJasperDir);
}
File tempJasperFile = new File(System.getProperty("java.io.tmpdir")+File.separator+template.replace(ReportGeneration.DESIGN_FILE_EXTENSION,"").concat(ReportGeneration.JASPER_REPORT_EXTENSION));
if (!tempJasperFile.exists()) {
JasperCompileManager.compileReportToStream(designTemplateResource.getInputStream(), new FileOutputStream(tempJasperFile));
}
return tempJasperFile;
}
/**
* Detect a default properties file for the supplied class, as specified
* in the class-level Javadoc for {@link TestPropertySource}.
*/
private static String detectDefaultPropertiesFile(Class<?> testClass) {
String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
prefixedResourcePath, testClass.getName()));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default properties file for test [%s]: " +
"%s does not exist. Either declare the 'locations' or 'properties' attributes " +
"of @TestPropertySource or make the default properties file available.", testClass.getName(),
classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
/**
* 加载文件后替换头和尾并解密
*
* @return 文件字节
*/
private byte[] replaceAndBase64Decode(
final String filePath, final String headReplace, final String tailReplace) throws Exception {
// 从 classpath:resources/ 中加载资源
final ClassPathResource resource = new ClassPathResource(filePath);
if (!resource.exists()) {
throw new Exception("公私钥文件找不到");
}
final byte[] keyBytes = new byte[(int) resource.getFile().length()];
final FileInputStream in = new FileInputStream(resource.getFile());
in.read(keyBytes);
in.close();
final String keyPEM =
new String(keyBytes).replace(headReplace, "").trim().replace(tailReplace, "").trim();
return Base64.decodeBase64(keyPEM);
}
/**
* Detect a default properties file for the supplied class, as specified
* in the class-level Javadoc for {@link TestPropertySource}.
*/
private static String detectDefaultPropertiesFile(Class<?> testClass) {
String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
prefixedResourcePath, testClass.getName()));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default properties file for test [%s]: "
+ "%s does not exist. Either declare the 'locations' or 'properties' attributes "
+ "of @TestPropertySource or make the default properties file available.", testClass.getName(),
classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
@Override
public void init() {
String file = getInitParameter("log4j-init-file");
ClassPathResource res = new ClassPathResource(file);
if (!res.exists()) {
// creating basic log4j configuration which writes to console out, Only called when not yet configured
ConsoleAppender appender = new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %5p %c{1}:%L - %m%n"), ConsoleAppender.SYSTEM_OUT);
appender.setThreshold(Level.INFO);
BasicConfigurator.configure(appender);
log.info("*****************************************************************************************");
log.info("You don't provide a log4j config file for your OLAT instance. OLAT will just log to standard out (e.g. catalina.out)."
+ " Please provide a proper log config file (log4j.xml, see olat/conf for an example or read the installation guide) "
+ "and place it into the root of the classpath e.g. tomcat/lib or WEB-INF/classes");
log.info("*****************************************************************************************");
}
}
@Override
public void init() {
String file = getInitParameter("log4j-init-file");
ClassPathResource res = new ClassPathResource(file);
if (!res.exists()) {
// creating basic log4j configuration which writes to console out, Only called when not yet configured
ConsoleAppender appender = new ConsoleAppender(new PatternLayout("%d{ABSOLUTE} %5p %c{1}:%L - %m%n"), ConsoleAppender.SYSTEM_OUT);
appender.setThreshold(Level.INFO);
BasicConfigurator.configure(appender);
log.info("*****************************************************************************************");
log.info("You don't provide a log4j config file for your OLAT instance. OLAT will just log to standard out (e.g. catalina.out)."
+ " Please provide a proper log config file (log4j.xml, see olat/conf for an example or read the installation guide) "
+ "and place it into the root of the classpath e.g. tomcat/lib or WEB-INF/classes");
log.info("*****************************************************************************************");
}
}
/**
* @see org.kuali.kfs.sys.batch.service.ReportGenerationService#generateReportToOutputStream(java.util.Map, java.lang.Object,
* java.lang.String, java.io.ByteArrayOutputStream)
*/
public void generateReportToOutputStream(Map<String, Object> reportData, Object dataSource, String template, ByteArrayOutputStream baos) {
ClassPathResource resource = getReportTemplateClassPathResource(template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
if (resource == null || !resource.exists()) {
throw new IllegalArgumentException("Cannot find the template file: " + template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
}
try {
if (reportData != null && reportData.containsKey(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME)) {
Map<String, String> subReports = (Map<String, String>) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME);
String subReportDirectory = (String) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR);
compileSubReports(subReports, subReportDirectory);
}
String designTemplateName = template.concat(ReportGeneration.DESIGN_FILE_EXTENSION);
InputStream jasperReport = new FileInputStream(compileReportTemplate(designTemplateName));
JRDataSource jrDataSource = JasperReportsUtils.convertReportData(dataSource);
JasperRunManager.runReportToPdfStream(jasperReport, baos, decorateReportData(reportData), jrDataSource);
}
catch (Exception e) {
LOG.error(e);
throw new RuntimeException("Fail to generate report.", e);
}
}
public String readJsonFromFile(String filePath) throws IOException {
ClassPathResource resource = new ClassPathResource(filePath);
if (resource.exists()) {
return new String(IOUtils.toString(resource.getInputStream()));
}
return null;
}
/**
* Detect a default SQL script by implementing the algorithm defined in
* {@link Sql#scripts}.
*/
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
Class<?> clazz = testContext.getTestClass();
Method method = testContext.getTestMethod();
String elementType = (classLevel ? "class" : "method");
String elementName = (classLevel ? clazz.getName() : method.toString());
String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
if (!classLevel) {
resourcePath += "." + method.getName();
}
resourcePath += ".sql";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
prefixedResourcePath, elementType, elementName));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
"%s does not exist. Either declare statements or scripts via @Sql or make the " +
"default SQL script available.", elementType, elementName, classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
public static byte[] read(String classPath) {
//考虑到数据的一致性,这里没有使用map的containsKey()
byte[] s = map.get(classPath);
if (s != null) {
return s;
}
//判空
ClassPathResource resource = new ClassPathResource(classPath);
if (!resource.exists()) {
return null;
}
//读取
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(stream)) {
byte[] bytes = new byte[1024];
int n;
while ((n = bufferedInputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,n);
}
} catch (IOException e) {
e.printStackTrace();
}
//DCL双检查锁
if (!map.containsKey(classPath)) {
synchronized (ReadClasspathFile.class) {
if (!map.containsKey(classPath)) {
map.put(classPath, stream.toByteArray());
}
}
}
return stream.toByteArray();
}
/**
* Detect a default SQL script by implementing the algorithm defined in
* {@link Sql#scripts}.
*/
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
Class<?> clazz = testContext.getTestClass();
Method method = testContext.getTestMethod();
String elementType = (classLevel ? "class" : "method");
String elementName = (classLevel ? clazz.getName() : method.toString());
String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
if (!classLevel) {
resourcePath += "." + method.getName();
}
resourcePath += ".sql";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
prefixedResourcePath, elementType, elementName));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
"%s does not exist. Either declare statements or scripts via @Sql or make the " +
"default SQL script available.", elementType, elementName, classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
/**
* Generate the default classpath resource locations array based on the
* supplied class.
* <p>For example, if the supplied class is {@code com.example.MyTest},
* the generated locations will contain a single string with a value of
* {@code "classpath:com/example/MyTest<suffix>"}, where {@code <suffix>}
* is the value of the first configured
* {@linkplain #getResourceSuffixes() resource suffix} for which the
* generated location actually exists in the classpath.
* <p>As of Spring 3.1, the implementation of this method adheres to the
* contract defined in the {@link SmartContextLoader} SPI. Specifically,
* this method will <em>preemptively</em> verify that the generated default
* location actually exists. If it does not exist, this method will log a
* warning and return an empty array.
* <p>Subclasses can override this method to implement a different
* <em>default location generation</em> strategy.
* @param clazz the class for which the default locations are to be generated
* @return an array of default application context resource locations
* @since 2.5
* @see #getResourceSuffixes()
*/
protected String[] generateDefaultLocations(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
String[] suffixes = getResourceSuffixes();
for (String suffix : suffixes) {
Assert.hasText(suffix, "Resource suffix must not be empty");
String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName()) + suffix;
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default resource location \"%s\" for test class [%s]",
prefixedResourcePath, clazz.getName()));
}
return new String[] {prefixedResourcePath};
}
else if (logger.isDebugEnabled()) {
logger.debug(String.format("Did not detect default resource location for test class [%s]: " +
"%s does not exist", clazz.getName(), classPathResource));
}
}
if (logger.isInfoEnabled()) {
logger.info(String.format("Could not detect default resource locations for test class [%s]: " +
"no resource found for suffixes %s.", clazz.getName(), ObjectUtils.nullSafeToString(suffixes)));
}
return EMPTY_STRING_ARRAY;
}
private void loadConfigsUsingClassLoader(String configFileName) throws Exception {
try (BufferedInputStream fis = (BufferedInputStream) this.getClass().getClassLoader().getResourceAsStream(configFileName)) {
ClassPathResource configFile = new ClassPathResource(configFileName);
if (!configFile.exists()) {
throw new FileNotFoundException(configFileName);
}
String configData = IOUtils.toString(fis, Charset.defaultCharset());
loadConfigs(configData);
}
}
public static Content getContentFromClassPath(String url) throws IOException {
final ClassPathResource resource = new ClassPathResource(url);
if (resource.exists()) {
final byte[] data = IOUtils.toByteArray(resource.getInputStream());
final long lastModified = resource.lastModified();
return new Content() {
@Override
public long getLastModified() {
return lastModified;
}
@Override
public long getLength() {
return data.length;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
};
} else {
return null;
}
}
private String loadImportView() throws IOException
{
ClassPathResource importViewResource = new ClassPathResource(configPath + packageName + ".xml");
if (!importViewResource.exists())
{
throw new AlfrescoRuntimeException("Cannot find site config " + importViewResource.getPath());
}
return convert(importViewResource.getInputStream());
}
/**
* Detect a default SQL script by implementing the algorithm defined in
* {@link Sql#scripts}.
*/
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
Class<?> clazz = testContext.getTestClass();
Method method = testContext.getTestMethod();
String elementType = (classLevel ? "class" : "method");
String elementName = (classLevel ? clazz.getName() : method.toString());
String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
if (!classLevel) {
resourcePath += "." + method.getName();
}
resourcePath += ".sql";
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]", prefixedResourcePath,
elementType, elementName));
}
return prefixedResourcePath;
}
else {
String msg = String.format("Could not detect default SQL script for test %s [%s]: "
+ "%s does not exist. Either declare statements or scripts via @Sql or make the "
+ "default SQL script available.", elementType, elementName, classPathResource);
logger.error(msg);
throw new IllegalStateException(msg);
}
}
/**
* Generate the default classpath resource locations array based on the
* supplied class.
*
* <p>For example, if the supplied class is {@code com.example.MyTest},
* the generated locations will contain a single string with a value of
* {@code "classpath:com/example/MyTest<suffix>"}, where {@code <suffix>}
* is the value of the first configured
* {@linkplain #getResourceSuffixes() resource suffix} for which the
* generated location actually exists in the classpath.
*
* <p>As of Spring 3.1, the implementation of this method adheres to the
* contract defined in the {@link SmartContextLoader} SPI. Specifically,
* this method will <em>preemptively</em> verify that the generated default
* location actually exists. If it does not exist, this method will log a
* warning and return an empty array.
*
* <p>Subclasses can override this method to implement a different
* <em>default location generation</em> strategy.
*
* @param clazz the class for which the default locations are to be generated
* @return an array of default application context resource locations
* @since 2.5
* @see #getResourceSuffixes()
*/
protected String[] generateDefaultLocations(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
String[] suffixes = getResourceSuffixes();
for (String suffix : suffixes) {
Assert.hasText(suffix, "Resource suffix must not be empty");
String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName()) + suffix;
String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
ClassPathResource classPathResource = new ClassPathResource(resourcePath);
if (classPathResource.exists()) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Detected default resource location \"%s\" for test class [%s]",
prefixedResourcePath, clazz.getName()));
}
return new String[] { prefixedResourcePath };
}
else if (logger.isDebugEnabled()) {
logger.debug(String.format("Did not detect default resource location for test class [%s]: "
+ "%s does not exist", clazz.getName(), classPathResource));
}
}
if (logger.isInfoEnabled()) {
logger.info(String.format("Could not detect default resource locations for test class [%s]: "
+ "no resource found for suffixes %s.", clazz.getName(), ObjectUtils.nullSafeToString(suffixes)));
}
return EMPTY_STRING_ARRAY;
}
private boolean isPluginApplicationContextAvailable(){
ClassPathResource r = new ClassPathResource( config.getPluginApplicationContextFile() );
if( r.exists() ){
try{
log.debug( "Found plugin application context at " + r.getURL().toExternalForm() );
}
catch( IOException e ){
log.debug( "Cannot find/access plugin application context file at " + config.getPluginApplicationContextFile() );
}
}
return r.exists();
}
/**
* The dataSource can be an instance of JRDataSource, java.util.Collection or object array.
*
* @see org.kuali.kfs.sys.batch.service.ReportGenerationService#generateReportToPdfFile(java.util.Map, java.lang.Object, java.lang.String,
* java.lang.String)
*/
public void generateReportToPdfFile(Map<String, Object> reportData, Object dataSource, String template, String reportFileName) {
ClassPathResource resource = getReportTemplateClassPathResource(template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
if (resource == null || !resource.exists()) {
throw new IllegalArgumentException("Cannot find the template file: " + template.concat(ReportGeneration.DESIGN_FILE_EXTENSION));
}
try {
if (reportData != null && reportData.containsKey(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME)) {
Map<String, String> subReports = (Map<String, String>) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_TEMPLATE_NAME);
String subReportDirectory = (String) reportData.get(ReportGeneration.PARAMETER_NAME_SUBREPORT_DIR);
compileSubReports(subReports, subReportDirectory);
}
String designTemplateName = template.concat(ReportGeneration.DESIGN_FILE_EXTENSION);
InputStream jasperReport = new FileInputStream(compileReportTemplate(designTemplateName));
JRDataSource jrDataSource = JasperReportsUtils.convertReportData(dataSource);
reportFileName = reportFileName + ReportGeneration.PDF_FILE_EXTENSION;
File reportDirectory = new File(StringUtils.substringBeforeLast(reportFileName, File.separator));
if(!reportDirectory.exists()) {
reportDirectory.mkdir();
}
JasperRunManager.runReportToPdfStream(jasperReport, new FileOutputStream(reportFileName), decorateReportData(reportData), jrDataSource);
}
catch (Exception e) {
LOG.error(e);
throw new RuntimeException("Fail to generate report.", e);
}
}