/** * Create the public key. * * @throws Exception if key creation ran into an error */ protected void createGoogleAppsPublicKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps public key bean will not be created, because it's not configured"); return; } final PublicKeyFactoryBean bean = new PublicKeyFactoryBean(); if (this.publicKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.publicKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.publicKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setLocation(new FileSystemResource(this.publicKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps public key from [{}] with key algorithm [{}]", bean.getResource(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps public key instance via [{}]", this.publicKeyLocation); this.publicKey = bean.getObject(); }
/** * Create the private key. * * @throws Exception if key creation ran into an error */ protected void createGoogleAppsPrivateKey() throws Exception { if (!isValidConfiguration()) { LOGGER.debug("Google Apps private key bean will not be created, because it's not configured"); return; } final PrivateKeyFactoryBean bean = new PrivateKeyFactoryBean(); if (this.privateKeyLocation.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { bean.setLocation(new ClassPathResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.CLASSPATH_URL_PREFIX))); } else if (this.privateKeyLocation.startsWith(ResourceUtils.FILE_URL_PREFIX)) { bean.setLocation(new FileSystemResource(StringUtils.removeStart(this.privateKeyLocation, ResourceUtils.FILE_URL_PREFIX))); } else { bean.setLocation(new FileSystemResource(this.privateKeyLocation)); } bean.setAlgorithm(this.keyAlgorithm); LOGGER.debug("Loading Google Apps private key from [{}] with key algorithm [{}]", bean.getLocation(), bean.getAlgorithm()); bean.afterPropertiesSet(); LOGGER.debug("Creating Google Apps private key instance via [{}]", this.privateKeyLocation); this.privateKey = bean.getObject(); }
private int doSort(ConfigModelWrapper w1, ConfigModelWrapper w2) { ConfigModel m1 = w1.model; ConfigModel m2 = w2.model; boolean isM1Jar = ResourceUtils.isJarURL(m1.getUrl()); boolean isM2Jar = ResourceUtils.isJarURL(m2.getUrl()); if (isM1Jar != isM2Jar) { if (isM1Jar) { return -1; } return 1; } // min order load first int result = Integer.compare(m1.getOrder(), m2.getOrder()); if (result != 0) { return result; } return doFinalSort(w1, w2); }
@Override public PublicKey createInstance() throws Exception { try { final PublicKeyFactoryBean factory = this.publicKeyFactoryBeanClass.newInstance(); if (this.location.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, ResourceUtils.CLASSPATH_URL_PREFIX))); } else { factory.setLocation(new FileSystemResource(this.location)); } factory.setAlgorithm(this.algorithm); factory.setSingleton(false); return factory.getObject(); } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); throw Throwables.propagate(e); } }
/** * 文件列表 * @author eko.zhan at 2017年8月9日 下午8:32:19 * @return * @throws FileNotFoundException */ @ApiOperation(value="获取文件数据列表", notes="获取固定路径下的文件,并返回文件名,文件所在路径和文件大小") @RequestMapping(value="getDataList", method=RequestMethod.POST) public JSONArray getDataList() throws FileNotFoundException{ JSONArray arr = new JSONArray(); File dir = ResourceUtils.getFile("classpath:static/DATAS"); File[] files = dir.listFiles(); for (File file : files){ if (file.isFile()){ JSONObject json = new JSONObject(); json.put("path", file.getPath()); json.put("name", file.getName()); json.put("size", file.length()); arr.add(json); } } return arr; }
@Test public void test1() throws FileNotFoundException { final File sourceFolder = ResourceUtils.getFile("classpath:bulkimport"); final StripingFilesystemTracker tracker = new StripingFilesystemTracker(directoryAnalyser, new NodeRef("workspace", "SpacesStore", "123"), sourceFolder, Integer.MAX_VALUE); List<ImportableItem> items = tracker.getImportableItems(Integer.MAX_VALUE); assertEquals("", 11, items.size()); tracker.incrementLevel(); items = tracker.getImportableItems(Integer.MAX_VALUE); assertEquals("", 2, items.size()); tracker.incrementLevel(); items = tracker.getImportableItems(Integer.MAX_VALUE); assertEquals("", 31, items.size()); }
@SuppressWarnings("deprecation") @Override public void setUp() throws Exception { auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry"); serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); auditComponent = (AuditComponent) ctx.getBean("auditComponent"); auditService = serviceRegistry.getAuditService(); transactionService = serviceRegistry.getTransactionService(); transactionServiceImpl = (TransactionServiceImpl) ctx.getBean("transactionService"); nodeService = serviceRegistry.getNodeService(); searchService = serviceRegistry.getSearchService(); AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName()); nodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE); // Register the models URL modelUrlMnt11072 = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-11072.xml"); URL modelUrlMnt16748 = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test-mnt-16748.xml"); auditModelRegistry.registerModel(modelUrlMnt11072); auditModelRegistry.registerModel(modelUrlMnt16748); auditModelRegistry.loadAuditModels(); }
public String editUserExtend(PersonalInfoPersonalOriented userExtend, String lastImgPath, File newFileName) throws Exception { String tarImg = lastImgPath; //传的文件出现变化则更新文件信息 if (!lastImgPath.equals(newFileName.getPath())) { File lastImg = ResourceUtils.getFile(StaticVar.getToFilePath() + lastImgPath); //FileUtils.forceDelete(lastImg); tarImg = "UserSpace" + "/" + userExtend.getUUuid() + "/" + newFileName.getName(); File newImg = ResourceUtils.getFile(StaticVar.getToFilePath() + tarImg); FileUtils.writeByteArrayToFile(newImg, userExtend.getUImgObj().getBytes("ISO-8859-1")); } userExtend.setUHeadImg(tarImg); registDao.editUserExtend(userExtend); return tarImg; }
/** * Returns a <code>File</code> handle for this resource. This method does a * best-effort attempt to locate the bundle resource on the file system. It * is strongly recommended to use {@link #getInputStream()} method instead * which works no matter if the bundles are saved (in exploded form or not) * on the file system. * * @return File handle to this resource * @throws IOException if the resource cannot be resolved as absolute file * path, i.e. if the resource is not available in a file system */ public File getFile() throws IOException { // locate the file inside the bundle only known prefixes if (searchType != OsgiResourceUtils.PREFIX_TYPE_UNKNOWN) { String bundleLocation = bundle.getLocation(); int prefixIndex = bundleLocation.indexOf(ResourceUtils.FILE_URL_PREFIX); if (prefixIndex > -1) { bundleLocation = bundleLocation.substring(prefixIndex + ResourceUtils.FILE_URL_PREFIX.length()); } File file = new File(bundleLocation, path); if (file.exists()) { return file; } // fall back to the URL discovery (just in case) } try { return ResourceUtils.getFile(getURI(), getDescription()); } catch (IOException ioe) { throw (IOException) new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path").initCause(ioe); } }
@Override public Reader getReader(Engine engine, String fileName, Charset charset) throws IOException { File file; try { file = ResourceUtils.getFile(fileName); } catch (FileNotFoundException e) { Reader reader = defaultKnowledgeBaseFileProvider.getReader(engine, fileName, charset); if (reader == null) { logger.warn("getReader", e); } return reader; } if (!file.exists()) { return null; } return new InputStreamReader(new FileInputStream(file), charset); }
@Override public boolean doInternal(MessageReceivedEvent message, BotContext context, String query) throws DiscordException { if (!message.getMessage().getAttachments().isEmpty()) { query = message.getMessage().getAttachments().get(0).getUrl(); } List<String> results = (List<String>) context.getAttribute(ATTR_SEARCH_RESULTS); if (StringUtils.isNumeric(query) && CollectionUtils.isNotEmpty(results)) { int index = Integer.parseInt(query) - 1; query = getChoiceUrl(context, index); if (query == null) { messageManager.onQueueError(message.getChannel(), "discord.command.audio.play.select", results.size()); return fail(message); } } message.getTextChannel().sendTyping().queue(); if (!ResourceUtils.isUrl(query)) { String result = youTubeService.searchForUrl(query); query = result != null ? result : query; } loadAndPlay(message.getTextChannel(), context, message.getMember(), query); return true; }
@Before public void setup() throws Exception { super.setup(); permissionService = applicationContext.getBean("permissionService", PermissionService.class); authorityService = (AuthorityService) applicationContext.getBean("AuthorityService"); auditService = applicationContext.getBean("AuditService", AuditService.class); AuditModelRegistryImpl auditModelRegistry = (AuditModelRegistryImpl) applicationContext.getBean("auditModel.modelRegistry"); // Register the test model URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/audit/alfresco-audit-access.xml"); auditModelRegistry.registerModel(testModelUrl); auditModelRegistry.loadAuditModels(); }
private void configureSslKeyStore(SslContextFactory factory, Ssl ssl) { try { URL url = ResourceUtils.getURL(ssl.getKeyStore()); factory.setKeyStoreResource(Resource.newResource(url)); } catch (IOException ex) { throw new WebServerException( "Could not find key store '" + ssl.getKeyStore() + "'", ex); } if (ssl.getKeyStoreType() != null) { factory.setKeyStoreType(ssl.getKeyStoreType()); } if (ssl.getKeyStoreProvider() != null) { factory.setKeyStoreProvider(ssl.getKeyStoreProvider()); } }
private void configureSslTrustStore(final SslContextFactory factory, final Ssl ssl) { if (ssl.getTrustStorePassword() != null) { factory.setTrustStorePassword(ssl.getTrustStorePassword()); } if (ssl.getTrustStore() != null) { try { URL url = ResourceUtils.getURL(ssl.getTrustStore()); factory.setTrustStoreResource(Resource.newResource(url)); } catch (IOException ex) { throw new WebServerException( "Could not find trust store '" + ssl.getTrustStore() + "'", ex); } } if (ssl.getTrustStoreType() != null) { factory.setTrustStoreType(ssl.getTrustStoreType()); } if (ssl.getTrustStoreProvider() != null) { factory.setTrustStoreProvider(ssl.getTrustStoreProvider()); } }
@Override public boolean isReadable() { try { URL url = getURL(); if (ResourceUtils.isFileURL(url)) { // Proceed with file system resolution... File file = getFile(); return (file.canRead() && !file.isDirectory()); } else { return true; } } catch (IOException ex) { return false; } }
/** * This implementation opens an InputStream for the given URL. * <p>It sets the {@code useCaches} flag to {@code false}, * mainly to avoid jar file locking on Windows. * @see java.net.URL#openConnection() * @see java.net.URLConnection#setUseCaches(boolean) * @see java.net.URLConnection#getInputStream() */ @Override public InputStream getInputStream() throws IOException { URLConnection con = this.url.openConnection(); ResourceUtils.useCachesIfNecessary(con); try { return con.getInputStream(); } catch (IOException ex) { // Close the HTTP connection (if applicable). if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).disconnect(); } throw ex; } }
/** * Subclasses can override this method to return the locations of their * config files. * <p>A plain path will be treated as class path location, e.g.: * "org/springframework/whatever/foo.xml". Note however that you may prefix * path locations with standard Spring resource prefixes. Therefore, a * config location path prefixed with "classpath:" with behave the same as a * plain path, but a config location such as * "file:/some/path/path/location/appContext.xml" will be treated as a * filesystem location. * <p>The default implementation builds config locations for the config paths * specified through {@link #getConfigPaths()}. * @return an array of config locations * @see #getConfigPaths() * @see org.springframework.core.io.ResourceLoader#getResource(String) */ protected final String[] getConfigLocations() { String[] paths = getConfigPaths(); String[] convertedPaths = new String[paths.length]; for (int i = 0; i < paths.length; i++) { String path = paths[i]; if (path.startsWith(SLASH)) { convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path; } else if (!ResourcePatternUtils.isUrl(path)) { convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH + StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + SLASH + path); } else { convertedPaths[i] = StringUtils.cleanPath(path); } } return convertedPaths; }
/** * 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); } }
private void init() { config = new HashMap<String, String>(); File file = null; try { file = ResourceUtils.getFile(PROPERTIES_PATH); } catch (FileNotFoundException e) { LOGGER.warn(String.format("file not found, path:[%s]", PROPERTIES_PATH)); file = new File(GLOBAL_PROPERTIES_PATH); if(!file.exists() || !file.isFile()) { LOGGER.warn(String.format("file not found, path:[%s]", PROPERTIES_PATH)); file = null; } } if(file == null) return; PropertiesUtils.convertPropertiesToMap(config, file); ip = config.get("ip"); }
private <E> void initProps(Class<E> clazz) throws Exception { String rcName = clazz.getSimpleName() + ".properties"; File rcFile = ResourceUtils.getFile("classpath:"+rcName); log.debug(rcFile.exists()); Properties prop=new Properties(); prop.load(new InputStreamReader(new FileInputStream(rcFile), Constants.CHARSET)); Constructor<E> minimalConstructor = getConstructor(clazz, new Class[] {String.class, int.class}); Constructor<E> additionalConstructor = getConstructor(clazz, new Class[] {String.class, String.class, int.class}); int ordinal = 0; Iterator<Object> keys = prop.keySet().iterator(); while(keys.hasNext()){ String key = keys.next().toString(); String value = prop.getProperty(key); if(StringUtils.isEmpty(value)) minimalConstructor.newInstance(key, ordinal++); else additionalConstructor.newInstance(key, value, ordinal++); } }
@Override public void setFilterChainDefinitions(String definitionFile) { checkArgument(definitionFile.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX), "definition file must be a classpath file, and it must start with 'classpath:'"); String realPath = definitionFile.split(ResourceUtils.CLASSPATH_URL_PREFIX)[1]; checkNotNull(realPath, "empty real path is not allowed"); Resource filterChainDefinitionResource = new ClassPathResource(realPath); String definitions; try { log.info("start load shiro filter definition [{}]", realPath); definitions = FileUtils.readFileToString(filterChainDefinitionResource.getFile(), StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException("shiro filter initialize need an valid filter chain definition " + "resource file, it's must start with [classpath:], and then is a valid file path, but get [" + definitionFile + "]", e); } checkNotNull(definitions, "empty definitions is not allowed"); super.setFilterChainDefinitions(definitions); }
/** * 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); // } }
protected void loadConfiguration(String location, LogFile logFile) { Assert.notNull(location, "Location must not be null"); try { String configuration = FileCopyUtils.copyToString( new InputStreamReader(ResourceUtils.getURL(location).openStream())); if (logFile != null) { configuration = configuration.replace("${LOG_FILE}", StringUtils.cleanPath(logFile.toString())); } LogManager.getLogManager().readConfiguration( new ByteArrayInputStream(configuration.getBytes())); } catch (Exception ex) { throw new IllegalStateException( "Could not initialize Java logging from " + location, ex); } }
private void initializeSystem(ConfigurableEnvironment environment, LoggingSystem system, LogFile logFile) { LoggingInitializationContext initializationContext = new LoggingInitializationContext( environment); String logConfig = environment.getProperty(CONFIG_PROPERTY); if (ignoreLogConfig(logConfig)) { system.initialize(initializationContext, null, logFile); } else { try { ResourceUtils.getURL(logConfig).openStream().close(); system.initialize(initializationContext, logConfig, logFile); } catch (Exception ex) { // NOTE: We can't use the logger here to report the problem System.err.println("Logging system failed to initialize " + "using configuration from '" + logConfig + "'"); ex.printStackTrace(System.err); throw new IllegalStateException(ex); } } }
private void configureSslTrustStore(AbstractHttp11JsseProtocol<?> protocol, Ssl ssl) { if (ssl.getTrustStore() != null) { try { protocol.setTruststoreFile( ResourceUtils.getURL(ssl.getTrustStore()).toString()); } catch (FileNotFoundException ex) { throw new EmbeddedServletContainerException( "Could not load trust store: " + ex.getMessage(), ex); } } protocol.setTruststorePass(ssl.getTrustStorePassword()); if (ssl.getTrustStoreType() != null) { protocol.setTruststoreType(ssl.getTrustStoreType()); } if (ssl.getTrustStoreProvider() != null) { protocol.setTruststoreProvider(ssl.getTrustStoreProvider()); } }
private void configureSslKeyStore(SslContextFactory factory, Ssl ssl) { try { URL url = ResourceUtils.getURL(ssl.getKeyStore()); factory.setKeyStoreResource(Resource.newResource(url)); } catch (IOException ex) { throw new EmbeddedServletContainerException( "Could not find key store '" + ssl.getKeyStore() + "'", ex); } if (ssl.getKeyStoreType() != null) { factory.setKeyStoreType(ssl.getKeyStoreType()); } if (ssl.getKeyStoreProvider() != null) { factory.setKeyStoreProvider(ssl.getKeyStoreProvider()); } }
private void configureSslTrustStore(SslContextFactory factory, Ssl ssl) { if (ssl.getTrustStorePassword() != null) { factory.setTrustStorePassword(ssl.getTrustStorePassword()); } if (ssl.getTrustStore() != null) { try { URL url = ResourceUtils.getURL(ssl.getTrustStore()); factory.setTrustStoreResource(Resource.newResource(url)); } catch (IOException ex) { throw new EmbeddedServletContainerException( "Could not find trust store '" + ssl.getTrustStore() + "'", ex); } } if (ssl.getTrustStoreType() != null) { factory.setTrustStoreType(ssl.getTrustStoreType()); } if (ssl.getTrustStoreProvider() != null) { factory.setTrustStoreProvider(ssl.getTrustStoreProvider()); } }
private Set<String> getSearchLocations() { Set<String> locations = new LinkedHashSet<String>(); // User-configured settings take precedence, so we do them first if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) { for (String path : asResolvedSet( this.environment.getProperty(CONFIG_LOCATION_PROPERTY), null)) { if (!path.contains("$")) { path = StringUtils.cleanPath(path); if (!ResourceUtils.isUrl(path)) { path = ResourceUtils.FILE_URL_PREFIX + path; } } locations.add(path); } } locations.addAll( asResolvedSet(ConfigFileApplicationListener.this.searchLocations, DEFAULT_SEARCH_LOCATIONS)); return locations; }
private boolean updateFileSystem(URL url, String name, ClassLoaderFile classLoaderFile) { if (!isFolderUrl(url.toString())) { return false; } try { File folder = ResourceUtils.getFile(url); File file = new File(folder, name); if (file.exists() && file.canWrite()) { if (classLoaderFile.getKind() == Kind.DELETED) { return file.delete(); } FileCopyUtils.copy(classLoaderFile.getContents(), file); return true; } } catch (IOException ex) { // Ignore } return false; }
@PostConstruct private void init() { try { ArffLoader loader = new ArffLoader(); File f = ResourceUtils.getFile(dummyFile); loader.setFile(f); log.info("Reading file ["+f+"] for creating evaluation dataset"); instances = loader.getDataSet(); } catch (Exception e) { log.error("EvaluationDatasetGenerator::init [ "+e.getMessage() + "] Will go with a dummy dataset. "); log.debug("", e); try { instances = new RandomRBF().generateExamples(); } catch (Exception e1) { log.debug("", e); } } instances.setClassIndex(instances.numAttributes()-1); }
/** * 装载资源到文件 * @param p_location 资源的绝对路径/资源的classpath * @return * @see #getResourceURL(String) */ public static File getResourceFile(String p_location) throws IOException{ File file = null; URL url = getResourceURL(p_location); try { if(url == null){ //1 当采用绝对路径时 D:/chen/chen.properties //2 或者 含有classpath:前缀 file = ResourceUtils.getFile(p_location); }else{ //传统方式中 File URL 只能以"file://" 开头的 。 //uap 模块中的使用的是 "束"协议bundleresource:// 例如:bundleresource://150.fwk17482403:1/diag-debug.properties file = ResourceUtils.getFile(url); //TODO: "束" bundleresource:// } return file; } catch (Exception e) { throw new IOException("loading file failed. from " + p_location); } }
@Override public File getFile() throws IOException { URL resourceUrl = getURL(); if(ResourceUtils.isJarURL(resourceUrl)) { File tempFile = FILE_REGISTRY.get(resourceUrl); if(tempFile == null || !tempFile.exists()) { log.debug("Extracting File for URL: {}", resourceUrl); tempFile = JarUtils.getFile(delegate, extractPath); FILE_REGISTRY.put(resourceUrl, tempFile); } else { log.debug("File found in registry for URL: {}", resourceUrl); } return new File(tempFile.toURI()); } return delegate.getFile(); }
/** * Search for a resource according to the following rules: * <ul> * <li>If the location represents an URL, return a new {@link org.springframework.core.io.UrlResource} for * this URL.</li> * <li>Try to find a file below the {@code conf} directory using {@code location} as relative path. * If found, return a new {@link org.springframework.core.io.UrlResource} for this file.</li> * <li> Otherwise return a new {@link org.springframework.core.io.ClassPathResource} to retrieve content * from classpath.</li> * </ul> * * @param location resource location * @return resource reference */ @Override public Resource getResource(String location) { if (ResourceUtils.isUrl(location)) { return super.getResource(location); } else { if (location.startsWith("/")) location = location.substring(1); File file = new File(confDir, location); if (file.exists()) { location = file.toURI().toString(); } else { location = "classpath:" + location; } return super.getResource(location); } }
protected void replaceLocationsFromConf(String[] locations) { String confDirProp = AppContext.getProperty("cuba.confDir"); if (confDirProp == null) throw new IllegalStateException("cuba.confDir app property is not set"); File confDir = new File(confDirProp); for (int i = 0; i < locations.length; i++) { String location = locations[i]; if (ResourceUtils.isUrl(location)) continue; if (location.startsWith("/")) location = location.substring(1); File file = new File(confDir, location); if (file.exists()) { locations[i] = file.toURI().toString(); } } }
@Override public byte[] serialize(Object data) throws ZkSerializeException { InputStream is = null; try { if(data instanceof String) { is = ResourceUtils.getURL((String)data).openStream(); }else if(data instanceof Resource) { is = ((Resource) data).getInputStream(); }else if(data instanceof InputStream) is = (InputStream)data; return IOUtils.toByteArray(is); } catch (IOException e) { throw new ZkSerializeException("ZkResourceSerializer serialize error.", e); } finally { IOUtils.closeQuietly(is); } }