org.apache.velocity.exception.ResourceNotFoundException Java Examples

The following examples show how to use org.apache.velocity.exception.ResourceNotFoundException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ASTBlock.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException, MethodInvocationException,
    	ResourceNotFoundException, ParseErrorException
{
    SpaceGobbling spaceGobbling = rsvc.getSpaceGobbling();

    if (spaceGobbling == SpaceGobbling.NONE)
    {
        writer.write(prefix);
    }

    int i, k = jjtGetNumChildren();

    for (i = 0; i < k; i++)
        jjtGetChild(i).render(context, writer);

    if (morePostfix.length() > 0 || spaceGobbling.compareTo(SpaceGobbling.LINES) < 0)
    {
        writer.write(postfix);
    }

    writer.write(morePostfix);

    return true;
}
 
Example #2
Source File: SpringResourceLoader.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getResourceStream(String source) throws ResourceNotFoundException {
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for Velocity resource with name [" + source + "]");
	}
	for (String resourceLoaderPath : this.resourceLoaderPaths) {
		org.springframework.core.io.Resource resource =
				this.resourceLoader.getResource(resourceLoaderPath + source);
		try {
			return resource.getInputStream();
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not find Velocity resource: " + resource);
			}
		}
	}
	throw new ResourceNotFoundException(
			"Could not find resource [" + source + "] in Spring resource loader path");
}
 
Example #3
Source File: Page.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Renders the template and writes the output to the given file.
 *
 * Strips all trailing whitespace before writing to file.
 */
public void write(File outputFile) throws IOException {
  StringWriter stringWriter = new StringWriter();
  try {
    engine.mergeTemplate(template, "UTF-8", context, stringWriter);
  } catch (ResourceNotFoundException|ParseErrorException|MethodInvocationException e) {
    throw new IOException(e);
  }
  stringWriter.close();

  String[] lines = stringWriter.toString().split(System.getProperty("line.separator"));
  try (Writer fileWriter = Files.newBufferedWriter(outputFile.toPath(), UTF_8)) {
    for (String line : lines) {
      // Strip trailing whitespace then append newline before writing to file.
      fileWriter.write(line.replaceFirst("\\s+$", "") + "\n");
    }
  }
}
 
Example #4
Source File: EagleMailClient.java    From eagle with Apache License 2.0 6 votes vote down vote up
public boolean send(String from, String to, String cc, String title,
                    String templatePath, VelocityContext context) {
    Template t = null;
    try {
        t = velocityEngine.getTemplate(BASE_PATH + templatePath);
    } catch (ResourceNotFoundException ex) {
        // ignored
    }
    if (t == null) {
        try {
            t = velocityEngine.getTemplate(templatePath);
        } catch (ResourceNotFoundException e) {
            t = velocityEngine.getTemplate("/" + templatePath);
        }
    }
    final StringWriter writer = new StringWriter();
    t.merge(context, writer);
    if (LOG.isDebugEnabled()) {
        LOG.debug(writer.toString());
    }

    return this.send(from, to, cc, title, writer.toString());
}
 
Example #5
Source File: EagleMailClient.java    From eagle with Apache License 2.0 6 votes vote down vote up
public boolean send(String from, String to, String cc, String title,
                    String templatePath, VelocityContext context) {
    Template t = null;
    try {
        t = velocityEngine.getTemplate(BASE_PATH + templatePath);
    } catch (ResourceNotFoundException ex) {
        // ignored
    }
    if (t == null) {
        try {
            t = velocityEngine.getTemplate(templatePath);
        } catch (ResourceNotFoundException e) {
            t = velocityEngine.getTemplate("/" + templatePath);
        }
    }
    final StringWriter writer = new StringWriter();
    t.merge(context, writer);
    if (LOG.isDebugEnabled()) {
        LOG.debug(writer.toString());
    }

    return this.send(from, to, cc, title, writer.toString());
}
 
Example #6
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a markdown rendering of provider documentation for the given provider information
 * object with the given name.
 */
public String render(String providerName, ProviderInfo providerInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("providerName", providerName);
  context.put("providerInfo", providerInfo);

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(providerTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, providerTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #7
Source File: SpringResourceLoader.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getResourceStream(String source) throws ResourceNotFoundException {
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for Velocity resource with name [" + source + "]");
	}
	for (String resourceLoaderPath : this.resourceLoaderPaths) {
		org.springframework.core.io.Resource resource =
				this.resourceLoader.getResource(resourceLoaderPath + source);
		try {
			return resource.getInputStream();
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not find Velocity resource: " + resource);
			}
		}
	}
	throw new ResourceNotFoundException(
			"Could not find resource [" + source + "] in Spring resource loader path");
}
 
