How to replace underscore with dashes when building XML document with Nokogiri? - ruby

I'm building a new XML document using the following code:
doc = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do
reginfo {
client_type_id client_type == :associate ? ASSOCIATE : CLIENT
parent_ {
id_ client_type == :associate ? associate_id : customer_id
client_type_id client_type == :associate ? ASSOCIATE : CLIENT
vsn client_type == :associate ? associate_vsn : customer_vsn
}
}
end
The tags above listed as client_type_id show up in the XML file like client_type_id, but that is not the correct XML tag name format. I need them to be client-type-id.
I tried replacing the line with:
:"client-type-id" client_type == :associate ? ASSOCIATE : CLIENT
but I get:
syntax error, unexpected tIDENTIFIER, expecting '}'
:"client-type-id" client_type == :associate ? ASSOCIATE : CLIENT
^
or:
:"client-type-id" (client_type == :associate ? ASSOCIATE : CLIENT)
but I get:
syntax error, unexpected '(', expecting '}'
:"client-type-id" (client_type == :associate ? ASSOCIATE : CLIENT)
^
Is there a way to tell Nokogiri::XML::Builder:
on a per-line basis, to use dashes for a tag name and does it have a different syntax?
that for the entire document, during creation or after, to use dashes for all underscores in element names so that it forms correctly formatted XML element names?

There is a fancy way of doing this:
Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
...
xml.send :"client-type-id", (client_type == :associate ? ASSOCIATE : CLIENT)
...
end

Related

Can a logstash filter error be forwarded to elastic?

I'm having these json parsing errors from time to time:
2022-01-07T12:15:19,872][WARN ][logstash.filters.json ] Error parsing json
{:source=>"message", :raw=>" { the invalid json }", :exception=>#<LogStash::Json::ParserError: Unrecognized character escape 'x' (code 120)
Is there a way to get the :exception field in the logstash config file?
I opened the exact same thread on the elastic forum and got a working solution there. Thanks to #Badger on the forum, I ended up using the following raw ruby filter:
ruby {
code => '
#source = "message"
source = event.get(#source)
return unless source
begin
parsed = LogStash::Json.load(source)
rescue => e
event.set("jsonException", e.to_s)
return
end
#target = "jsonData"
if #target
event.set(#target, parsed)
end
'
}
which extracts the info I needed:
"jsonException" => "Unexpected character (',' (code 44)): was expecting a colon to separate field name and value\n at [Source: (byte[])\"{ \"baz\", \"oh!\" }\r\"; line: 1, column: 9]",
Or as the author of the solution suggested, get rid of the #target part and use the normal json filter for the rest of the data.

error in mule 4 "You cannot compare a value of type :Null"

I am trying to find the max of date from json data. But i am getting below error
Message : "You cannot compare a value of type :Null
Trace:
at reduce (Unknown)
at dw::Core::maxBy (line: 5535, column: 3)
at main (line: 1, column: 248)" evaluating expression:
"%dw 2.0 output application/json --- { Value2: ( if (vars.data.Value1 as String != "")
(payload maxBy((item) -> item.startDate)).startDate default vars.data.Value1
else "" ), RCount: sizeOf(payload) }".
Error type : MULE:EXPRESSION
Element : executeInterface/processors/8 # gg:gg.xml:121 (interface)
Element XML : <set-variable value="#[%dw 2.0 output application/json ---
{ Value2: ( if (vars.data.Value1 as String != "")
(payload maxBy((item) -> item.startDate)).startDate default vars.data.Value1
else "" ), RCount: sizeOf(payload) }]" doc:name="interface" doc:id="2c140185-2fc5-4e11-9b78-96fc2ddcfa2f" variableName="interface"></set-variable>
(set debug level logging or '-Dmule.verbose.exceptions=true' for everything).
The logic written in set variable component is
%dw 2.0
output application/json
---
{
Value2:
( if (vars.data.Value1 as String != "")
(payload maxBy((item) -> item.startDate)).startDate default vars.data.Value1
else ""
),
RCount: sizeOf(payload)
}
while running in the debug mode, found the problem is in maxby statement.
Please suggest.how to fix this issue
The error indicates that something is null when trying to compare. Given that you mentioned the error is at maxBy(), it is probable the the attribute startDate is null or not present in one of the elements. You should show also the values of the transformation so we could confirm it.
UPDATE: I can reproduce the error if the startDate attribute is not present or if it is misspelled. For example if I misspell item.StartDate (wrong uppercase 'S') it produces the error. Make sure the payload and script match exactly.

Why does this warning testCase return an error?

