Does anyone have a full solution/walkthrough of how to use the perl Template module? - string

#neuhaus pointed out new documentation to me on the template-toolkit.org site
Here is the code from CPAN that I have been trying to run/mess about with:
#!/usr/bin/env perl
use lib ('./t/lib/');
use strict;
use warnings;
use Template;
use Test::More tests => 1;
my $text = "This is string number [% num %] .";
my $vars = {
num => "one",
};
my $template = Template->new();
$template->process($text, $vars)
|| die "Template process failed: ", $template->error(), "\n";
ok(defined $text, 'Returns something');
I am receiving the following error:
Template process failed: file error - This is string number [% num %] . : not found
I am just running it in a test file at the moment, in case you guy are wondering.

The definition of the process() method in the Template documentation says this:
The first parameter indicates the input template as one of: a filename
relative to INCLUDE_PATH, if defined; a reference to a text string
containing the template text; or a file handle reference (e.g.
IO::Handle or sub-class) or GLOB (e.g. \*STDIN), from which the
template can be read.
If you pass it a string, it is assumed to be the name of a file containing the template. If you want to pass it a string containing the actual template, then you need to pass a reference to a string.
So your line:
$template->process($text, $vars)
Needs to be:
$template->process(\$text, $vars)
The error message was a good clue to this. It was telling you that it couldn't find a file called "This is string number [% num %] .".

You may find Template::Manual::Intro and Template::FAQ useful, and there are excellent tutorials in the package with Template
Template::Tutorial is a portal to
Template::Tutorial::Web Generating Web Content Using the Template Toolkit
Template::Tutorial::Datafile Creating Data Output Files Using the Template Toolkit
The module has its own web site at template-toolkit.org but the documentation there is just a mirror of the POD from the installation package

Check out the tutorial at template-toolkit.org
especially the section
Dynamic Content Generation Via CGI Script

Related

Spreadsheet::ParseExcel::SaveParser Issues - Cannot Obtain a Defined Workbook Object

