org.apache.velocity.runtime.parser.ParseException Java Examples

The following examples show how to use org.apache.velocity.runtime.parser.ParseException. 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: VelocityTransformer.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
public String transform(String mockGuid, String requestBody, Map<String, Object> context, String stringTemplate) {
    log.debug("transform (requestBody = {}, context = {}, template = {})", requestBody, context, stringTemplate);

    final VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.init();
    final ToolManager toolManager = new ToolManager();
    toolManager.setVelocityEngine(velocityEngine);
    velocityContext = toolManager.createContext();
    if (context != null) {
        context.forEach((k, v) -> velocityContext.put(k, v));
    }
    velocityContext.put("staticContext", staticContext.computeIfAbsent(mockGuid, k -> new HashMap<>()));

    try {
        return render(stringTemplate);
    } catch (ParseException e) {
        log.error("exception while parsing, return exception message", e);
        return e.getMessage();
    }
}
 
Example #2
Source File: CustomVelocityResponseTransformer.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
private String getRenderedBodyFromFile(final ResponseDefinition response) throws ParseException {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    StringReader reader = new StringReader(response.getBody());
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    Template template = new Template();
    template.setEncoding("UTF-8");
    template.setRuntimeServices(runtimeServices);
    template.setData(node);
    template.initDocument();

    StringWriter writer = new StringWriter();
    template.merge(context, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #3
Source File: Define.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Called by the parser to validate the argument types
 */
public void checkArgs(ArrayList<Integer> argtypes,  Token t, String templateName)
throws ParseException
{
  if (argtypes.size() != 1)
  {
      throw new MacroParseException("The #define directive requires one argument",
         templateName, t);
  }

  if (argtypes.get(0) == ParserTreeConstants.JJTWORD)
  {
      throw new MacroParseException("The argument to #define is of the wrong type",
          templateName, t);
  }
}
 
Example #4
Source File: For.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * We do not allow a word token in any other arg position except for the 2nd
 * since we are looking for the pattern #foreach($foo in $bar).
 */
public void checkArgs(ArrayList<Integer> argtypes, Token t,
    String templateName) throws ParseException
{
  super.checkArgs(argtypes, t, templateName);

  // If #foreach is defining an index variable make sure it has the 'index
  // $var' combo.
  if (argtypes.size() > 3)
  {
    if (argtypes.get(3) != ParserTreeConstants.JJTWORD)
    {
      throw new MacroParseException(
          "Expected word 'index' at argument position 4 in #foreach",
          templateName, t);
    }
    else if (argtypes.size() == 4
        || argtypes.get(4) != ParserTreeConstants.JJTREFERENCE)
    {
      throw new MacroParseException(
          "Expected a reference after 'index' in #foreach", templateName, t);
    }
  }
}
 
Example #5
Source File: Foreach.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * We do not allow a word token in any other arg position except for the 2nd since
 * we are looking for the pattern #foreach($foo in $bar).
 */
public void checkArgs(ArrayList<Integer> argtypes,  Token t, String templateName)
  throws ParseException
{
    if (argtypes.size() < 3)
    {
        throw new MacroParseException("Too few arguments to the #foreach directive",
          templateName, t);
    }
    else if (argtypes.get(0) != ParserTreeConstants.JJTREFERENCE)
    {
        throw new MacroParseException("Expected argument 1 of #foreach to be a reference",
            templateName, t);
    }
    else if (argtypes.get(1) != ParserTreeConstants.JJTWORD)
    {
        throw new MacroParseException("Expected word 'in' at argument position 2 in #foreach",
            templateName, t);
    }
    else if (argtypes.get(2) == ParserTreeConstants.JJTWORD)
    {
        throw new MacroParseException("Argument 3 of #foreach is of the wrong type",
            templateName, t);
    }
}
 
Example #6
Source File: Parse.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Called by the parser to validate the argument types
 */
public void checkArgs(ArrayList<Integer> argtypes,  Token t, String templateName)
  throws ParseException
{
    if (argtypes.size() != 1)
    {
        throw new MacroParseException("The #parse directive requires one argument",
           templateName, t);
    }

    if (argtypes.get(0) == ParserTreeConstants.JJTWORD)
    {
        throw new MacroParseException("The argument to #parse is of the wrong type",
            templateName, t);
    }
}
 
Example #7
Source File: AttributesHelper.java    From PackageTemplates with Apache License 2.0 6 votes vote down vote up
public static String[] getUnsetAttributes(FileTemplate fileTemplate, PackageTemplateWrapper ptWrapper) {
    HashSet<String> defaultAttributeNames = getDefaultAttributeNames(ptWrapper.getProject());

    // Add globals vars
    for (GlobalVariable variable : ptWrapper.getPackageTemplate().getListGlobalVariable()) {
        defaultAttributeNames.add(variable.getName());
    }

    Properties properties = new Properties();
    for (String item : defaultAttributeNames) {
        properties.put(item, "fakeValue");
    }

    //parse
    try {
        return fileTemplate.getUnsetAttributes(properties, ptWrapper.getProject());
    } catch (ParseException e) {
        Logger.log("getUnsetAttributes ex: " + e.getMessage());
        Logger.printStack(e);
        return new String[0];
    }
}
 
Example #8
Source File: VelocityTransformer.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
private String render(final String stringTemplate) throws ParseException {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    runtimeServices.setProperty("userdirective", GroovyDirective.class.getName());
    StringReader reader = new StringReader(stringTemplate);
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    Template template = new Template();
    template.setEncoding("UTF-8");
    template.setRuntimeServices(runtimeServices);
    template.setData(node);
    template.initDocument();

    StringWriter writer = new StringWriter();
    template.merge(velocityContext, writer);
    return String.valueOf(writer.getBuffer());
}
 
Example #9
Source File: Break.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called by the parser to validate the argument types
 */
public void checkArgs(ArrayList<Integer> argtypes,  Token t, String templateName)
    throws ParseException
{
    if (argtypes.size() > 1)
    {
        throw new MacroParseException("The #break directive takes only a single, optional Scope argument",
           templateName, t);
    }
}
 
Example #10
Source File: Stop.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called by the parser to check the argument types
 */
public void checkArgs(ArrayList<Integer> argtypes,  Token t, String templateName)
  throws ParseException
{
    int kids = argtypes.size();
    if (kids > 1)
    {
        throw new MacroParseException("The #stop directive only accepts a single message parameter",
           templateName, t);
    }
}
 
Example #11
Source File: RuntimeInstance.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the input and return the root of
 * AST node structure.
 * <br><br>
 *  In the event that it runs out of parsers in the
 *  pool, it will create and let them be GC'd
 *  dynamically, logging that it has to do that.  This
 *  is considered an exceptional condition.  It is
 *  expected that the user will set the
 *  PARSER_POOL_SIZE property appropriately for their
 *  application.  We will revisit this.
 *
 * @param reader Reader retrieved by a resource loader
 * @param template template being parsed
 * @return A root node representing the template as an AST tree.
 * @throws ParseException When the template could not be parsed.
 */
public SimpleNode parse(Reader reader, Template template)
    throws ParseException
{
    requireInitialization();

    Parser parser = parserPool.get();
    boolean keepParser = true;
    if (parser == null)
    {
        /*
         *  if we couldn't get a parser from the pool make one and log it.
         */
        log.info("Runtime: ran out of parsers. Creating a new one. "
                 + " Please increment the parser.pool.size property."
                 + " The current value is too small.");
        parser = createNewParser();
        keepParser = false;
    }

    try
    {
        return parser.parse(reader, template);
    }
    finally
    {
        if (keepParser)
        {
            /* drop the parser Template reference to allow garbage collection */
            parser.resetCurrentTemplate();
            parserPool.put(parser);
        }

    }
}
 
Example #12
Source File: ParseErrorException.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Create a ParseErrorException with the given ParseException.
 *
 * @param pex the parsing exception
 * @param templName
 * @since 1.5
 */
public ParseErrorException(VelocityException pex, String templName)
{
    super(pex.getMessage());

    if (templName != null) templateName = templName;

    // Don't use a second C'tor, TemplateParseException is a subclass of
    // ParseException...
    if (pex instanceof ExtendedParseException)
    {
        ExtendedParseException xpex = (ExtendedParseException) pex;

        columnNumber = xpex.getColumnNumber();
        lineNumber = xpex.getLineNumber();
        templateName = xpex.getTemplateName();
    }
    else if (pex.getCause() instanceof ParseException)
    {
        ParseException pex2 = (ParseException) pex.getCause();

        if (pex2.currentToken != null && pex2.currentToken.next != null)
        {
            columnNumber = pex2.currentToken.next.beginColumn;
            lineNumber = pex2.currentToken.next.beginLine;
        }
    }
}
 
Example #13
Source File: TemplateInitException.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param msg
 * @param parseException
 * @param templateName
 * @param col
 * @param line
 */
public TemplateInitException(final String msg, ParseException parseException,
        final String templateName, final int col, final int line)
{
    super(msg,parseException);
    this.templateName = templateName;
    this.col = col;
    this.line = line;
}
 
Example #14
Source File: FileTemplateUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static String[] calculateAttributes(String templateContent, Set<String> propertiesNames, boolean includeDummies, Project project) throws ParseException {
  final Set<String> unsetAttributes = new LinkedHashSet<>();
  final Set<String> definedAttributes = new HashSet<>();
  SimpleNode template = VelocityWrapper.parse(new StringReader(templateContent), "MyTemplate");
  collectAttributes(unsetAttributes, definedAttributes, template, propertiesNames, includeDummies, new HashSet<>(), project);
  for (String definedAttribute : definedAttributes) {
    unsetAttributes.remove(definedAttribute);
  }
  return ArrayUtil.toStringArray(unsetAttributes);
}
 
Example #15
Source File: FileTemplateUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Deprecated
@DeprecationInfo("Use #calculateAttributes with Map parameter")
public static String[] calculateAttributes(String templateContent, Properties properties, boolean includeDummies, Project project) throws ParseException {
  Set<String> propertiesNames = new HashSet<>();
  for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
    propertiesNames.add((String)e.nextElement());
  }
  return calculateAttributes(templateContent, propertiesNames, includeDummies, project);
}
 
Example #16
Source File: CreateFromTemplateDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CreateFromTemplateDialog(@Nonnull PsiDirectory directory,
                                @Nonnull FileTemplate template,
                                @Nullable final AttributesDefaults attributesDefaults,
                                @Nullable final Map<String, Object> defaultProperties) {
  super(directory.getProject(), true);
  myDirectory = directory;
  myProject = directory.getProject();
  myTemplate = template;
  setTitle(IdeBundle.message("title.new.from.template", template.getName()));

  myDefaultProperties = defaultProperties == null ? FileTemplateManager.getInstance(myProject).getDefaultVariables() : defaultProperties;
  FileTemplateUtil.fillDefaultProperties(myDefaultProperties, directory);
  boolean mustEnterName = FileTemplateUtil.findHandler(template).isNameRequired();
  if (attributesDefaults != null && attributesDefaults.isFixedName()) {
    myDefaultProperties.put(FileTemplate.ATTRIBUTE_NAME, attributesDefaults.getDefaultFileName());
    mustEnterName = false;
  }

  String[] unsetAttributes = null;
  try {
    unsetAttributes = myTemplate.getUnsetAttributes(myDefaultProperties, myProject);
  }
  catch (ParseException e) {
    showErrorDialog(e);
  }

  if (unsetAttributes != null) {
    myAttrPanel = new CreateFromTemplatePanel(unsetAttributes, mustEnterName, attributesDefaults);
    myAttrComponent = myAttrPanel.getComponent();
    init();
  }
  else {
    myAttrPanel = null;
    myAttrComponent = null;
  }
}
 
Example #17
Source File: TemplateVars.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForResource(String templateStr, String resourceName) {
  try {
    return velocityRuntimeInstance.parse(templateStr, resourceName);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #18
Source File: VelocityUtils.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
public static Template create(String source, String templateName) throws ParseException {
  RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
  StringReader reader = new StringReader(source);
  SimpleNode node = runtimeServices.parse(reader, templateName);
  Template template = new Template();
  template.setRuntimeServices(runtimeServices);
  template.setData(node);
  template.initDocument();
  return template;
}
 
Example #19
Source File: AlarmDeduplicationProcessor.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void init(AlarmDeduplicationProcessorConfiguration configuration) {
  this.configuration = configuration;
  try {
    this.alarmIdTemplate = VelocityUtils.create(configuration.getAlarmIdTemplate(), "Alarm Id Template");
    this.alarmBodyTemplate = VelocityUtils.create(configuration.getAlarmBodyTemplate(), "Alarm Body Template");
  } catch (ParseException e) {
    log.error("Failed to create templates based on provided configuration!", e);
    throw new RuntimeException("Failed to create templates based on provided configuration!", e);
  }
}
 
Example #20
Source File: SendMailAction.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void init(SendMailActionConfiguration configuration) {
  this.configuration = configuration;
  try {
    fromTemplate = toTemplate(configuration.getFromTemplate(), "From Template");
    toTemplate = toTemplate(configuration.getToTemplate(), "To Template");
    ccTemplate = toTemplate(configuration.getCcTemplate(), "Cc Template");
    bccTemplate = toTemplate(configuration.getBccTemplate(), "Bcc Template");
    subjectTemplate = toTemplate(configuration.getSubjectTemplate(), "Subject Template");
    bodyTemplate = toTemplate(configuration.getBodyTemplate(), "Body Template");
  } catch (ParseException e) {
    log.error("Failed to create templates based on provided configuration!", e);
    throw new RuntimeException("Failed to create templates based on provided configuration!", e);
  }
}
 
Example #21
Source File: SendMailAction.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
private Optional<Template> toTemplate(String source, String name) throws ParseException {
  if (!StringUtils.isEmpty(source)) {
    return Optional.of(VelocityUtils.create(source, name));
  } else {
    return Optional.empty();
  }
}
 
Example #22
Source File: AbstractTemplatePluginAction.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@Override
public void init(T configuration) {
  this.configuration = configuration;
  try {
    this.template = VelocityUtils.create(configuration.getTemplate(), "Template");
  } catch (ParseException e) {
    throw new RuntimeException(e.getMessage(), e);
  }
}
 
Example #23
Source File: TemplateVars.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForResource(String templateStr, String resourceName) {
  try {
    return velocityRuntimeInstance.parse(templateStr, resourceName);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #24
Source File: TemplateVarsTest.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForString(String string) {
  try {
    Reader reader = new StringReader(string);
    return RuntimeSingleton.parse(reader, string);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #25
Source File: TemplateVars.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForResource(String templateStr, String resourceName) {
  try {
    return velocityRuntimeInstance.parse(templateStr, resourceName);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #26
Source File: TemplateVarsTest.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForString(String string) {
  try {
    Reader reader = new StringReader(string);
    return RuntimeSingleton.parse(reader, string);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #27
Source File: TemplateVarsTest.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
static SimpleNode parsedTemplateForString(String string) {
  try {
    Reader reader = new StringReader(string);
    return RuntimeSingleton.parse(reader, string);
  } catch (ParseException e) {
    throw new AssertionError(e);
  }
}
 
Example #28
Source File: ParseErrorException.java    From velocity-engine with Apache License 2.0 4 votes vote down vote up
/**
 * Create a ParseErrorException with the given ParseException.
 *
 * @param pex the parsing exception
 * @param templName
 * @since 1.5
 */
public ParseErrorException(ParseException pex, String templName)
{
    super(pex.getMessage());

    if (templName != null) templateName = templName;

    // Don't use a second C'tor, TemplateParseException is a subclass of
    // ParseException...
    if (pex instanceof ExtendedParseException)
    {
        ExtendedParseException xpex = (ExtendedParseException) pex;

        columnNumber = xpex.getColumnNumber();
        lineNumber = xpex.getLineNumber();
        templateName = xpex.getTemplateName();
    }
    else
    {
        // We get here if the the Parser has thrown an exception. Unfortunately,
        // the error message created is hard coded by javacc, so here we alter
        // the error message, so that it is in our standard format.
        Matcher match =  lexError.matcher(pex.getMessage());
        if (match.matches())
        {
           lineNumber = Integer.parseInt(match.group(1));
           columnNumber = Integer.parseInt(match.group(2));
           String restOfMsg = match.group(3);
           msg = "Lexical error, " + restOfMsg + " at "
             + StringUtils.formatFileString(templateName, lineNumber, columnNumber);
        }

        //  ugly, ugly, ugly...

        if (pex.currentToken != null && pex.currentToken.next != null)
        {
            columnNumber = pex.currentToken.next.beginColumn;
            lineNumber = pex.currentToken.next.beginLine;
        }
    }
}
 
Example #29
Source File: FileTemplate.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Deprecated
@DeprecationInfo("getUnsetAttributes")
String[] getUnsetAttributes(@Nonnull Properties properties, Project project) throws ParseException;
 
Example #30
Source File: VelocityWrapper.java    From consulo with Apache License 2.0 4 votes vote down vote up
static SimpleNode parse(Reader reader, String templateName) throws ParseException {
  Template template = new Template();
  template.setName(templateName);
  return RuntimeSingleton.parse(reader, template);
}