/**
* Return the file timestamp for the given resource.
* @param resourceUrl the URL of the resource
* @return the file timestamp in milliseconds, or -1 if not determinable
*/
protected long getFileTimestamp(String resourceUrl) {
ServletContextResource resource = new ServletContextResource(getServletContext(), resourceUrl);
try {
long lastModifiedTime = resource.lastModified();
if (logger.isDebugEnabled()) {
logger.debug("Last-modified timestamp of " + resource + " is " + lastModifiedTime);
}
return lastModifiedTime;
}
catch (IOException ex) {
logger.warn("Couldn't retrieve last-modified timestamp of [" + resource +
"] - using ResourceServlet startup time");
return -1;
}
}
java类org.springframework.web.context.support.ServletContextResource的实例源码
ResourceServlet.java 文件源码
项目:spring4-understanding
阅读 31
收藏 0
点赞 0
评论 0
ViewConfiguration.java 文件源码
项目:java-platform
阅读 24
收藏 0
点赞 0
评论 0
@Bean
public CompositeResourceLoader viewResourceLoader() {
CompositeResourceLoader compositeResourceLoader = new CompositeResourceLoader();
compositeResourceLoader.addResourceLoader(new StartsWithMatcher(VIEW_PREFIX_CLASSPATH).withoutPrefix(),
new ClasspathResourceLoader("/views"));
try {
compositeResourceLoader.addResourceLoader(new StartsWithMatcher(VIEW_PREFIX_TEMPLATE),
new WebAppResourceLoader(new ServletContextResource(servletContext, templateLocation).getFile().getAbsolutePath()));
compositeResourceLoader.addResourceLoader(new StartsWithMatcher("/WEB-INF").withPrefix(),
new WebAppResourceLoader(servletContext.getRealPath(".")));
} catch (IOException e) {
e.printStackTrace();
}
return compositeResourceLoader;
}
VelocityToolboxView.java 文件源码
项目:java-template-simple
阅读 78
收藏 0
点赞 0
评论 0
@Override
protected Context createVelocityContext(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ViewToolContext velocityContext = new ViewToolContext(getVelocityEngine(), request, response, getServletContext());
velocityContext.putAll(model);
if(getToolboxConfigLocation() != null ||getToolboxConfigResource() != null){
XmlFactoryConfiguration cfg = new XmlFactoryConfiguration();
URL cfgUrl;
if(getToolboxConfigLocation() != null){
cfgUrl = new ServletContextResource(getServletContext(), getToolboxConfigLocation()).getURL();
cfg.read(cfgUrl);
}else if(getToolboxConfigResource() != null){
cfgUrl = getToolboxConfigResource().getURL();
cfg.read(cfgUrl);
ToolboxFactory factory = cfg.createFactory();
velocityContext.addToolbox(factory.createToolbox(Scope.APPLICATION));
velocityContext.addToolbox(factory.createToolbox(Scope.REQUEST));
velocityContext.addToolbox(factory.createToolbox(Scope.SESSION));
}
}
return velocityContext;
}
WebResourceProcessor.java 文件源码
项目:edsutil
阅读 18
收藏 0
点赞 0
评论 0
private List<Resource> enumerateResourcesFromWebapp(final String line,
final String suffix) throws IOException {
if (line.endsWith("/")) {
ServletContextResourcePatternResolver resourceResolver = new ServletContextResourcePatternResolver(
this.servletContext);
String location = line + "**/*" + suffix;
Resource[] resources = resourceResolver.getResources(location);
return Arrays.asList(resources);
}
if (line.endsWith(suffix)) {
return Collections.singletonList(new ServletContextResource(
this.servletContext, line));
}
return Collections.emptyList();
}
ResourceServlet.java 文件源码
项目:class-guard
阅读 30
收藏 0
点赞 0
评论 0
/**
* Return the file timestamp for the given resource.
* @param resourceUrl the URL of the resource
* @return the file timestamp in milliseconds, or -1 if not determinable
*/
protected long getFileTimestamp(String resourceUrl) {
ServletContextResource resource = new ServletContextResource(getServletContext(), resourceUrl);
try {
long lastModifiedTime = resource.lastModified();
if (logger.isDebugEnabled()) {
logger.debug("Last-modified timestamp of " + resource + " is " + lastModifiedTime);
}
return lastModifiedTime;
}
catch (IOException ex) {
logger.warn("Couldn't retrieve last-modified timestamp of [" + resource +
"] - using ResourceServlet startup time");
return -1;
}
}
ExampleWsClient.java 文件源码
项目:jasig-cas-examples-robertoschwald
阅读 16
收藏 0
点赞 0
评论 0
/**
* Prepare client call
* Uses username/password if set in the bean definition. Otherwise, use the given credentials
* Also prepares the securityConfigResource.
*/
private void configureParameters(UsernamePasswordCredential credential) {
if (this._sConfigResource == null){
this._sConfigResource = new ServletContextResource(servletContext, this.configFilePath);
}
if (StringUtils.isNotBlank(this._wsUsername)) {
// got username/pw from bean definition
this._username = this._wsUsername;
this._password = this._wsPass;
} else {
// get username/pw from credentials.
this._username = credential.getUsername();
this._password = credential.getPassword();
}
// ensure that username is lowercase
if (this._username != null) {
this._username = this._username.trim().toLowerCase();
}
}
StartSyncGTSServlet.java 文件源码
项目:cagrid-core
阅读 18
收藏 0
点赞 0
评论 0
@Override
public void init(ServletConfig config) throws ServletException {
try {
String isSyncGtsAuto = config.getInitParameter("start-auto-syncgts");
log.debug("isSyncGtsAuto "+isSyncGtsAuto);
if (isSyncGtsAuto.equals("true")) {
ServletContextResource contextResource=new ServletContextResource(config.getServletContext(), "/WEB-INF/sync-description.xml");
InputStream inputStream = contextResource.getInputStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
SyncDescription description = (SyncDescription) Utils.deserializeObject(inputStreamReader,SyncDescription.class);
inputStreamReader.close();
SyncGTS.getInstance().syncAndResyncInBackground(description, false);
}
} catch (Exception e) {
log.error("Unable to Start Sync GTS Service." + FaultUtil.printFaultToString(e));
throw new ServletException(e);
}
super.init(config);
}
FilePersistence.java 文件源码
项目:red5-server
阅读 22
收藏 0
点赞 0
评论 0
/**
* Returns the context path.
*
* @param rootFile
* @return context path
*/
private String getContextPath(Resource rootFile) {
String contextPath = null;
if (rootFile instanceof ServletContextResource) {
ServletContextResource servletResource = (ServletContextResource) rootFile;
contextPath = servletResource.getServletContext().getContextPath();
if ("/".equals(contextPath)) {
contextPath = "/root";
}
} else if (resources instanceof IScope) {
contextPath = ((IScope) resources).getContextPath();
if (contextPath == null) {
contextPath = "/root";
}
}
log.debug("Persistence context path: {}", contextPath);
return contextPath;
}
FilePersistence.java 文件源码
项目:red5-server
阅读 19
收藏 0
点赞 0
评论 0
/**
* Initializes the root directory and creates it if it doesn't already exist.
*
* @param rootFile
* @param contextPath
* @throws IOException
*/
private void initRootDir(Resource rootFile, String contextPath) throws IOException {
if (rootFile instanceof ServletContextResource) {
rootDir = String.format("%s/webapps%s", System.getProperty("red5.root"), contextPath);
} else if (resources instanceof IScope) {
rootDir = String.format("%s%s", resources.getResource("/").getFile().getAbsolutePath(), contextPath);
}
log.debug("Persistence directory path: {}", rootDir);
File persistDir = new File(rootDir, path);
if (!persistDir.exists()) {
if (!persistDir.mkdirs()) {
log.warn("Persistence directory creation failed");
} else {
log.debug("Persistence directory access - read: {} write: {}", persistDir.canRead(), persistDir.canWrite());
}
} else {
log.debug("Persistence directory access - read: {} write: {}", persistDir.canRead(), persistDir.canWrite());
}
persistDir = null;
}
ActiveMQContextListener.java 文件源码
项目:t4f-data
阅读 17
收藏 0
点赞 0
评论 0
/**
* Factory method to create a new ActiveMQ Broker
*/
protected BrokerService createBroker(ServletContext context) {
String brokerURI = context.getInitParameter(INIT_PARAM_BROKER_URI);
if (brokerURI == null) {
brokerURI = "activemq.xml";
}
context.log("Loading ActiveMQ Broker configuration from: " + brokerURI);
Resource resource = new ServletContextResource(context, brokerURI);
BrokerFactoryBean factory = new BrokerFactoryBean(resource);
try {
factory.afterPropertiesSet();
} catch (Exception e) {
context.log("Failed to create broker: " + e, e);
}
return factory.getBroker();
}
FrontendController.java 文件源码
项目:oma-riista-web
阅读 29
收藏 0
点赞 0
评论 0
@Override
public String load(final String path) throws Exception {
final org.springframework.core.io.Resource resource = new ServletContextResource(servletContext, path);
try {
byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
return DigestUtils.md5DigestAsHex(content);
} catch (IOException ex) {
LOG.error("Could not calculate MD5 for resource: {}", path);
return runtimeEnvironmentUtil.getRevision();
}
}
PathResourceResolverTests.java 文件源码
项目:spring4-understanding
阅读 14
收藏 0
点赞 0
评论 0
@Test
public void checkServletContextResource() throws Exception {
Resource classpathLocation = new ClassPathResource("test/", PathResourceResolver.class);
MockServletContext context = new MockServletContext();
ServletContextResource servletContextLocation = new ServletContextResource(context, "/webjars/");
ServletContextResource resource = new ServletContextResource(context, "/webjars/webjar-foo/1.0/foo.js");
assertFalse(this.resolver.checkResource(resource, classpathLocation));
assertTrue(this.resolver.checkResource(resource, servletContextLocation));
}
EmbeddedWebApplicationContext.java 文件源码
项目:https-github.com-g0t4-jenkins2-course-spring-boot
阅读 18
收藏 0
点赞 0
评论 0
@Override
protected Resource getResourceByPath(String path) {
if (getServletContext() == null) {
return new ClassPathContextResource(path, getClassLoader());
}
return new ServletContextResource(getServletContext(), path);
}
EmbeddedWebApplicationContext.java 文件源码
项目:spring-boot-concourse
阅读 23
收藏 0
点赞 0
评论 0
@Override
protected Resource getResourceByPath(String path) {
if (getServletContext() == null) {
return new ClassPathContextResource(path, getClassLoader());
}
return new ServletContextResource(getServletContext(), path);
}
EmbeddedWebApplicationContext.java 文件源码
项目:contestparser
阅读 28
收藏 0
点赞 0
评论 0
@Override
protected Resource getResourceByPath(String path) {
if (getServletContext() == null) {
return new ClassPathContextResource(path, getClassLoader());
}
return new ServletContextResource(getServletContext(), path);
}
JspResourceViewResolver.java 文件源码
项目:onetwo
阅读 18
收藏 0
点赞 0
评论 0
protected boolean tryToCheckJspResource(HttpServletRequest request, String viewName){
ServletContext sc = request.getServletContext();
String jsp = getPrefix() + viewName + getSuffix();
ServletContextResource scr = new ServletContextResource(sc, jsp);
if(scr.exists()){
return true;
}
String path = sc.getRealPath(jsp);
if(StringUtils.isBlank(path)){
return false;
}
File jspFile = new File(path);
return jspFile.exists();
}
Velocity2ToolboxView.java 文件源码
项目:demyo
阅读 21
收藏 0
点赞 0
评论 0
@PostConstruct
private void initToolManager() throws IllegalStateException, IOException {
LOGGER.debug("Configuring toolbox from {}", getToolboxConfigLocation());
velocityToolManager = new ViewToolManager(getServletContext(), false, true);
velocityToolManager.setVelocityEngine(getVelocityEngine());
FileFactoryConfiguration factoryConfig = new XmlFactoryConfiguration(false);
factoryConfig.read(new ServletContextResource(getServletContext(), getToolboxConfigLocation()).getURL());
velocityToolManager.configure(factoryConfig);
}
ConfigHelper2.java 文件源码
项目:openyu-commons
阅读 17
收藏 0
点赞 0
评论 0
/**
* 建構目錄
*
* @param defaultDir
* @param resource
*/
protected static void buildDir(String defaultDir, Resource resource, String assignDir) {
try {
// 當沒使用spring注入時,或指定目錄
if (resource == null || assignDir != null) {
File dir = new File(assignDir != null ? assignDir : defaultDir);
FileHelper.md(dir);
}
// 使用spring注入時
else {
// web
// /WEB-INF/xml
// /custom/output
if (resource instanceof ServletContextResource) {
ServletContextResource recource = (ServletContextResource) resource;
// 1./cms/WEB-INF/xml
// 2./cms/custom/output
FileHelper.md(recource.getFile().getAbsolutePath());
}
// file:xml
// xml
// custom/output
else {
URL url = resource.getURL();
if (url != null) {
FileHelper.md(url.getFile());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
ProxyConfigImpl.java 文件源码
项目:OpenSDI-Manager2
阅读 18
收藏 0
点赞 0
评论 0
/**
* Reload proxy configuration reading {@link ProxyConfigImpl#locations}
*/
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");
}
}
SpringSoyViewBaseConfig.java 文件源码
项目:spring-soy-view
阅读 20
收藏 0
点赞 0
评论 0
@Bean
public DefaultTemplateFilesResolver soyTemplateFilesResolver() throws Exception {
final DefaultTemplateFilesResolver defaultTemplateFilesResolver = new DefaultTemplateFilesResolver();
defaultTemplateFilesResolver.setHotReloadMode(hotReloadMode);
defaultTemplateFilesResolver.setRecursive(recursive);
defaultTemplateFilesResolver.setFilesExtension(fileExtension);
defaultTemplateFilesResolver.setTemplatesLocation(new ServletContextResource(servletContext, templatesPath));
return defaultTemplateFilesResolver;
}
ApartmentController.java 文件源码
项目:rento
阅读 17
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/sitemap.xml", method = RequestMethod.GET, produces = "application/xml;charset=UTF-8")
@ResponseBody
public String getSitemap(HttpServletRequest request,Locale locale, Model model) throws IOException {
ServletContextResource resource = new ServletContextResource(context, "/WEB-INF/spring/sitemap.xml");
StringWriter writer = new StringWriter();
IOUtils.copy(resource.getInputStream(), writer, "UTF-8");
return writer.toString();
}
ApartmentController.java 文件源码
项目:rento
阅读 15
收藏 0
点赞 0
评论 0
@RequestMapping(value = "/robots.txt", method = RequestMethod.GET)
@ResponseBody
public String getRobots(HttpServletRequest request,Locale locale, Model model) throws IOException {
ServletContextResource resource = new ServletContextResource(context, "/WEB-INF/spring/robots.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(resource.getInputStream(), writer, "UTF-8");
return writer.toString();
}
FilePersistence.java 文件源码
项目:red5-mobileconsole
阅读 19
收藏 0
点赞 0
评论 0
/**
* Setter for file path.
*
* @param path New path
*/
public void setPath(String path) {
log.debug("Set path: {}", path);
Resource rootFile = resources.getResource(path);
try {
// check for existence
if (!rootFile.exists()) {
log.debug("Persistence directory does not exist");
if (rootFile instanceof ServletContextResource) {
ServletContextResource servletResource = (ServletContextResource) rootFile;
String contextPath = servletResource.getServletContext().getContextPath();
log.debug("Persistence context path: {}", contextPath);
if ("/".equals(contextPath)) {
contextPath = "/root";
}
rootDir = String.format("%s/webapps%s/persistence", System.getProperty("red5.root"), contextPath);
log.debug("Persistence directory path: {}", rootDir);
File persistDir = new File(rootDir);
if (!persistDir.mkdir()) {
log.warn("Persistence directory creation failed");
} else {
log.debug("Persistence directory access - read: {} write: {}", persistDir.canRead(), persistDir.canWrite());
}
persistDir = null;
}
} else {
rootDir = rootFile.getFile().getAbsolutePath();
}
log.debug("Root dir: {} path: {}", rootDir, path);
this.path = path;
} catch (IOException err) {
log.error("I/O exception thrown when setting file path to {}", path, err);
throw new RuntimeException(err);
}
storeThread = FilePersistenceThread.getInstance();
}
BasicSpringResourceSample.java 文件源码
项目:SpringTutorial
阅读 15
收藏 0
点赞 0
评论 0
public static void main(String[] args) throws IOException {
//Resource res=new ClassPathResource("abc2.txt");
//Resource res=new FileSystemResource("src/abc2.txt");
//Resource res=new UrlResource("file:///C:/Trainings/Spring3.0/Chapter1 - CORE/SpringWS/SpringChapter1-CorePartB-Resources/src/abc2.txt");
//Resource res=new UrlResource("http://www.google.com");
InputStream is=new ByteArrayInputStream("testbytesfromastring".getBytes());
Resource res=new InputStreamResource(is,"bais");
MockServletContext msc= new MockServletContext();
Resource resWeb=new ServletContextResource(msc, "org/springframework/core/io/Resource.class");
showFileContent(resWeb.getInputStream());
}
PathResourceResolver.java 文件源码
项目:spring4-understanding
阅读 18
收藏 0
点赞 0
评论 0
private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException {
if (resource.getClass() != location.getClass()) {
return false;
}
String resourcePath;
String locationPath;
if (resource instanceof UrlResource) {
resourcePath = resource.getURL().toExternalForm();
locationPath = StringUtils.cleanPath(location.getURL().toString());
}
else if (resource instanceof ClassPathResource) {
resourcePath = ((ClassPathResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ClassPathResource) location).getPath());
}
else if (resource instanceof ServletContextResource) {
resourcePath = ((ServletContextResource) resource).getPath();
locationPath = StringUtils.cleanPath(((ServletContextResource) location).getPath());
}
else {
resourcePath = resource.getURL().getPath();
locationPath = StringUtils.cleanPath(location.getURL().getPath());
}
if (locationPath.equals(resourcePath)) {
return true;
}
locationPath = (locationPath.endsWith("/") || locationPath.isEmpty() ? locationPath : locationPath + "/");
if (!resourcePath.startsWith(locationPath)) {
return false;
}
if (resourcePath.contains("%")) {
// Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
if (URLDecoder.decode(resourcePath, "UTF-8").contains("../")) {
if (logger.isTraceEnabled()) {
logger.trace("Resolved resource path contains \"../\" after decoding: " + resourcePath);
}
return false;
}
}
return true;
}
ViewResolverTests.java 文件源码
项目:spring4-understanding
阅读 18
收藏 0
点赞 0
评论 0
public void setLocation(Resource location) {
if (!(location instanceof ServletContextResource)) {
throw new IllegalArgumentException("Expecting ClassPathResource, not " + location.getClass().getName());
}
}
ResourceBundleViewResolverTests.java 文件源码
项目:spring4-understanding
阅读 19
收藏 0
点赞 0
评论 0
public void setLocation(Resource location) {
if (!(location instanceof ServletContextResource)) {
throw new IllegalArgumentException("Expecting ServletContextResource, not " + location.getClass().getName());
}
}
TemplateHttpRequestHandler.java 文件源码
项目:java-platform
阅读 38
收藏 0
点赞 0
评论 0
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Supported methods and required session
checkRequest(request);
// Check whether a matching resource exists
Resource resource = getResource(request);
if (resource == null) {
logger.trace("No matching resource found - returning 404");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// Check the resource's media type
MediaType mediaType = getMediaType(resource);
if (mediaType != null) {
if (logger.isTraceEnabled()) {
logger.trace("Determined media type '" + mediaType + "' for " + resource);
}
if (Objects.equal(mediaType, MediaType.TEXT_HTML)) {
WebRender render = new WebRender(beetlConfig.getGroupTemplate());
if (resource instanceof ServletContextResource) {
render.render(((ServletContextResource) resource).getPath(), request, response);
}
return;
}
} else {
if (logger.isTraceEnabled()) {
logger.trace("No media type found for " + resource + " - not sending a content-type header");
}
}
// Header phase
if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
logger.trace("Resource not modified - returning 304");
return;
}
// Apply cache settings, if any
prepareResponse(response);
// Content phase
if (METHOD_HEAD.equals(request.getMethod())) {
setHeaders(response, resource, mediaType);
logger.trace("HEAD request - skipping content");
return;
}
if (request.getHeader(HttpHeaders.RANGE) == null) {
setHeaders(response, resource, mediaType);
writeContent(response, resource);
} else {
writePartialContent(request, response, resource, mediaType);
}
}
IconGenerator.java 文件源码
项目:onecmdb
阅读 22
收藏 0
点赞 0
评论 0
private Map<String, List<Image>> getImageMap() throws IOException {
ServletContextResource imagesRes
= new ServletContextResource(getServletContext(), this.imageDirectory);
File imagesFile = imagesRes.getFile();
final Map<String, List<Image>> images = new TreeMap<String, List<Image>>();
File[] imageFiles = imagesFile.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
FileSystemResource file = new FileSystemResource(new File(dir, name));
for (String ext : exts) {
if (name.toLowerCase().endsWith(ext)) {
try {
BufferedImage img = ImageIO.read(file.getFile());
String key = name.substring(0, name.length() - ext.length());
key = name.substring(0, key.length() - 2);
List<Image> imageList = images.get(key);
if (imageList == null) {
imageList = new ArrayList<Image>(1);
images.put(key, imageList);
}
imageList.add(img);
return true;
} catch (IOException e) {
return false;
}
}
}
return false;
}});
return images;
}
ViewResolverTests.java 文件源码
项目:class-guard
阅读 23
收藏 0
点赞 0
评论 0
public void setLocation(Resource location) {
if (!(location instanceof ServletContextResource)) {
throw new IllegalArgumentException("Expecting ClassPathResource, not " + location.getClass().getName());
}
}