I have written the following validation Rule:
#Check
def checkDeclarationIsNotReferenceToItself(Declaration dec) {
if(dec.decCon.singleContent.reference == null && !dec.decCon.nextCon.isEmpty) {
//only proceed if it is a reference
return
}
var name = dec.name
if(dec.decCon.singleContent.reference.name == name) {
//only if the declaration is a self-reference without further actions
var warningMsg = "The declaration '" + name + "' is a reference to itself"
warning(warningMsg,
SQFPackage.eINSTANCE.declaration_DecCon,
SELFREFERENCE)
}
}
And then I have written an test case for it looking as following:
#Test
def void checkDeclarationIsNotReferenceToItselfTest() {
'''
test = 3;
test = test;
'''.parse.assertWarning(SQFPackage.eINSTANCE.decContent,
SQFValidator.SELFREFERENCE,
"The declaration 'test' is a reference to itself")
}
But when I run JUnit it reports an error:
Expected WARNING 'raven.sqf.SelfReference' on DecContent at [-1:-1] but got
WARNING (raven.sqf.SelfReference) 'The declaration 'test' is a reference to itself' on Declaration, offset 18, length 4
I don't understand this because it actually expects exactly that error message (As far as I see it)
Anyone has an idea why it doesn't work?
Greetings Krzmbrzl
looks like the way you create the warning and test the validation do not match together
warning(warningMsg,
SQFPackage.eINSTANCE.declaration_DecCon,
SELFREFERENCE)
creates the warning on a Declaration
.assertWarning(SQFPackage.eINSTANCE.decContent,
SQFValidator.SELFREFERENCE,
"The declaration 'test' is a reference to itself")
tests for a DecContent

How to stop ImageMagick in Ruby (Rmagick) evaluating an # sign in text annotation

In an app I recently built for a client the following code resulted in the variable #nameText being evaluated, and then resulting in an error 'no text' (since the variable doesn't exist).
To get around this I used gsub, as per the example below. Is there a way to tell Magick not to evaluate the string at all?
require 'RMagick'
#image = Magick::Image.read( '/path/to/image.jpg' ).first
#nameText = '#SomeTwitterUser'
#text = Magick::Draw.new
#text.font_family = 'Futura'
#text.pointsize = 22
#text.font_weight = Magick::BoldWeight
# Causes error 'no text'...
# #text.annotate( #image, 0,0,200,54, #nameText )
#text.annotate( #image, 0,0,200,54, #nameText.gsub('#', '\#') )
This is the C code from RMagick that is returning the error:
// Translate & store in Draw structure
draw->info->text = InterpretImageProperties(NULL, image, StringValuePtr(text));
if (!draw->info->text)
{
rb_raise(rb_eArgError, "no text");
}
It is the call to InterpretImageProperties that is modifying the input text - but it is not Ruby, or a Ruby instance variable that it is trying to reference. The function is defined here in the Image Magick core library: http://www.imagemagick.org/api/MagickCore/property_8c_source.html#l02966
Look a bit further down, and you can see the code:
/* handle a '#' replace string from file */
if (*p == '#') {
p++;
if (*p != '-' && (IsPathAccessible(p) == MagickFalse) ) {
(void) ThrowMagickException(&image->exception,GetMagickModule(),
OptionError,"UnableToAccessPath","%s",p);
return((char *) NULL);
}
return(FileToString(p,~0,&image->exception));
}
In summary, this is a core library feature which will attempt to load text from file (named SomeTwitterUser in your case, I have confirmed this -try it!), and your work-around is probably the best you can do.
For efficiency, and minimal changes to input strings, you could rely on the selectivity of the library code and only modify the string if it starts with #:
#text.annotate( #image, 0,0,200,54, #name_string.gsub( /^#/, '\#') )

Ruby libxml: format XMLParser to expand closing tags [duplicate]

libxml2 (for C) is not preserving empty elements in their original form on a save. It replaces <tag></tag> with <tag/> which is technically correct but causes problems for us.
xmlDocPtr doc = xmlParseFile("myfile.xml");
xmlNodePtr root = xmlSaveFile("mynewfile.xml", doc);
I've tried playing with the various options (using xlmReadFile) but none seem to affect the output. One post here mentioned disabling tag compression but the example was for PERL and I've found no analog for C.
Is there an option to disable this behavior?
Just found this enum in the xmlsave module documentation:
Enum xmlSaveOption {
XML_SAVE_FORMAT = 1 : format save output
XML_SAVE_NO_DECL = 2 : drop the xml declaration
XML_SAVE_NO_EMPTY = 4 : no empty tags
XML_SAVE_NO_XHTML = 8 : disable XHTML1 specific rules
XML_SAVE_XHTML = 16 : force XHTML1 specific rules
XML_SAVE_AS_XML = 32 : force XML serialization on HTML doc
XML_SAVE_AS_HTML = 64 : force HTML serialization on XML doc
XML_SAVE_WSNONSIG = 128 : format with non-significant whitespace
}
Maybe you can refactor your application to use this module for serialization, and play a little with these options. Specially with XML_SAVE_NO_EMPTY.
Your code may look like this:
xmlSaveCtxt *ctxt = xmlSaveToFilename("mynewfile.xml", "UTF-8", XML_SAVE_FORMAT | XML_SAVE_NO_EMPTY);
if (!ctxt || xmlSaveDoc(ctxt, doc) < 0 || xmlSaveClose(ctxt) < 0)
//...deal with the error

Resources