I am trying to use the Spreadsheet::ParseExcel::SaveParser plugin using example code at both metacpan.org and on SO and I cannot define the template (workbook).
I have played around with variations on the new statement, quotes, file parh, etc - nothing works. I put a die after the template statement and it prints the error message. Without that I have either a $template->worksheet() or worksheets() statement and if I skip the die I get a different message. I confirmed that the path to the Excel file is correct. I also new()'ed Spreadsheet::ParseXLSX instead and the code got past the template undefined problem - of course it crashed when I tried to do an AddCell.
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
my $saveParser = Spreadsheet::ParseExcel::SaveParser->new();
my $template = $saveParser->Parse("some Excel file verified to exist");
die "Error! Template not defined!\n" if (!defined($template));
dies
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
my $saveParser = Spreadsheet::ParseExcel::SaveParser->new();
my $template = $saveParser->Parse("some Excel file verified to exist");
my $worksheet = $template->worksheet(0);
Can't call method "worksheet" on an undefined value at ../bin/update_tp.pl line nnn. It also errors out if I use the worksheet name instead of number.
Obviously I expect the $saveParser->Parse command to return a valid object so I can work with it - it doesn't. FYI all modules I'm using are at the current rev of 0.65 except WriteExcel (which isn't relevant yet), which is 2.4.
Think you'd want to track down what error-handling is available for the Parse() function by reading the CPAN page for this module. Find and adapt that error-handling to give you an inkling of why Parse() would be failing. Your error about "worksheet on an undefined value" is indicative of that call failing. Could be you're not escaping file paths, maybe you don't have read permissions on the file, lots of other reasons Parse() could be failing. Eww, just went and looked myself, and there's fairly inadequate error-handling documented for that function. Maybe try die'ing with some error-handling variables? See https://perldoc.perl.org/perlvar.html#Error-Variables

How do I parse a YAML file in groovy?

say if you have a file called example.yaml which contains the following:
- subject: maths.
How do i grab the string after - subject?
I already can read the contents of the file but want to know how to grab a specific string from it.
note: i know regex may help but have never used it and would appreciate any help.
I am adding here the same example, but implemented with the native YAMLSlurper (Groovy 3.x+):
import groovy.yaml.YamlSlurper
def exampleYaml = '''\
---
- subject: "maths"
- subject: "chemistry"
'''
List example = new YamlSlurper().parseText(exampleYaml)
// If your source is a File
// List example = new YamlSlurper().parse("example.yaml" as File)
example.each{println it.subject}
For previous versions (Original answer):
snakeyaml is a library to parse YAML files. Easy to use in groovy.
UPDATE: changed type of the example variable to List, as the example file's top level element is a collection
#Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
Yaml parser = new Yaml()
List example = parser.load(("example.yaml" as File).text)
example.each{println it.subject}
Full documentation of snakeyaml:
https://bitbucket.org/snakeyaml/snakeyaml/wiki/Documentation
FWIW, the upcoming (as time of this writing) Groovy version 3.0 has direct support for yaml:
http://docs.groovy-lang.org/next/html/api/groovy/yaml/package-summary.html with the traditional YamlSlurper / YamlBuilder combo
You could always switch to this not-yet-officially-released version.
[Edited] that version 3.0.x is now officially available, with the groovy.yaml package http://docs.groovy-lang.org/latest/html/api/groovy/yaml/package-summary.html

echo of var to file in SConscript

In an SConscript file I have a env variable BUILDID_STR
that contains a C string that I wish to output to a file.
bstr = env['BUILDID_STR']
print(bstr)
which when printed, print(bstr) correctly shows this:
//this file is automatically generated
static char* build_str="0|0.1.0|2014-05-29_16:16:51";
However, I can't get the var expanded/exported correctly, just the literal string is output instead of the above text:
cat src/log/src/version.c
env[BUILDID_STR]
Here's the pertinent part of my SConscript file
env.Command(target='#/src/log/src/version.c',
source=libSrcfiles,
action="echo env['BUILDID_STR'] > $TARGET")
env.SharedLibrary('log', [libSrcfiles, '#/src/log/src/version.c'])
I've also tried the code in a function and also passing to a shell script, all with the same result.
The reason I have .../version.c in the SharedLibrary is that my goal is to have the .c file generated only when on of the libSrcfiles is built, thereby version.c is compiled-in.
The "textfile" Tool offers two Builders Textfile() and Substfile() for cases like this. You probably want to use the first:
env = Environment(tools=['textfile'])
env['BUILDID_STR'] = 'A test'
env.Textfile('test.txt', ['$BUILDID_STR'])
As you have seen, the action is not expanding the env variable. In the action, you can refer to env variables with the $VAR syntax (just like referring to the $SOURCE and $TARGET variables provided by SCons):
env.Command(target='#/src/log/src/version.c',
source=libSrcfiles,
action="echo $BUILDID_STR > $TARGET")
This solution may not handle a BUILDID_STR containing multiple lines.
You may want to investigate a system that builds your source file from a template (instead of constructing the file contents entirely within a string). The Substfile Builder referenced in this previous question might be a good starting point -- you can provide a list of (key, value) pairs to be substituted in an input file. The Substfile Builder is built into recent versions of SCons.

Relative path for JMeter XML Schema?

I'm using JMeter 2.6, and have the following setup for my test:
-
|-test.jmx
|-myschema.xsd
I've set up an XML Schema Assertion, and typed "myschema.xsd" in the File Name field. Unfortunately, this doesn't work:
HTTP Request
Output schema : error: line=1 col=114 schema_reference.4:
Failed to read schema document 'myschema.xsd', because
1) could not find the document;
2) the document could not be read;
3) the root element of the document is not <xsd:schema>.
I've tried adding several things to the path, including ${__P(user.dir)} (points to the home dir of the user) and ${__BeanShell(pwd())} (doesn't return anything). I got it working by giving the absolute path, but the script is supposed to be used by others, so that's no good.
I could make it use a property value defined in the command line, but I'd like to avoid it as well, for the same reason.
How can I correctly point the Assertion to the schema under these circumstances?
Looks like you have to in this situation
validate your xml against xsd manually: simply use corresponding java code from e.g. BeanShell Assertion or BeanShell PostProcessor;
here is a pretty nice solution: https://stackoverflow.com/a/16054/993246 (as well you can use any other you want for this);
dig into jmeter's sources, amend XML Schema file obtaining to support variables in path (File Name field) - like CSV Data Set Config does;
but the previous way seems to be much easier;
run your jmeter test-scenario from shell-script or ant-task which will first copy your xsd to jmeter's /bin dir before script execution - at least XML Schema Assertion can be used "as is".
Perhaps if you will find any other/better - please share it.
Hope this helps.
Summary: in the end I've used http://path.to.schema/myschema.xsd as the File Name parameter in the Assertion.
Explanation: following Alies Belik's advice, I've found that the code for setting up the schema looks something like this:
DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
...
parserFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", xsdFileName);
where xsdFileName is a string (the attribute string is actually a constant, I inlined it for readability).
According to e.g. this page, the attribute, when in the form a String, is interpreted as an URI - which includes HTTP URLs. Since I already have the schema accessible through HTTP, I've opted for this solution.
Add the 'myschema.xsd' to the \bin directory of your apache-jmeter next to the 'ApacheJMeter.jar' or set the 'File Name' from the 'XML Schema Assertion' to your 'myschema.xsd' from this starting point.
E.g.
JMeter: C:\Users\username\programs\apache-jmeter-2.13\bin\ApacheJMeter.jar
Schema: C:\Users\username\workspace\yourTest\schema\myschema.xsd
File Name: ..\\..\\..\workspace\yourTest\schema\myschema.xsd

How to specify the name of the generate file to the e:worksheet function

We use the jboss seam-->excel module integration for generating excel sheets using e:worksheet. But the downloaded file name comes out as ExportUsers.jxl.xls, I would rather see this as ExportUsers.xls. How do I customize this information.
filename attribute of the e:workbook tag
<e:workbook filename="ExportUsers.xls" />
Take a look at the Seam excel documentation.
filename — The filename to use for the download. The value is a string. Please note that if you map the DocumentServlet to some pattern, this file extension must also match.

Resources