Example #8
Source File: LocalizedTemplateResourceLoaderImpl.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
protected Language readTemplateLanguage(final String templateName) {
    if (StringUtils.isEmpty(templateName)) {
        throw new ResourceNotFoundException("DataSourceResourceLoader: Template name was empty or null");
    }
    Matcher matcher = SOURCE_NAME_PATTERN.matcher(templateName);
    String languageStr = null;
    if (matcher.matches()) {
        languageStr = matcher.group("language");
    } else {
        throw new ResourceNotFoundException("Template name not valid. Pattern: templateId(/lang)?");
    }

    Language language = null;
    if (StringUtils.isNotBlank(languageStr)) {
        language = Language.valueOf(languageStr);
        if (language == null) {
            throw new ResourceNotFoundException("Language not supported");
        }
    }
    return language;
}
 
Example #9
Source File: RegistryBasedResourceLoader.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Override
public InputStream getResourceStream(String name) throws ResourceNotFoundException {
    try {
        Registry registry =
                CarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType.SYSTEM_CONFIGURATION);
        if (registry == null) {
            throw new IllegalStateException("No valid registry instance is attached to the current carbon context");
        }
        if (!registry.resourceExists(EMAIL_CONFIG_BASE_LOCATION + "/" + name)) {
            throw new ResourceNotFoundException("Resource '" + name + "' does not exist");
        }
        org.wso2.carbon.registry.api.Resource resource =
                registry.get(EMAIL_CONFIG_BASE_LOCATION + "/" + name);
        resource.setMediaType("text/plain");
        return resource.getContentStream();
    } catch (RegistryException e) {
        throw new ResourceNotFoundException("Error occurred while retrieving resource", e);
    }
}
 
Example #10
Source File: ServletContextLoader.java    From ApprovalTests.Java with Apache License 2.0 6 votes vote down vote up
/**
 * Get an InputStream so that the Runtime can build a
 * template with it.
 *
 * @param name name of template to get
 * @return InputStream containing the template
 * @throws ResourceNotFoundException if template not found
 *         in  classpath.
 */
public synchronized InputStream getResourceStream(String name) throws ResourceNotFoundException
{
  if (name == null || name.length() == 0) { return null;}
  /* since the paths always ends in '/',
   * make sure the name never ends in one */
  while (name.startsWith("/"))
  {
    name = name.substring(1);
  }
  for (int i = 0; i < paths.length; i++)
  {
    InputStream result = null;
    result = servletContext.getResourceAsStream(paths[i] + name);
    if (result != null)
    {
      /* exit the loop if we found the template */
      return result;
    }
  }
  throw new ResourceNotFoundException(String.format("Template '%s' not found from %s", name, Arrays.asList(paths)));
}
 
Example #11
Source File: Split.java    From CodeGen with MIT License 6 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String value = (String) node.jjtGetChild(0).value(context);
    String character = (String) node.jjtGetChild(1).value(context);
    int len = value.length();
    StringBuilder sb = new StringBuilder(len);
    sb.append(value.charAt(0));
    for (int i = 1; i < len; i++) {
        char c = value.charAt(i);
        if (Character.isUpperCase(c)) {
            sb.append(character).append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }
    writer.write(sb.toString());
    return true;
}
 
Example #12
Source File: HtmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
try {
	writer.write(htmlCompressor.compress(content.toString()));
} catch (Exception e) {
	writer.write(content.toString());
	String msg = "Failed to compress content: "+content.toString();
          log.error(msg, e);
          throw new RuntimeException(msg, e);
          
}
return true;
  	
  }
 
Example #13
Source File: SpringResourceLoader.java    From scoold with Apache License 2.0 6 votes vote down vote up
@Override
public Reader getResourceReader(String source, String encoding) throws ResourceNotFoundException {
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for Velocity resource with name [" + source + "]");
	}
	for (String resourceLoaderPath : this.resourceLoaderPaths) {
		org.springframework.core.io.Resource resource =
				this.resourceLoader.getResource(resourceLoaderPath + source);
		try {
			return new InputStreamReader(resource.getInputStream());
		} catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not find Velocity resource: " + resource);
			}
		}
	}
	throw new ResourceNotFoundException(
			"Could not find resource [" + source + "] in Spring resource loader path");
}
 
Example #14
Source File: SpringResourceLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public InputStream getResourceStream(String source) throws ResourceNotFoundException {
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for Velocity resource with name [" + source + "]");
	}
	for (String resourceLoaderPath : this.resourceLoaderPaths) {
		org.springframework.core.io.Resource resource =
				this.resourceLoader.getResource(resourceLoaderPath + source);
		try {
			return resource.getInputStream();
		}
		catch (IOException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Could not find Velocity resource: " + resource);
			}
		}
	}
	throw new ResourceNotFoundException(
			"Could not find resource [" + source + "] in Spring resource loader path");
}
 
