/** * 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; } }
@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; }
@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; }
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(); }
/** * 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(); } }
@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); }
/** * 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; }
/** * 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; }
/** * 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(); }
@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(); } }
@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)); }
@Override protected Resource getResourceByPath(String path) { if (getServletContext() == null) { return new ClassPathContextResource(path, getClassLoader()); } return new ServletContextResource(getServletContext(), path); }
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(); }
@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); }
/** * 建構目錄 * * @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(); } }
/** * 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"); } }
@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; }
@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(); }
@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(); }
/** * 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(); }
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()); }
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; }
public void setLocation(Resource location) { if (!(location instanceof ServletContextResource)) { throw new IllegalArgumentException("Expecting ClassPathResource, not " + location.getClass().getName()); } }
public void setLocation(Resource location) { if (!(location instanceof ServletContextResource)) { throw new IllegalArgumentException("Expecting ServletContextResource, not " + location.getClass().getName()); } }
@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); } }
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; }
public String renderServletContextResource(String servletContextResource, Map<String, Object> model, HttpServletRequest request, TemplateOutput templateOutput) { model.put("request", request); model.put(WebSecurityConfig.CSRF_PARAM_NAME, request.getAttribute(CsrfToken.class.getName())); return render(new ServletContextResource(request.getServletContext(), servletContextResource), model, RequestContextUtils.getLocale(request), templateOutput); }
public ModelAndView addHandler(HttpServletRequest request, HttpServletResponse respone, IconOptionsCommand optionsCommand) throws IOException { HashMap<String, Object> data = new HashMap<String, Object>(); ServletContextResource depot = new ServletContextResource(getServletContext(), this.imageDirectory); String imageid = optionsCommand.getIconid(); if (imageid != null) { final ByteArrayInputStream in = new ByteArrayInputStream(optionsCommand.getIconData()); final BufferedImage image = ImageIO.read(in); for (double f = 16.0; f <= 48.0; f += 16) { Image scaled = image.getScaledInstance((int) f, (int) f, java.awt.Image.SCALE_AREA_AVERAGING); BufferedImage scaledImage = toBufferedImage(scaled); final File file = new File(depot.getFile(), imageid + ((int) f) + ".png"); ImageIO.write(scaledImage, "png", file); } data.put("successful", true); } return new ModelAndView("imageAdd", "imageAdd", data); }