Re: #foreach($i in [1..$n]) causes exception
On 05/30/2011 08:36 PM, Robert Lee wrote: I have tried #set($n = 2) #set($range = [1..$n]) #foreach($i in $range) as well Velocity 1.7 fails when it reaches the range variable in the #foreach directive. Is there a way to accomplish what I am trying to do, (a variable count loop) in velocity? The error is that you're not actually iterating over a range, but trying to iterate over a string. #set($range = [1..$n]) = $range is a String #foreach($i in $range) = $range is still a String, it won't be replaced with [1..$n] This should work: #set($n = 2) #foreach($i in [1..$n]) If you must define the range somewhere else as a string, you can use #evaluate to dynamically interpret the range, but that adds unneeded complexity. -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Does velocity provide these features?
On 06/01/2011 03:40 PM, Moe221 wrote: Hi there, i'm evaluating Velocity to find out whether it meets my requirements to generate text by using custom templates. I looked at the user guide and wrote a little hello world application but there are requirements for which I don't know if I have to write my own methods or if there are velocity tools that would do the job for me: Is there a way to automatically add line breaks when you merge the template with the context (without cutting words after e.g. 80 characters)? Is there a way to use text shifting (indentation) in combination with line breaks without cutting words after e.g. 80 characters)? Long text: $magic.doMagic( $text ) -- Long text: Some very Very long text, more text … Is there a way to automatically add line breaks (without cutting words after e.g. 80 characters) and add a certain String (e.g. 100. ) at the beginning of each line: Funny Velocity user request: $magic.doMagic2( $text ) -- Funny Velocity user request: this 100. is just a test, a test, a test, a 100. test, a test … Is there a way to cut the string of a variable after 9 characters and add a * to the string, if the string has more than 10 characters? #set( $test = textwithmorethan10char ) Test: $magic.doMagic3( $test) -- Test: textwithm* Thanx in advance! Natively, no, this is not the job of the velocity core. But it would be fairly simple to write a velocity tool that does that for you, similar to http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/DisplayTool.html DisplayTool does have a method for your last request, see http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/DisplayTool.html#truncate%28java.lang.Object,%20int,%20java.lang.String,%20boolean%29 You will have to enable the tools, then you would have to write: $displaytool.truncate($test, 10, '*', false) Alternatively, you can do that as well directly in the template, but it would be a bit harder since you don't have all the power of Java. For example, line numbering has been done in: https://github.com/xwiki/xwiki-platform/raw/master/xwiki-platform-core/xwiki-platform-web/src/main/webapp/templates/code.vm -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: String to Number/Integer
On 07/05/2011 11:09 AM, LaStudent wrote: Hello, is it possible to convert a String to a Number? something like this: #set($tmpStr = 14) #set($tmpInt = parseInt($tmpStr)) best regards Not directly, but there's a tool for that: http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/ConversionTool.html#toInteger%28java.lang.Object%29 -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Velocity to fetch full docs?
On 09/26/2011 10:56 AM, Nathan Bubna wrote: Definitely for a question for the Nutch or Solr lists. Velocity is a simple template engine and knows nothing about Nutch or Solr that it isn't told about. Indeed, Velocity is a very simple template engine, with no smart APIs provided by the engine alone. What you need to do is to put in the context some data objects holding the instance data you're currently processing (or even just the servlet request and response objects to get access to the request parameters), and some smart objects that can contact Solr, Nutch and your other nonSolr services. You'd have to write these yourself in Java, and put instances in the velocity context before parsing. Another approach is to put enough low level services to allow you to implement the whole logic inside a Velocity template, like a HTTP client, XML processing library, the escape tool, etc. On Mon, Sep 26, 2011 at 5:17 AM, Fred Zimmermanw...@nimblebooks.com wrote: Hi, I am using Nutch/Solr to index an intranet of about 12 million pages and when I do a search I want Solr to retrieve the full documents and append them into a single simple HTML doc (no js, not ads, etc.), then shoot the single doc to another (nonSolr) process for postprocessing. Can I use Velocity to do this? How? Can Velocity reach back to the Nutch crawl for the full text of the docs (they don't change often at all)? Any help would be much appreciated. -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Javascript, multiple lines, and Velocity
On 11/09/2011 04:42 PM, Andrew Ducker wrote: I have a textarea which I want to populate with some text. I have the text in a property that Velocity has access to. The template looks like this: document.DeliciousPoster.PostTemplate.value = '$data.DefaultPostTemplate'; Which would be fine - except that DefaultPostTemplate contains multiple lines, which breaks javascript. What's best practice for dealing with this? Remove new line characters in Java, and then put them back in in JS? Or something else? http://velocity.apache.org/tools/devel/generic/EscapeTool.html#javascript%28%29 -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
MIME type for velocity templates
Is there a recommended MIME type that should be used for .vm files? I found text/velocity on http://www.filesuffix.com/extension/vm.html but I'd like to get an official opinion. -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: MIME type for velocity templates
On 01/31/2012 11:00 AM, Christopher Schultz wrote: Nathan, On 1/31/12 10:52 AM, Nathan Bubna wrote: On Tue, Jan 31, 2012 at 7:48 AM, Christopher Schultz ch...@christopherschultz.net wrote: Nathan, On 1/25/12 1:16 PM, Nathan Bubna wrote: text/velocity sounds fine to me. this isn't something that i recall coming up previously, so i'm pretty sure there's no official opinion. Why not text/plain? If you you are serving up plain text, sure, why not? I thought the OP was asking about the .vm files themselves. If you request a .vm file and you just get the source, then it's text/plain. If you are evaluating the template and returning something, then it's up to the application: I use Velocity to generate plain text, XHTML, SVG, etc. Each of these applications needs a different MIME type that can't be predicted simply by looking at the extension of the template (which is pretty much always .vm). You can use plain text as a template, or almost plain text. But what if they are serving up an un-rendered template that has enough VTL directives in it to clearly not be plain text. Wouldn't that seem like a more fitting place for text/x-velocity? I was just assuming the mime type was for a template itself, not the rendered contents of a template. :) Yeah, me too. But what makes text plain? It's just nothing special, right? I've seen MIME types for Java source that are both text/plain and text/x-java. Yep, the question is about downloading the .vm files themselves, not about the rendering result. Considering all the answers, I'll go with text/x-velocity. Given that most of the templates contain a mixture of Velocity code and HTML markup, it would make sense to go for a neutral MIME type, like text/plain, but I feel that the HTML is just part of the output. Does a Java file full of String concatenation, where the strings are XML markup, warrant an application/xml MIME type just because it has more than 50% XML in it? Thanks everyone for your answers. -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Velocity syntax
On 03/26/2012 03:36 AM, Nikhil G. Daddikar wrote: Hello, I was looking at Velocity syntax and have a few questions. What is use of parenthesis in the #set directive: #set ($x = 1) Why not simply: #set $x = 1 ? Another question is regarding curly braces: What is the use of curly braces in the directives? E.g. #{set} ($x = 1) I am sure there are good reasons, just would like to know why. Thanks. Because in Velocity anything that's not correctly identified as part of the syntax is printed literally. I often find myself writing stuff like: text class=#if ($foreach.index % $parameters.labelStep == 0)major-#{else}minor-#{end}label Here I have to use the formal notation to separate #end from the following label text. It's not right to say that whenever #end is found stop parsing further and say that this is the #end keyword, since this would prevent me from defining my custom macros called #endTable, for example. Now it's true that I can't think of any valid usecase when #{set} is needed for practical reasons, but for consistency it's better to say that all velocity keywords can be written in the formal notation, not just those that might need it from time to time. The same is true for variables, not just keywords. Going back to my initial statement, the parenthesis help the parser separate the velocity statements from the plain text. Probably at all times #set instructions can go on their own line, so we could infere that it's very safe to say that the #set instruction always ends at the end of the line. But as you can see from the above example, that's not true for most of the other keywords, especially when dealing with space-sensitive output formats. And again for consistency it helps to have one rule for all the keywords, so that users don't have to remember which ones require () and which don't. In summary, some keywords in some cases do need the formal notation to separate the velocity syntax from the plain text that's going to be printed. For the same reason, most keywords also require parenthesis around their argument. For consistency and a more thorough yet simple definition of the syntax, all keywords follow these rules. -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: More 1.7 BC issues (porting from 1.5)
On 05/03/2012 03:20 PM, Nathan Bubna wrote: Ah, it was Sergiu, not Byron. Here's the relevant discussion: https://issues.apache.org/jira/browse/VELOCITY-681 Yep, me. http://wiki.apache.org/velocity/MacroEvaluationStrategy lists the different ways that Velocity treats macro parameters, depending on how they're used, what their value is, and what kind of expressions are actually used when calling the macro. I'd say that your example falls in the call by macro expansion example, which is how true macros are supposed to be evaluated, and this is what you'd get from a C #define macro as well. You're making the same mistake I often do, and think of Velocity as a kind of scripted Java, and of macros as a kind of Java functions. Under these assumptions, indeed one would expect call by value behavior. Velocity 1.7 moved closer to the call by macro expansion model, since it is a templating engine, and not a real programming language, even if some of its users do use it like one. Bottom line, I wouldn't call this a regression that needs to be fixed, but a bugfix that unfortunately broke compatibility for the few users that actually relied on the bug. The proper solution is to bite the bullet and fix all your macros. On Thu, May 3, 2012 at 12:16 PM, Nathan Bubnanbu...@gmail.com wrote: Ok, for my sanity, is this an accurate rewrite? #macro( inner $arg ) #set($ref = '')$arg #end #macro( outer ) #foreach( $ref in ['foo','bar','yok','dar'] ) #inner( $ref ) #end #end #outer() Do you get the same behavior in both with this? #macro( inner $arg ) #set($ref = '')$arg #end #foreach( $ref in ['foo','bar','yok','dar'] ) #inner( $ref ) #end Or is it only when the macros are nested? Also, do you have localscope on for the macros? I know changes were made in the pass-by-name behavior between 1.5 and the trunk (2.0-SNAPSHOT), but my memory is failing as to the chronology of them. What i do recall (possibly incorrectly), makes me think this should have been reversed; blank in the older version, instead of the newer. I thought we stopped proxying #set calls on macro args, because while that was arguably a correct way to do pass-by-name, it was deemed surprising and not worth the implementation/performance costs. I seem to recall arguing with someone about this, maybe Byron? Well, i'm confused. I also haven't the time to fire up Velocity environment right now on this machine to test it. Perhaps someone else can step in. On Thu, May 3, 2012 at 11:51 AM, Boris Partensky boris.parten...@gmail.com wrote: Not seeing any errors in log. Corrected to 2 single quotes. Same behavior. I was hoping that $input in each iteration will not be empty string, but rather 'foo', 'bar' etc (that's the way 1.5 behaves). Why would setting a value of $type in parent (foreach) scope would affect the value of the local $input argument? String template = #set($global_types=['foo', 'bar', 'yok', 'dar'])#macro( showBox $input)#set($type = '')$input#end+ #macro(showBoxes $types)#foreach($type in $types)#showBox($type)#end#end#showBoxes($global_types); On Thu, May 3, 2012 at 2:33 PM, Nathan Bubnanbu...@gmail.com wrote: Anything in the log? #set($type = \\) is not valid syntax, i think. I'm not even sure what value you want $type to have. Two double quotes or an empty string? On Thu, May 3, 2012 at 11:17 AM, Boris Partensky boris.parten...@gmail.com wrote: Hi, I have this use case which involves 2 nested macros and a foreach. I am trying to understand why this template evaluates to empty string on 1.7, and to foobaryokdar - on 1.5. String template = #set($global_types=['foo', 'bar', 'yok', 'dar'])#macro( showBox $input)#set($type = \\)$input#end+ #macro(showBoxes $types)#foreach($type in $types)#showBox($type)#end#end#showBoxes($global_types); -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Accessing a key in a java map.
On 06/01/2012 01:20 PM, Lukas, Ray wrote: I have created a java.util.HashMapString, TressSetMyJavaObject and have placed that into the $values map which I then pass into Velocity. The name of a group of things mapped to a sorted set of those things. I have no problem iterating through the map but I cannot seem to find a way to access the key (the String) of the map.entry and overlay that into my form. How is this done. I want to print out the name of the group and then the group. Common thing to do I would think.. #foreach($LabTestTypeEntrySet in $values.TestTypeGroupedBySpecimenName.keySet()) $LabTestTypeEntrySet.??? - what goes here ---?? #foreach($LabTestType in $values.TestTypeGroupedBySpecimenName.get($LabTestTypeEntrySet) ) $LabTestType.labTestTypeCode #end #end I am kind of new to Velocity and have been hunting for the solution.. can someone help me out real quick. Thanks guys.. Behind any velocity variable there's a real Java object. So, given that, as you said, $values is a HashMapString, TreeSet, then what would you do to get the key in Java? There are some things that don't seem to be right in your code... The name of $LabTestTypeEntrySet seems wrong, since the variable that you're iterating with will not hold a set, but only one value at a time, so it should be called $LabTestTypeEntry. $values.TestTypeGroupedBySpecimenName translates into HashMapString, TreeSet.get('TestTypeGroupedBySpecimenName'), which returns a value from the map, which should have the type TreeSetMyJavaObject. There's no keySet() method for a TreeSet, so that whole #foreach shouldn't have any values to iterate on... Perhaps you placed this whole map as an entry into the the $values object, under the 'TestTypeGroupedBySpecimenName' key? In that case, this code should work: #foreach($LabTestTypeEntry in $values.TestTypeGroupedBySpecimenName.entrySet()) ## Notice that I used entrySet(), not keySet() ## $LabTestTypeEntry.key is the key, of type String ## $LabTestTypeEntry.value is the value, of type TressSetMyJavaObject #foreach($LabTestType in $LabTestTypeEntry.value) ## $LabTestType is a MyJavaObject from the TreeSet $LabTestType.labTestTypeCode ## I guess that your MyJavaObject has a getLabTestTypeCode() method #end #end -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Having trouble doing math with values retrieved from external data source
On 10/02/2012 01:55 PM, Dalrymple, Craig - OCIO-ITS, Kansas City, MO wrote: Could the following issue be related to the 1.4 engine, or to the way Cisco has it implemented? Source: #set ($county=$!{dsobj.getValue('Location-CountyName')}) #set ($county=$county.toLowerCase()) #if ($county.lentgh() 8) ## check to see if the county name is longer than 8 Do you really have lentgh instead of length in your code? ! true hostname $county.substring(0,8)$!{dsobj.getValue('Location-FIPSCode')}$!{dsobj.getValue('Device-Instance')} #else ! false hostname $county$!{dsobj.getValue('Location-FIPSCode')}$!{dsobj.getValue('Device-Instance')} #end Output: ! false hostname stelsewhere99 ! Clearly, the length is more than 8 -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Simple list of all methods, properties, variables available to templates?
On 02/12/2013 12:17 PM, ANS Developer Team wrote: Ah thanks, it's pretty sparse, hence why I'm asking here. Much appreciated, will figure it out from source. If you can get your hands on the current VelocityContext, then you could list all the properties it contains (it extends Map). On Tue, Feb 12, 2013 at 12:42 AM, Nathan Bubna nbu...@gmail.com wrote: Velocity doesn't provide anything but the syntax. You will have to seek documentation from Vosao CMS. On Mon, Feb 11, 2013 at 6:57 PM, ANS Developer Team d...@answeb.org wrote: Hi all, I'm trying to find a list all of the above that can be used in a template, preferably with a brief description of what it does (but that's not entirely necessary). I'm building site using the Velocity-based Vosao CMS, and have no idea what what methods, properties, and variables are available to me except the sparse few used in the example Blog app. For example there's a $page.friendlyURL property, but what other properties does $page have? Having trouble finding this information. I've found the Velocity VTL Reference Guide, but that's more of a syntax uide without a comprehensive list, and I've found the online Velocity API docs, but that's overkill and I still can't find the $page object in it (not sure what class it's in). Any help on this much appreciated! - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: template.merge output an empty file
On 02/21/2013 01:50 PM, Garey Mills wrote: Hi - I am trying to user VelocityEngine. Here is my code: Properties vp = new Properties(); vp.setProperty(file.resource.loader.path, templatesDirectory + /); VelocityEngine ve = new VelocityEngine(); ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, fysclLogger); ve.init(vp); VelocityContext context = new VelocityContext(); context.put(coll, coll); context.put(metsArk, metsArk); Template template = null; try { FileWriter fw = new FileWriter(new File(metsDirectory + / + metsFileName)); template = ve.getTemplate(metsTemplate.vm); template.merge(context, fw); } catch(ResourceNotFoundException rnfe) { System.out.println(Resource not found exception trying to get template: + rnfe); } catch(ParseErrorException pee) { System.out.println(Parse error exception trying to get template: + pee); } catch(MethodInvocationException mie) { System.out.println(Method invocation exception trying to get template: + mie); } catch(Exception e) { System.out.println(Exception trying to get template: + e); } Here is my template (reduced for debugging): OBJID=${metsArk} LABEL=${coll.getTitle()} And here is the logging output: Initializing Velocity, Calling init()... *** Starting Apache Velocity v1.7 (compiled: 2010-11-19 12:14:37) RuntimeInstance initializing. Default Properties File: org/apache/velocity/runtime/defaults/velocity.properties Default ResourceManager initializing. (class org.apache.velocity.runtime.resource.ResourceManagerImpl) ResourceLoader instantiated: org.apache.velocity.runtime.resource.loader.FileResourceLoader FileResourceLoader : initialization starting. Do unicode file recognition: false FileResourceLoader : adding path '/data/apps/fysclmgr/web/templates/' FileResourceLoader : initialization complete. ResourceCache: initialized (class org.apache.velocity.runtime.resource.ResourceCacheImpl) with class java.util.Collections$SynchronizedMap cache map. Default ResourceManager initialization complete. Loaded System Directive: org.apache.velocity.runtime.directive.Stop Loaded System Directive: org.apache.velocity.runtime.directive.Define Loaded System Directive: org.apache.velocity.runtime.directive.Break Loaded System Directive: org.apache.velocity.runtime.directive.Evaluate Loaded System Directive: org.apache.velocity.runtime.directive.Literal Loaded System Directive: org.apache.velocity.runtime.directive.Macro Loaded System Directive: org.apache.velocity.runtime.directive.Parse Loaded System Directive: org.apache.velocity.runtime.directive.Include Loaded System Directive: org.apache.velocity.runtime.directive.Foreach Created '20' parsers. Velocimacro : initialization starting. Velocimacro : velocimacro.library is not set. Trying default library: VM_global_library.vm Velocimacro : Default library not found. Velocimacro : allowInline = true : VMs can be defined inline in templates Velocimacro : allowInlineToOverride = false : VMs defined inline may NOT replace previous VM definitions Velocimacro : allowInlineLocal = false : VMs defined inline will be global in scope if allowed. Velocimacro : autoload off : VM system will not automatically reload global library macros Velocimacro : Velocimacro : initialization complete. RuntimeInstance successfully initialized. Velocity Engine initialized ResourceManager : found metsTemplate.vm with loader org.apache.velocity.runtime.resource.loader.FileResourceLoader The result is always the same, the output file is empty. And ideas about what I can try? Try adding a fw.close() at the end? - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: While-like structure in Velocity?
On 05/15/2013 12:11 PM, Christopher Schultz wrote: All, I've searched the archives for while capabilities in Velocity, and mostly the answers have been things like that's beyond the scope of Velocity... you want a real programming language for that. I'd like to do something that naturally would use a while loop, but perhaps someone can offer an alternative suggestion. I need to traverse a queue, but that queue needs to be able to modify itself during the processing. Basically, something like this: while (!queue.empty) { // do something with the head element // possible enqueue some more items at the back } #foreach would be the way to do it if the queue didn't have to be modified, but I'll get an exception if I try to traverse an iterator over the queue and then modify it mid-flight. Right now, I have this written as a JSP but I'd rather have it as a Velocity template. My only thought is to create an ugly class that implements Iterator and wraps the queue but is much less strict than a standard iterator. Any suggestions? -chris While not a very clean solution, you can use a very large foreach and manually work with the queue inside the loop, and #break($foreach) once the queue is empty: #foreach($i in [0..10]) #if ($queue.isEmpty()) #break($foreach) #end #set ($item = $queue.pop()) ## Do stuff with $item #if (should add more things) #set ($discard = $queue.add(new things)) #end #end -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: addition of lists
On 05/24/2013 02:37 PM, ricardo.julio.rodriguez.fernan...@sergas.es wrote: Hey Sergiu! A big pleasure to meet you here! Thanks for your answer. Please, see below... From: Sergiu Dumitriu [sergiu.dumit...@gmail.com] Sent: 24 May 2013 19:54 To: user@velocity.apache.org Subject: Re: addition of lists On 05/24/2013 01:50 PM, ricardo.julio.rodriguez.fernan...@sergas.es wrote: Hi! Probably I'll use the wrong semantic, but I'll try to explain the very simple result I want to get with Velocity: given two lists of results, let's me call them $list1 and $list2, I want to get a new list, let's call it $listTotal, including all item in $list1 and $list2. Please, how could I do that? What is the correct expression I must it in Velocity's World for his operation? Thank you so much for your help! Ricardo Hey Ricardo, If those are indeed lists, they should support all the methods that Java's List class provides [1], including addAll [2], so this should work: #set ($listTotal = []) #set ($discard = $listTotal.addAll($list1)) #set ($discard = $listTotal.addAll($list2)) It worked! They are indeed lists :-) But I've not a clear idea yet about what is list, what an array, what a collection, what any sort of collection... Please, could you provide me a good reference to keep trying to understand what I feel like a must to leverage the power of Velocity and, of course, the nice team XWiki/Velocity? These two lists come from a for you well known lines of code. Something like this... #set ($xwqlquery = where doc.translation = 0 and doc.creationDate '2013-01-01' and doc.parent like '%$doc.title%' and doc.fullName NOT IN ($nicestr0) order by doc.object(XWiki.XWikiUsers).last_name) #set ($results = $services.query.xwql($xwqlquery).execute()) Please, is it possible to check $results if is it a list? For instance, I guessed it is a list because I can apply size() to it. Is this a right guess? You can always check the actual class of a variable with: $var.class This will print the classname, which will correspond to a real Java class (most likely an ArrayList). You can then look up that class in your favorite Java IDE and look at its hierarchy: which interfaces does it implement (List, Set or Map), what methods does it have, etc. One exception is that arrays (like String[]) are treated as lists by Velocity, so they will also support all the List methods, even though in Java they don't. Thank you so much for your help! [1] http://docs.oracle.com/javase/1.5.0/docs/api/java/util/List.html [2] http://docs.oracle.com/javase/1.5.0/docs/api/java/util/List.html#addAll%28java.util.Collection%29 Thanks! -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: On sorting
On 05/25/2013 11:39 AM, ricardo.julio.rodriguez.fernan...@sergas.es wrote: I'm really getting mad! :-) Of course I know that the only reason for this is my lack of skills!!! Catching up... I do need some kind of security. Please, could you confirm this statement... Class SortTool can be used to sort any list of objects, but NOT a list of strings. Where did you get this from? It is not true, it can sort any list of comparable things: #set ($strings = ['a', 'x', 'b', 'r', 'f']) $sorttool.sort($strings) - [a, b, f, r, x] http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/SortTool.html Thanks! - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: On sorting
On 05/25/2013 11:59 AM, ricardo.julio.rodriguez.fernan...@sergas.es wrote: From: Sergiu Dumitriu [sergiu.dumit...@gmail.com] Sent: 25 May 2013 17:49 To: Velocity Users List Subject: Re: On sorting On 05/25/2013 11:39 AM, ricardo.julio.rodriguez.fernan...@sergas.es wrote: I'm really getting mad! :-) Of course I know that the only reason for this is my lack of skills!!! Catching up... I do need some kind of security. Please, could you confirm this statement... Class SortTool can be used to sort any list of objects, but NOT a list of strings. Where did you get this from? It is not true, it can sort any list of comparable things: #set ($strings = ['a', 'x', 'b', 'r', 'f']) $sorttool.sort($strings) - [a, b, f, r, x] Great! It is clear my wrong interpretation of this sentence... SortTool allows a user to sort a collection (or array, iterator, etc) on any arbitary set of properties exposed by the objects contained within the collection. It is taken from the link below. No reference to strings, it speaks only about objects. But it is great to be wrong! Yes, that is the more advanced part of the SortTool, the ability to sort beans [1] by one or more of their properties. Unfortunately Strings are not beans, so the sort methods that take a second parameter can't be used for a simple list of strings. [1] http://en.wikipedia.org/wiki/JavaBeans And, in this case, how could I get a reverse/desc order? It's not possible using the SortTool, but in XWiki we have the $collectionstool [2, 3] which does provide both a simple sort(List) and a reverse(List) method, so you could do: #set ($discard = $collectionstool.sort($list)) #set ($discard = $collectionstool.reverse($list)) Keep in mind that these two methods sort the list in place, and they return true if the list could be sorted/reversed. [2] https://github.com/xwiki/xwiki-commons/blob/xwiki-commons-5.0/xwiki-commons-core/xwiki-commons-velocity/src/main/java/org/xwiki/velocity/tools/CollectionsTool.java [3] http://platform.xwiki.org/xwiki/bin/view/SRD/Navigation?api=collectionstoolxpage=embed Thanks! http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/SortTool.html Thanks! - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Returning String without Whitespace from Velocimacros
Velocimacros are macros, they don't return anything. They print stuff, just like normal code outside the macro. A macro is a simple way of reusing code without duplicating it. As in other Velocity code, almost all whitespace is important, so you have to be careful if you don't want it to be printed. Still, it is possible to control all the whitespace produced, reducing the style of the code, combining: - ## at the end of the line to comment out the \n that would otherwise be printed - The formal syntax for #{else} ${var} #{end} to eliminate the need for a separator space after the end of these words - Removing leading whitespace, thus breaking the indentation Another option is to use a pre-processor that trims the whole .vm file before parsing it, so instead of sending the original template to the Velocity engine, you send a string with all the leading and trailing space removed. Another option is to run the macro inside a string, which you can then trim: #set ($tmp = #query_url($query_param)) ${tmp.trim()} On 08/01/2013 01:27 PM, O. Olson wrote: Hi, I am new to using Apache Velocity. What is the correct way of returning a string from a Macro or a Velocimacro? Since I did not have a clue on how to return a string from a Macro, I decided to do something like #macro(query_url $query_param) q=$query_param #end I can then call the Macro using: #query_url(*) The problem with this is that the resulting value contains a Tab or number of Spaces before the 'q=' when I call it. One option is to delete the spaces like: #macro(query_url $query_param) q=$query_param #end This fixes my problem but is very hard to read. To take this a step further consider: #macro(default_query_url) #if($request.params.get('q')) #query_url($request.params.get('q')) #else #query_url(*) #end #end Vs. #macro(default_query_url) #if($request.params.get('q')) #query_url($request.params.get('q')) #else #query_url(*) #end In the first case there is no whitespace, but editing it would be very difficult for more complicated macros. I am curious what is the correct way to return values from Velocimacros and if I can Trim the resulting Whitespace before returning it? Thank you an advance for any help. O. O. -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Returning String without Whitespace from Velocimacros
On 08/01/2013 02:02 PM, O. Olson wrote: Thank you very much Alex. This would be very painful if every time I call a macro, I would need to set a variable and trim it. I am curious what is the function of the @ sign in the helper “trim” macro that you suggested. By the way, how do I call this macro i.e. invoke it? This is a macro with a body: http://velocity.apache.org/engine/releases/velocity-1.7/vtl-reference-guide.html#amacro_-_Allows_users_to_define_a_Velocimacro_VM_a_repeated_segment_of_a_VTL_template_as_required The full code would be: #macro(trim) $!bodyContent.trim() #end #macro(default_query_url) ... your normal macro body, with all the extra space ... #end Calling it: #@trim()#default_query_url()#end Is it possible to return a particular variable from a Web Macro? E.g. #macro(default_query_url) #if($request.params.get('q')) #set($str = query_url($request.params.get('q'))) #else #set($str = query_url(*)) #end RETURN $str How??? No. Macros are not functions. But any variable you set will still be available after the macro call ends, so you can use it afterwards. You could do something like: #set ($discard = #default_query_url()) $str This will just discard anything the macro would normally print, and you just print the variable that was set inside the macro. Note that this behavior is optional, and the velocity configuration can disable it. #end This would help my whitespace problem. Thanks again, O. O. - Messaggio originale - Da: Alex Fedotov a...@kayak.com A: Velocity Users List user@velocity.apache.org; O. Olson olson_...@yahoo.it Cc: Inviato: Giovedì 1 Agosto 2013 12:43 Oggetto: Re: Returning String without Whitespace from Velocimacros Simple way: #set($str=#default_query_url()) $str.trim() Can probably create a helper macro trim that does the same thing to the body content: #@trim() #default_query_url() #end On Thu, Aug 1, 2013 at 1:27 PM, O. Olson olson_...@yahoo.it wrote: Hi, I am new to using Apache Velocity. What is the correct way of returning a string from a Macro or a Velocimacro? Since I did not have a clue on how to return a string from a Macro, I decided to do something like #macro(query_url $query_param) q=$query_param #end I can then call the Macro using: #query_url(*) The problem with this is that the resulting value contains a Tab or number of Spaces before the 'q=' when I call it. One option is to delete the spaces like: #macro(query_url $query_param) q=$query_param #end This fixes my problem but is very hard to read. To take this a step further consider: #macro(default_query_url) #if($request.params.get('q')) #query_url($request.params.get('q')) #else #query_url(*) #end #end Vs. #macro(default_query_url) #if($request.params.get('q')) #query_url($request.params.get('q')) #else #query_url(*) #end In the first case there is no whitespace, but editing it would be very difficult for more complicated macros. I am curious what is the correct way to return values from Velocimacros and if I can Trim the resulting Whitespace before returning it? Thank you an advance for any help. O. O. -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Documentation regarding Custom Utility Class for Velocity
It depends on what you mean by velocity tools. As the description on http://velocity.apache.org/tools/releases/2.0/ says, a tool is just a Plain Old Java Object, so any Java object can act as a tool. Officially, a tool is something that can be automatically placed in the context when you have a more complex/automatic Velocity Engine setup, like VelocityViewServlet or VelocityStruts, or using one of the configuration mechanisms listed on http://velocity.apache.org/tools/devel/config.html Unofficially, if you're working directly with the engine, you can place any object in the VelocityContext when rendering a parsed template. So, there's no restriction on the class that you're using as a tool, other than: - only public methods can be invoked from Velocity, but there can be helper private methods if they help you organize the code - if the tool is automatically instantiated, it must have a public constructor with no parameters; if you instantiate it manually, you can pass as many arguments as you want in the constructor On 08/08/2013 12:06 PM, O. Olson wrote: Hi, I am wondering if there is any documentation on writing your own Utility Class or Custom Tool to add to Velocity. The only place I found some help is http://www.sergiy.ca/how-to-create-custom-tools-for-apache-velocity/ (There is something regarding Custom Tools at http://velocity.apache.org/tools/releases/2.0/creatingtools.html - but I could not find anything regarding Utility Classes that we can push into the Velocity Context.) Originally, I was thinking of doing my processing/customization in Velocimacros, but that is turning out to be a bit more complex/cumbersome than I expected. I am thinking of doing this in Java, and pushing the results to the Velocity Context as a single object/utility class instance. For purposes of discussion let us assume, I do something like the following in Java: VelocityContext context; context.put(myUtil, new MyUtil()); I'd appreciate if I could get answers/ideas on: 1.I am wondering if MyUtil() needs to be static across requests. I intend MyUtil() to provide easy access and manipulation of the current request. Hence, I would probably do something like the following in Java: context.put(myUtil, new MyUtil(currentWebRequest)); i.e. I would instantiate MyUtil with the current Web Request. MyUtil could then provide easy access to say the Number of Rows in the Request. So in the Template I could do: $myUtil.NumRows If MyUtil() is static, this would not work, because different requests would have different number of Rows. Should the Utility Class/Object be static? The example mentioned above shows only static methods, hence my question. 2.Should my Utility class follow the bean syntax i.e. for the above example of $myUtil.NumRows in the template, would I need to declare something like the following in the MyUtil Java class: public int getNumRows() { } 3.What would be a good way to pass a Constant from Java to the Template? Should I use the bean syntax again? E.g. in the template $myUtil.JAVA_CONSTANT Would I need to have something like: public int getJAVA_CONSTANT () { } Thank you in advance for your help, O. O. - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: [tools] Replacement for ListTool?
This should work without any tools: $bundleType.class.getName().startsWith('[') On 06/26/2014 03:27 PM, Christopher Schultz wrote: All, ListTool is marked as deprecated because Velocity 1.6 and later treat arrays and lists as first-class collections and can perform appropriate operations on them. One thing it's not easy to do is determine if an object is an List or an Array. I have something hacked-together using ClassTool like this: #set($bundleType=$class.inspect($bundle).type) #if($bundleType $class.inspect('java.util.List').type.isAssignableFrom($bundleType)) [the $bundle object is a List] #end But it's kind of verbose, plus I need to check to see if it's an array as well. Any suggestions using existing tools? Thanks, -chris -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Fwd: Trouble with Velocity in SOLR 5.0.0
That's a change in the velocity engine, the way nested quotes are escaped is by doubling them: #set ($temp0 = $paramsq.replaceAll(, )) Or better: #set ($temp0 = $paramsq.replaceAll('', '')) I guess Solr 5 upgraded the version of Velocity they embed, thus the regression in your code. On 03/11/2015 04:46 AM, phi...@free.fr wrote: Good morning, I have found the cause of the error (see below) in this line: #set ($temp0 = $paramsq.replaceAll(\, )) I replaced \ by \u0022, and the error message vanished. #set ($temp0 = $test.replaceAll(\u0022, )) Philippe ERROR 500 Encountered AND at richtext_doc.vm[line 65, column 51] Was expecting one of: , ... ) ... ... - #if ($params.q and $pdf_dir_v and $pdf_year_mon_v and $pdf_day_v and $pdf_name_v) #set ($paramsq = $params.q) #if ($paramsq.length() 0) paramsq = $paramsq ## Remove double quotes #set ($temp0 = $paramsq.replaceAll(\, )) - - Mail transféré - De: phi...@free.fr À: Velocity Users List user@velocity.apache.org Envoyé: Mardi 10 Mars 2015 16:29:48 Objet: Re: Trouble with Velocity in SOLR 5.0.0 Problem solved. A query Response Writer was not declared in my solrconfig.xml file. queryResponseWriter name=velocity class=solr.VelocityResponseWriter startup=lazy str name=template.base.dir${velocity.template.base.dir:}/str /queryResponseWriter - Mail original - De: phi...@free.fr À: Velocity Users List user@velocity.apache.org Envoyé: Mardi 10 Mars 2015 14:16:41 Objet: Trouble with Velocity in SOLR 5.0.0 Hello, I am trying to make Velocity work in SOLR 5.0.0. First of all, I have added the following lines to my core's solrconfig.xml file: luceneMatchVersion5.0.0/luceneMatchVersion lib dir=../../../contrib/extraction/lib regex=.*\.jar / lib dir=../../../dist/ regex=solr-cell-\d.*\.jar / lib dir=../../../contrib/langid/lib/ regex=.*\.jar / lib dir=../../../dist/ regex=solr-langid-\d.*\.jar / lib dir=../../../contrib/velocity/lib regex=.*\.jar / lib dir=../../../dist/ regex=solr-velocity-\d.*\.jar / ... ... and created a /browse request handler requestHandler name=/browse class=solr.SearchHandler lst name=defaults str name=echoParamsexplicit/str !-- VelocityResponseWriter settings -- str name=wtvelocity/str str name=v.templatebrowse/str str name=v.layoutlayout/str str name=titleArchives/str !-- Query settings -- str name=defTypeedismax/str I have also copied the 'velocity' directory from a 4.9 core to the /archives/solr-5.0.0/server/solr/mycore1/conf directory as well as the toolbox.xml file. The mycore1's conf directory now contains the following files and directories: currency.xml lang protwords.txt _rest_managed.json schema.xml solrconfig.xml stopwords.txt synonyms.txt toolbox.xml velocity When I type http://myserver.com:8990/solr/mycore1/select?q=*:* in a browser, I get an XML page, not HTML generated by Velocity, as expected. response lst name=responseHeader int name=status0/int int name=QTime5/int lst name=params/ /lst result name=response numFound=0 start=0 maxScore=0.0/ lst name=facet_counts lst name=facet_queries/ lst name=facet_fields lst name=ymd/ /lst lst name=facet_dates/ lst name=facet_ranges/ lst name=facet_intervals/ /lst lst name=highlighting/ /response What did I miss? Cheers, Philippe - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Explicitly using null in a template
I remember reading somewhere that you should use $NULL, but can't remember where. On 07/27/2015 01:11 PM, Christopher Schultz wrote: All, I have a situation where I need to explicitly pass NULL to a method on an object. Can I simply do something like this: $myObject.getSomething($referenceThatIsCertainlyNull) ? I seem to remember there being a helper object (VelocityTool?) that had nice things in it like $helper.null or something like that, but I can't seem to find a reference for it. Thanks, -chris -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: [ANNOUNCE] Velocity Engine 2.0 test build available
If you don't want surprises, you should also specify the encoding to use. I'm guessing that the files you're reading have a known encoding that's kept from the build into the distribution package, but you don't always have control over the system where it's installed. try { return new BufferedReader(new InputStreamReader(servletContext.getResourceAsStream(path), "UTF-8")); } catch (UnsupportedEncodingException e) { // This should never happen, UTF-8 is mandatory for a valid JVM return null; } On 11/08/2016 07:13 AM, Greg Huber wrote: > Seems to be working OK. Thanks. > > For the ResourceLoader changes I have been doing this : > > public InputStream getResourceStream(String name) > > return result = servletContext.getResourceAsStream(path); > > but now must use : > > public Reader getResourceReader(String name, String encoding) > > return result = new BufferedReader(new InputStreamReader( > servletContext.getResourceAsStream(path))); > > Is this the most efficient way to the Reader class? Seems a lot more > processing than just the InputStream?? > > > > > > On 7 November 2016 at 10:06, Claude Brisson <cla...@renegat.net> wrote: > >> The test build of Velocity Engine 2.0 is available. >> >> No determination as to the quality ('alpha,' 'beta,' or 'GA') of Velocity >> Engine 2.0 has been made, and at this time it is simply a "test build". We >> welcome any comments you may have, and will take all feedback into account >> if a quality vote is called for this build. >> >> Release notes: >> >> * https://dist.apache.org/repos/dist/dev/velocity/velocity-eng >> ine/2.0/release-notes.html >> >> Distribution: >> >> * https://dist.apache.org/repos/dist/dev/velocity/velocity-engine/2.0/ >> >> Maven 2 staging repository: >> >> * https://repository.apache.org/content/repositories/orgapache >> velocity-1010/ >> >> A vote regarding the quality of this test build will be initiated within >> the next couple of days. >> >> >> Regards, >> >> Claude >> >> >> > -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: How to prevent skip of newline after line comment
Since you know there's a comment there which will eat the newline, you can add an empty line after it: Some text to display ## some comment following Next line with some text This will print as you want. Since the newline following the comment is discarded, the newline on the following empty line will be moved at the end of the first line. Another way is to use block comments: Some text to display #* some comment following *# Next line with some text On 11/25/2016 01:10 PM, Andreas Kuhtz wrote: > Hello, > > Is it possible to prevent skip of newline after line comment during > rendering? > I've the following lines in a template: > > Some text to display ## some comment following > Next line with some text > > The result is the following: > Some text to display Next line with some text > > Instead of: > Some text to display > Next line with some text > > Best regards, > Andreas > -- Sergiu Dumitriu http://purl.org/net/sergiu/ - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Create an empty java.util.Set in VTL
Not if you're using the secure uberspector, which everyone should be doing. On 01/25/2018 11:44 AM, Alex Fedotov wrote: > You can probably use a hack with classloader. Along the lines of: > > #set($x = > "1".getClass().getClassloader().findClass("java.uti.HashSet").newInstance()) > > Alex > > > On Thu, Jan 25, 2018 at 11:30 AM, Christopher Schultz < > ch...@christopherschultz.net> wrote: > > All, > > If I want to create a new empty array/collection, I can do something > like this: > > #set($array = []) > > If I want to create a new Map, I can do this: > > #set($map = {}) > > Is there a way to create a new Set? > > I'd like to use a set because: > > 1. I want to use this object as a sort of scratch-area to know what > work I've done before > > and > > 2. I'm going to be consulting it a lot using Set.contains(object) so > something other than ArrayList/LinkedList will be much faster > > Thanks, > -chris >> >> - >> To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org >> For additional commands, e-mail: user-h...@velocity.apache.org >> >> > -- Sergiu Dumitriu http://purl.org/net/sergiu -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org
Re: Create an empty java.util.Set in VTL
Not with the default syntax and context. If you can control the context, you can put an utility that can create any type of collection: random sets, linked sets, ordered sets, linked maps, ordered maps... On 01/25/2018 11:30 AM, Christopher Schultz wrote: > All, > > If I want to create a new empty array/collection, I can do something > like this: > > #set($array = []) > > If I want to create a new Map, I can do this: > > #set($map = {}) > > Is there a way to create a new Set? > > I'd like to use a set because: > > 1. I want to use this object as a sort of scratch-area to know what > work I've done before > > and > > 2. I'm going to be consulting it a lot using Set.contains(object) so > something other than ArrayList/LinkedList will be much faster > > Thanks, > -chris > > - > To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org > For additional commands, e-mail: user-h...@velocity.apache.org > -- Sergiu Dumitriu http://purl.org/net/sergiu - To unsubscribe, e-mail: user-unsubscr...@velocity.apache.org For additional commands, e-mail: user-h...@velocity.apache.org