Java Code Examples for org.springframework.web.context.support.ServletContextResource

The following are top voted examples for showing how to use org.springframework.web.context.support.ServletContextResource. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spring4-understanding   File: ResourceServlet.java   View source code 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 2
Project: java-platform   File: ViewConfiguration.java   View source code 6 votes vote down vote up
@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;
}
 
Example 3
Project: java-template-simple   File: VelocityToolboxView.java   View source code 6 votes vote down vote up
@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;
}
 
Example 4
Project: edsutil   File: WebResourceProcessor.java   View source code 6 votes vote down vote up
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();
}
 
Example 5
Project: class-guard   File: ResourceServlet.java   View source code 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example 6
Project: jasig-cas-examples-robertoschwald   File: ExampleWsClient.java   View source code 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example 7
Project: cagrid-core   File: StartSyncGTSServlet.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: red5-server   File: FilePersistence.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: red5-server   File: FilePersistence.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: t4f-data   File: ActiveMQContextListener.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 11
Project: oma-riista-web   File: FrontendController.java   View source code 5 votes vote down vote up
@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();
    }
}
 
Example 12
Project: spring4-understanding   File: PathResourceResolverTests.java   View source code 5 votes vote down vote up
@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));
}
 
Example 13
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: EmbeddedWebApplicationContext.java   View source code 5 votes vote down vote up
@Override
protected Resource getResourceByPath(String path) {
	if (getServletContext() == null) {
		return new ClassPathContextResource(path, getClassLoader());
	}
	return new ServletContextResource(getServletContext(), path);
}
 
Example 14
Project: spring-boot-concourse   File: EmbeddedWebApplicationContext.java   View source code 5 votes vote down vote up
@Override
protected Resource getResourceByPath(String path) {
	if (getServletContext() == null) {
		return new ClassPathContextResource(path, getClassLoader());
	}
	return new ServletContextResource(getServletContext(), path);
}
 
Example 15
Project: contestparser   File: EmbeddedWebApplicationContext.java   View source code 5 votes vote down vote up
@Override
protected Resource getResourceByPath(String path) {
	if (getServletContext() == null) {
		return new ClassPathContextResource(path, getClassLoader());
	}
	return new ServletContextResource(getServletContext(), path);
}
 
Example 16
Project: onetwo   File: JspResourceViewResolver.java   View source code 5 votes vote down vote up
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();
}
 
Example 17
Project: demyo   File: Velocity2ToolboxView.java   View source code 5 votes vote down vote up
@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);
}
 
Example 18
Project: openyu-commons   File: ConfigHelper2.java   View source code 5 votes vote down vote up
/**
 * 建構目錄
 * 
 * @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();
	}
}
 
Example 19
Project: OpenSDI-Manager2   File: ProxyConfigImpl.java   View source code 5 votes vote down vote up
/**
 * 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");
	}
}
 
Example 20
Project: spring-soy-view   File: SpringSoyViewBaseConfig.java   View source code 5 votes vote down vote up
@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;
}
 
Example 21
Project: rento   File: ApartmentController.java   View source code 5 votes vote down vote up
@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();
}
 
Example 22
Project: rento   File: ApartmentController.java   View source code 5 votes vote down vote up
@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();
}
 
Example 23
Project: red5-mobileconsole   File: FilePersistence.java   View source code 5 votes vote down vote up
/**
 * 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();
}
 
Example 24
Project: SpringTutorial   File: BasicSpringResourceSample.java   View source code 4 votes vote down vote up
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());
	
}
 
Example 25
Project: spring4-understanding   File: PathResourceResolver.java   View source code 4 votes vote down vote up
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;
}
 
Example 26
Project: spring4-understanding   File: ViewResolverTests.java   View source code 4 votes vote down vote up
public void setLocation(Resource location) {
	if (!(location instanceof ServletContextResource)) {
		throw new IllegalArgumentException("Expecting ClassPathResource, not " + location.getClass().getName());
	}
}
 
Example 27
Project: spring4-understanding   File: ResourceBundleViewResolverTests.java   View source code 4 votes vote down vote up
public void setLocation(Resource location) {
	if (!(location instanceof ServletContextResource)) {
		throw new IllegalArgumentException("Expecting ServletContextResource, not " + location.getClass().getName());
	}
}
 
Example 28
Project: java-platform   File: TemplateHttpRequestHandler.java   View source code 4 votes vote down vote up
@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);
	}
}
 
Example 29
Project: onecmdb   File: IconGenerator.java   View source code 4 votes vote down vote up
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;
    
}
 
Example 30
Project: class-guard   File: ViewResolverTests.java   View source code 4 votes vote down vote up
public void setLocation(Resource location) {
	if (!(location instanceof ServletContextResource)) {
		throw new IllegalArgumentException("Expecting ClassPathResource, not " + location.getClass().getName());
	}
}
 
Example 31
Project: class-guard   File: ResourceBundleViewResolverTests.java   View source code 4 votes vote down vote up
public void setLocation(Resource location) {
	if (!(location instanceof ServletContextResource)) {
		throw new IllegalArgumentException("Expecting ServletContextResource, not " + location.getClass().getName());
	}
}
 
Example 32
Project: OneCMDBwithMaven   File: IconGenerator.java   View source code 4 votes vote down vote up
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;
    
}
 
Example 33
Project: alf.io   File: TemplateManager.java   View source code 4 votes vote down vote up
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);
}
 
Example 34
Project: onecmdb   File: IconGenerator.java   View source code 2 votes vote down vote up
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);

    
}
 
Example 35
Project: OneCMDBwithMaven   File: IconGenerator.java   View source code 2 votes vote down vote up
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);

    
}