Example #15
Source File: VelocityViewServlet.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Manages the {@link ResourceNotFoundException} to send an HTTP 404 result
 * when needed.
 *
 * @param request The request object.
 * @param response The response object.
 * @param e The exception to check.
 * @throws IOException If something goes wrong when sending the HTTP error.
 */
protected void manageResourceNotFound(HttpServletRequest request,
        HttpServletResponse response, ResourceNotFoundException e)
        throws IOException
{
    String path = ServletUtils.getPath(request);
    getLog().debug("Resource not found for path '{}'", path, e);
    String message = e.getMessage();
    if (!response.isCommitted() && path != null &&
        message != null && message.contains("'" + path + "'"))
    {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, path);
    }
    else
    {
        error(request, response, e);
        throw e;
    }
}
 
Example #16
Source File: URLResourceLoader.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see when a resource was last modified
 *
 * @param resource Resource the resource to check
 * @return long The time when the resource was last modified or 0 if the file can't be reached
 */
public long getLastModified(Resource resource)
{
    // get the previously used root
    String name = resource.getName();
    String root = (String)templateRoots.get(name);

    try
    {
        // get a connection to the URL
        URL u = new URL(root + name);
        URLConnection conn = u.openConnection();
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        return conn.getLastModified();
    }
    catch (IOException ioe)
    {
        // the file is not reachable at its previous address
        String msg = "URLResourceLoader: '"+name+"' is no longer reachable at '"+root+"'";
        log.error(msg, ioe);
        throw new ResourceNotFoundException(msg, ioe, rsvc.getLogContext().getStackTrace());
    }
}
 
Example #17
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a markdown rendering of a user-defined function's documentation for the function info
 * object.
 */
