/** * Initialize logback from the given file location, with no config file * refreshing. Assumes an XML file in case of a ".xml" file extension, and a * properties file otherwise. * * @param location the location of the config file: either a "classpath:" * location (e.g. "classpath:mylogback.properties"), an absolute * file URL (e.g. * "file:C:/logback.properties), or a plain absolute path in the file system (e.g. " * C:/logback.properties") * @throws FileNotFoundException if the location specifies an invalid file path */ public static void initLogging(String location) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils .resolvePlaceholders(location); URL url = ResourceUtils.getURL(resolvedLocation); if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) { // DOMConfigurator.configure(url); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(url); } catch (JoranException ex) { throw new FileNotFoundException(url.getPath()); } lc.start(); } // else { // PropertyConfigurator.configure(url); // } }
/** * Finds all the classes which have a BeanTag or BeanTags annotation * * @param basePackage the package to start in * @return classes which have BeanTag or BeanTags annotation * @throws IOException * @throws ClassNotFoundException */ protected static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); List<Class<?>> classes = new ArrayList<Class<?>>(); String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders( basePackage)); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolvedBasePackage + "/" + "**/*.class"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (metadataReader != null && isBeanTag(metadataReader)) { classes.add(Class.forName(metadataReader.getClassMetadata().getClassName())); } } } return classes; }
/** * Initialize logback from the given file. * * @param location * the location of the config file: either a "classpath:" * location (e.g. "classpath:logback.xml"), an absolute file URL * (e.g. "file:C:/logback.xml), or a plain absolute path in the * file system (e.g. "C:/logback.xml") * @throws java.io.FileNotFoundException * if the location specifies an invalid file path */ public static void initLogging(final String location) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location); URL url = ResourceUtils.getURL(resolvedLocation); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); // the context was probably already configured by default // configuration // rules loggerContext.reset(); configurator.doConfigure(url); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); }
public static void main(String[] args) { ClassPathXmlApplicationContext ctx = Util.initContext("simple-res.xml"); System.out.println("res loaderd"); ctx.close(); try { String s1 ="D:/tmp/gemlite/data/prod*"; String s2 ="classpath:prod*"; String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(s2); URL url = ResourceUtils.getURL(resolvedLocation); System.out.println(resolvedLocation+" "+url); } catch (Exception e) { e.printStackTrace(); } }
/** * 加载logback配置 * @param location 文件路径 * @throws FileNotFoundException 文件不存在异常 */ public static void initLogging(String location) throws FileNotFoundException { if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) { String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location); URL url = ResourceUtils.getURL(resolvedLocation); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); loggerContext.reset(); configurator.doConfigure(url); } catch (Throwable e) { BasicConfigurator.configureDefaultContext(); Logger log = LoggerFactory.getLogger(MODULE); log.warn("Logback configure fail!", e); } } }
private void initModuleConfiguration() { if (!scanModuleConfigurations) { this.moduleDefaultConfiguration = new ConcurrentMapConfiguration(); return; } HashMap<String, Object> base = new HashMap<>(); Set<Class<?>> types = reflections .getTypesAnnotatedWith(PropertySource.class); for (Class<?> type : types) { PropertySource propertySource = type .getAnnotation(PropertySource.class); String[] propertiesFiles = propertySource.value(); for (String propertyFile : propertiesFiles) { Properties properties = new Properties(); try (InputStream is = resourceLoader.getResource(SystemPropertyUtils.resolvePlaceholders(propertyFile)) .getInputStream()) { properties.load(is); LOGGER.debug("Initializing module properties from path " + propertyFile); } catch (Exception e) { BootstrapException.resourceLoadingFailed(propertyFile, e); } join(base, properties, propertyFile, propertiesFiles); } } this.moduleDefaultConfiguration = new ConcurrentMapConfiguration(base); }
public static OutputStream createFile(String path) { try { Path p = Paths.get(SystemPropertyUtils.resolvePlaceholders(path)); if (Files.exists(p)) { Files.delete(p); } File file = new File(path); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new RuntimeException("Unable to create parent file(s) " + file.getParent()); } } return Files.newOutputStream(p); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Finds all the classes which have a BeanTag or BeanTags annotation * * @param basePackage the package to start in * @return classes which have BeanTag or BeanTags annotation * @throws IOException * @throws ClassNotFoundException */ private static List<Class<?>> findTagClasses(String basePackage) throws IOException, ClassNotFoundException { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); List<Class<?>> classes = new ArrayList<Class<?>>(); String resolvedBasePackage = ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders( basePackage)); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolvedBasePackage + "/" + "**/*.class"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (metadataReader != null && isBeanTag(metadataReader)) { classes.add(Class.forName(metadataReader.getClassMetadata().getClassName())); } } } return classes; }
/** * 根据扫描包的,查询下面的所有类 * * @param scanPackages 扫描的package路径 * @return */ public static Set<String> findPackageClass(String scanPackages) { if (StringUtils.isEmpty(scanPackages)) { return Collections.EMPTY_SET; } //验证及排重包路径,避免父子路径多次扫描 Set<String> packages = checkPackage(scanPackages); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); Set<String> clazzSet = new HashSet<String>(); for (String basePackage : packages) { if (StringUtils.isEmpty(basePackage)) { continue; } String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + org.springframework.util.ClassUtils.convertClassNameToResourcePath( SystemPropertyUtils.resolvePlaceholders(basePackage)) + "/" + DEFAULT_RESOURCE_PATTERN; try { Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { //检查resource,这里的resource都是class String clazz = loadClassName(metadataReaderFactory, resource); clazzSet.add(clazz); } } catch (Exception e) { LOG.error("获取包下面的类信息失败,package:" + basePackage, e); } } return clazzSet; }
/** * 根据扫描包的,查询下面的所有类 * * @param scanPackages * 扫描的package路径 * @return */ public static Set<String> findPackageClass(String scanPackages) { if (StringUtils.isBlank(scanPackages)) { return Collections.emptySet(); } // 验证及排重包路径,避免父子路径多次扫描 Set<String> packages = checkPackage(scanPackages); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); Set<String> clazzSet = new HashSet<String>(); for (String basePackage : packages) { if (StringUtils.isBlank(basePackage)) { continue; } String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + org.springframework.util.ClassUtils .convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)) + "/" + DEFAULT_RESOURCE_PATTERN; try { Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { // 检查resource,这里的resource都是class String clazz = loadClassName(metadataReaderFactory, resource); clazzSet.add(clazz); } } catch (Exception e) { log.error("获取包内shard方法失败,package:" + basePackage, e); } } return clazzSet; }
/** * Initialize logback, including setting the web app root system property. * * @param servletContext the current ServletContext * @see WebUtils#setWebAppRootSystemProperty */ public static void initLogging(ServletContext servletContext) { // Expose the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.setWebAppRootSystemProperty(servletContext); } // Only perform custom logback initialization in case of a config file. String location = servletContext .getInitParameter(CONFIG_LOCATION_PARAM); if (location != null) { // Perform actual logback initialization; else rely on logback's // default initialization. try { // Return a URL (e.g. "classpath:" or "file:") as-is; // consider a plain file path as relative to the web application // root directory. if (!ResourceUtils.isUrl(location)) { // Resolve system property placeholders before resolving // real path. location = SystemPropertyUtils .resolvePlaceholders(location); location = WebUtils.getRealPath(servletContext, location); } // Write log message to server log. servletContext.log("Initializing logback from [" + location + "]"); // Initialize without refresh check, i.e. without logback's // watchdog thread. LogbackConfigurer.initLogging(location); } catch (FileNotFoundException ex) { throw new IllegalArgumentException( "Invalid 'logbackConfigLocation' parameter: " + ex.getMessage()); } } }
private static String getClassSearchPattern(String packageName) { String resolvedPackageName = SystemPropertyUtils.resolvePlaceholders(packageName); String resourcePath = ClassUtils.convertClassNameToResourcePath(resolvedPackageName); if (StringUtils.isEmpty(resourcePath)) { return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "??/" + CLASS_RESOURCE_PATTERN; } return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourcePath + "/" + CLASS_RESOURCE_PATTERN; }
/** * Finds all the model classes and the model error class. * * @throws MojoExecutionException if a class couldn't be instantiated or an I/O error occurred. */ private void findModelClasses() throws MojoExecutionException { try { log.debug("Finding model classes."); // Get the model classes as resources. modelClasses = new HashSet<>(); // Loop through each model resource and add each one to the set of model classes. for (Resource resource : ResourceUtils.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(modelJavaPackage)) + "/**/*.class")) { if (resource.isReadable()) { MetadataReader metadataReader = new CachingMetadataReaderFactory(new PathMatchingResourcePatternResolver()).getMetadataReader(resource); Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName()); modelClasses.add(clazz); log.debug("Found model class \"" + clazz.getName() + "\"."); // If the model error class name is configured and matches this class, then hold onto it. if (clazz.getSimpleName().equals(modelErrorClassName)) { log.debug("Found model error class \"" + clazz.getName() + "\"."); modelErrorClass = clazz; } } } } catch (IOException | ClassNotFoundException e) { throw new MojoExecutionException("Error finding model classes. Reason: " + e.getMessage(), e); } }
/** * 扫描指定的package,找出所有指定注解的class * <br/>内部调用{@link this#matches(MetadataReader)} 来判断 * @param basePackage 指定的package * @return 寻找的结果 */ public Set<Class> doScan(String basePackage) { Set<Class> classes = new HashSet<Class>(); try { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils .convertClassNameToResourcePath(SystemPropertyUtils .resolvePlaceholders(basePackage)) + DEFAULT_RESOURCE_PATTERN; Resource[] resources = this.resourcePatternResolver .getResources(packageSearchPath); for (int i = 0; i < resources.length; i++) { Resource resource = resources[i]; if (resource.isReadable()) { MetadataReader metadataReader = this.metadataReaderFactory .getMetadataReader(resource); if ((includeFilters.size() == 0 && excludeFilters.size() == 0) || matches(metadataReader)) { try { classes.add(Class.forName(metadataReader .getClassMetadata().getClassName())); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } catch (IOException ex) { throw new BeanDefinitionStoreException( "I/O failure during classpath scanning", ex); } return classes; }
public static void initLog4j(String configFile) { configFile = "log4j2-server.xml"; if (getProperty(ITEMS.NODE_TYPE.name()) == null) setProperty("NODE_TYPE", ""); if (getProperty(ITEMS.NODE_NAME.name()) == null) setProperty("NODE_NAME", ""); String resolvedLocation = SystemPropertyUtils.resolvePlaceholders("log4j2-server.xml"); URL url; try { url = ServerConfigHelper.class.getClassLoader().getResource(configFile); LoggerContext context = (LoggerContext) LogManager.getContext(false); context.setConfigLocation(url.toURI()); LogUtil.init(); } catch (URISyntaxException e) { e.printStackTrace(); } // System.setProperty("log4j.configurationFile", configFile); // try // { // if (!configFile.startsWith("classpath")) // configFile = "classpath:" + configFile; // Log4jConfigurer.initLogging(configFile); // } // catch (FileNotFoundException e) // { // System.err.println("File " + configFile + " not exists!"); // } }
@SuppressWarnings({"unchecked", "rawtypes"}) private void initApplicationFileConfiguration() { if (applicationPropertiesPath == null) { LOGGER.debug("No client application properties to configure. Skipping..."); applicationFileConfiguration = new ConcurrentMapConfiguration(); return; } this.applicationFileConfiguration = new ConcurrentCompositeConfiguration(); String path = SystemPropertyUtils.resolvePlaceholders(applicationPropertiesPath); LOGGER.debug("Configuring client application properties from path " + applicationPropertiesPath); Map applicationProperties = new Properties(); if (SystemUtils.IS_OS_WINDOWS) { if (path.startsWith("file://")) { if (!path.startsWith("file:///")) { path = path.replaceFirst(Pattern.quote("file://"), "file:///"); } } } try (InputStream is = resourceLoader.getResource(path).getInputStream()) { ((Properties) applicationProperties).load(is); } catch (Exception e) { BootstrapException.resourceLoadingFailed(path, applicationPropertiesPath, e); } Map environmentApplicationProperties = getEnvironmentSpecificProperties(path); if (environmentApplicationProperties != null) { ((ConcurrentCompositeConfiguration) this.applicationFileConfiguration).addConfiguration(new ConcurrentMapConfiguration(environmentApplicationProperties)); } ((ConcurrentCompositeConfiguration) this.applicationFileConfiguration).addConfiguration(new ConcurrentMapConfiguration(applicationProperties)); if (applicationFileConfiguration.containsKey(BootstrapConfigKeys.PUBLISH_DEFAULTS_KEY.getPropertyName())) { this.publishDefaults = applicationFileConfiguration.getBoolean(BootstrapConfigKeys.PUBLISH_DEFAULTS_KEY.getPropertyName()); } }
@SuppressWarnings("unchecked") public static void writePropertiesToFile(String path, Set<Path> filesCreated, SimpleEntry<String, String>... entries) { Properties properties = new Properties(); for (SimpleEntry<String, String> entry : entries) { properties.put(entry.getKey(), entry.getValue()); } Path p = Paths.get(SystemPropertyUtils.resolvePlaceholders(path)); try (OutputStream os = createFile(p.toString())) { properties.store(os, "test properties"); filesCreated.add(p); } catch (IOException e) { throw new RuntimeException(e); } }
static boolean isTransport(ClassNode node, String type) { for (AnnotationNode annotationNode : node.getAnnotations()) { String annotation = "EnableBinding"; if (PatternMatchUtils.simpleMatch(annotation, annotationNode.getClassNode().getName())) { Expression expression = annotationNode.getMembers().get("transport"); String transport = expression == null ? "rabbit" : expression.getText(); if (transport != null) { transport = SystemPropertyUtils.resolvePlaceholders(transport); } return transport.equals(type); } } return false; }
protected String resolveBasePackage(String basePackage) { return convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)); }
protected String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)); }
private static String getResourcePath(final String packageName) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)); }
public static String expandEnvironmentVars(String text) { if (text == null) { return text; } return SystemPropertyUtils.resolvePlaceholders(text); }
private void initializeWithSpecificConfig( LoggingInitializationContext initializationContext, String configLocation, LogFile logFile) { configLocation = SystemPropertyUtils.resolvePlaceholders(configLocation); loadConfiguration(initializationContext, configLocation, logFile); }
private File getDefaultLibDirectory() { String home = SystemPropertyUtils .resolvePlaceholders("${spring.home:${SPRING_HOME:.}}"); return new File(home, "lib"); }
private static String getFileSearchPattern(String path) { String resolvedPath = SystemPropertyUtils.resolvePlaceholders(path); return ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolvedPath; }
/** * Initialize Logback, including setting the web app root system property. * * @param servletContext * the current ServletContext * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty */ public static void initLogging(final ServletContext servletContext) { // Expose the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.setWebAppRootSystemProperty(servletContext); } // Only perform custom Logback initialization in case of a config file. String locationParameter = servletContext.getInitParameter(CONFIG_LOCATION_PARAM); String[] locations = null; if(locationParameter.indexOf(",") != -1) { locations = locationParameter.split(","); } else { locations = new String[] {locationParameter}; } if (locations.length > 0) { for (String location : locations) { // Perform actual Logback initialization; else rely on Logback's // default initialization. try { // Return a URL (e.g. "classpath:" or "file:") as-is; // consider a plain file path as relative to the web // application // root directory. if (!ResourceUtils.isUrl(location)) { // Resolve system property placeholders before resolving // real path. location = SystemPropertyUtils.resolvePlaceholders(location); location = WebUtils.getRealPath(servletContext, location); } // Write log message to server log. servletContext.log("Initializing Logback from [" + location + "]"); // Initialize LogbackConfigurer.initLogging(location); break; } catch (FileNotFoundException ex) { servletContext.log("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage()); } } } }
private String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage)); }
private static String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders( basePackage)); }
private String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils .resolvePlaceholders(basePackage)); }
/** * Resolve base package. * * @param basePackage the base package * @return the string */ protected String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils .resolvePlaceholders(basePackage)); }
/** * 将包名转换成目录名(com.my9yu-->com/my9yu) * @param basePackage 包名 * @return */ private static String resolveBasePackage(String basePackage) { String placeHolderReplace = SystemPropertyUtils.resolvePlaceholders(basePackage);//${classpath}替换掉placeholder 引用的变量值 return ClassUtils.convertClassNameToResourcePath(placeHolderReplace); }