public String render(StarlarkFunctionInfo functionInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("funcInfo", functionInfo);

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(functionTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, functionTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #18
Source File: VelocityBodyContentTest.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.VelocityBodyContent#getReader()}.
 * @throws IOException If something goes wrong.
 * @throws ParseErrorException If something goes wrong.
 * @throws ResourceNotFoundException If something goes wrong.
 * @throws MethodInvocationException If something goes wrong.
 */
@Test
public void testGetReader() throws MethodInvocationException, ResourceNotFoundException, ParseErrorException, IOException
{
    expect(block.render(eq(context), isA(StringWriter.class))).andReturn(true);
    replay(jspWriter, block, context);
    assertNotNull(content.getReader());
    verify(jspWriter, block, context);
}
 
Example #19
Source File: FileFactoryConfiguration.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
public void read(String path, boolean required, Logger log)
{
    if (path == null)
    {
        throw new NullPointerException("Path value cannot be null");
    }
    if (log != null && log.isTraceEnabled())
    {
        log.trace("Attempting to read configuration file at: {}", path);
    }

    URL url = findURL(path);
    if (url != null)
    {
        read(url, required, log);
    }
    else
    {
        String msg = "Could not find configuration file at: "+path;
        if (log != null)
        {
            log.debug(msg);
        }
        if (required)
        {
            throw new ResourceNotFoundException(msg);
        }
    }
}
 
Example #20
Source File: VelocityJspFragmentTest.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.VelocityJspFragment#invoke(java.io.Writer)}.
 * @throws IOException If something goes wrong.
 * @throws ParseErrorException If something goes wrong.
 * @throws ResourceNotFoundException If something goes wrong.
 * @throws MethodInvocationException If something goes wrong.
 * @throws JspException If something goes wrong.
 */
@Test
public void testInvokeWriter() throws MethodInvocationException, ResourceNotFoundException, ParseErrorException, IOException, JspException
{
    PageContext pageContext = createMock(PageContext.class);
    ASTBlock block = createMock(ASTBlock.class);
    InternalContextAdapter context = createMock(InternalContextAdapter.class);
    Writer writer = createMock(Writer.class);
    expect(block.render(context, writer)).andReturn(true);

    replay(pageContext, block, context, writer);
    VelocityJspFragment fragment = new VelocityJspFragment(pageContext, block, context);
    fragment.invoke(writer);
    verify(pageContext, block, context, writer);
}
 
Example #21
Source File: SecureIntrospectionTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
private boolean doesStringEvaluate(VelocityEngine ve, Context c, String inputString) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException
{
	// assume that an evaluation is bad if the input and result are the same (e.g. a bad reference)
	// or the result is an empty string (e.g. bad #foreach)
	Writer w = new StringWriter();
    ve.evaluate(c, w, "foo", inputString);
    String result = w.toString();
    return (result.length() > 0 ) &&  !result.equals(inputString);
}
 
Example #22
Source File: VelocityTemplateProcessor.java    From mobile-persistence with MIT License 5 votes vote down vote up
/**
 * Get a template from the cache; if template has not been loaded, load it
 *
 * @param templatePath
 * @return
 */
private Template getTemplate(final String templatePath)
  throws ResourceNotFoundException, ParseErrorException, Exception
{
  VelocityEngine ve = velocityInitializer.getVelocityEngine();
  return ve.getTemplate(templatePath);
}
 
Example #23
Source File: VelocityBodyContentTest.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.VelocityBodyContent#writeOut(java.io.Writer)}.
 * @throws IOException If something goes wrong.
 * @throws ParseErrorException If something goes wrong.
 * @throws ResourceNotFoundException If something goes wrong.
 * @throws MethodInvocationException If something goes wrong.
 */
@Test
public void testWriteOutWriter() throws MethodInvocationException, ResourceNotFoundException, ParseErrorException, IOException
{
    Writer writer = createMock(Writer.class);
    expect(block.render(context, writer)).andReturn(true);
    replay(jspWriter, block, context, writer);
    content.writeOut(writer);
    verify(jspWriter, block, context, writer);
}
 
Example #24
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a markdown header string that should appear at the top of Stardoc's output, providing a
 * summary for the input Starlark module.
 */
public String renderMarkdownHeader(ModuleInfo moduleInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("moduleDocstring", moduleInfo.getModuleDocstring());

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(headerTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, headerTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #25
Source File: TestClasspathResourceLoader.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Override
public synchronized InputStream getResourceStream(String arg0) throws ResourceNotFoundException
{
	InputStream in =  super.getResourceStream(arg0);
	if ( in == null ) {
		in =  this.getClass().getResourceAsStream(arg0);
	}
	if ( in == null ) {
		log.error("Failed to load "+arg0);
	}
	return in;
}
 
Example #26
Source File: TrimExtDirective.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Params getParams(final InternalContextAdapter context, final Node node) throws IOException,
        ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    final Params params = new Params();
    final int nodes = node.jjtGetNumChildren();
    for (int i = 0; i < nodes; i++) {
        Node child = node.jjtGetChild(i);
        if (child != null) {
            if (!(child instanceof ASTBlock)) {
                if (i == 0) {
                    params.setPrefix(String.valueOf(child.value(context)));
                } else if (i == 1) {
                    params.setPrefixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
                } else if (i == 2) {
                    params.setSuffix(String.valueOf(child.value(context)));
                } else if (i == 3) {
                    params.setSuffixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
                } else {
                    break;
                }
            } else {
                StringWriter blockContent = new StringWriter();
                child.render(context, blockContent);
                if ("".equals(blockContent.toString().trim())) {
                    return null;
                }
                params.setBody(blockContent.toString().trim());
                break;
            }
        }
    }
    return params;
}
 
Example #27
Source File: TrimExtDirective.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public final boolean render(InternalContextAdapter ica, Writer writer, Node node) throws IOException,
        ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    Params p = getParams(ica, node);
    if (p == null) {
        return false;
    } else {
        return render(p, writer);
    }
}
 
Example #28
Source File: ClasspathPathResourceLoader.java    From oxTrust with MIT License 5 votes vote down vote up
/**
 * Get a Reader so that the Runtime can build a template with it.
 *
 * @param name     name of template to get
 * @param encoding asked encoding
 * @return InputStream containing the template
 * @throws ResourceNotFoundException if template not found in classpath.
 * @since 2.0
 */
public Reader getResourceReader(String templateName, String encoding) throws ResourceNotFoundException {
	Reader result = null;

	if (StringUtils.isEmpty(templateName)) {
		throw new ResourceNotFoundException("No template name provided");
	}

	for (String path : paths) {
		InputStream rawStream = null;
		try {
			rawStream = ClassUtils.getResourceAsStream(getClass(), path + "/" + templateName);
			if (rawStream != null) {
				result = buildReader(rawStream, encoding);
				if (result != null) {
					break;
				}
			}
		} catch (Exception fnfe) {
			if (rawStream != null) {
				try {
					rawStream.close();
				} catch (IOException ioe) {
				}
			}
			throw new ResourceNotFoundException("ClasspathResourceLoader problem with template: " + templateName, fnfe);
		}
	}

	if (result == null) {
		String msg = "ClasspathResourceLoader Error: cannot find resource " + templateName;

		throw new ResourceNotFoundException(msg);
	}

	return result;
}
 
Example #29
Source File: JesterJLoader.java    From jesterj with Apache License 2.0 5 votes vote down vote up
@Override
protected URL findResource(String name) {
  try {
    return (URL) callParentMethod("findResource", new Class[]{String.class}, name);
  } catch (ClassNotFoundException e) {
    // should not be possible
    throw new ResourceNotFoundException(e.getMessage());
  }
}
 
Example #30
Source File: TemplateEngineUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public InputStream getResourceStream(String source) throws ResourceNotFoundException {
   try {
      return ConnectorIOUtils.getResourceAsStream(source);
   } catch (TechnicalConnectorException var3) {
      throw new ResourceNotFoundException(var3);
   }
}