I am trying to replace the text value of a node using a groovy scripting transformer in Mule.
I first use a XML to DOM transformer then I am using the following
<scripting:transformer name="replacePassword">
<scripting:script engine="Groovy"><![CDATA[import org.dom4j.*
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory
Node passwordElement = message.payload.getRootElement().selectSingleNode("//*[local-name()=\'Password\']")
passwordElement.setTextContent("xxxxxxxxxxxxx")
return message.payload
]]></scripting:script>
</scripting:transformer>
But this seems to be throwing the following exception
Root Exception stack trace: groovy.lang.MissingMethodException: No
signature of method: org.dom4j.tree.DefaultElement.setTextContent() is
applicable for argument types: (java.lan g.String) values:
[xxxxxxxxxxxxx]
I am not too familiar with groovy is my script correct?
Thanks
just look at the documentation for org.dom4j.tree.DefaultElement
there is no setTextContent() method... but there is a setText() method
Went with this in the end, this will get a node and replace the text value
<scripting:transformer name="replacePassword">
<scripting:script engine="Groovy"><![CDATA[
node = message.payload.getRootElement().selectSingleNode('//*[local-name()=\'Password\'][1]');
node.text = 'xxxxxxx';
return message.payload;]]></scripting:script>
</scripting:transformer>
Related
I feel a bit silly for making this question, but I'm out of options.
Basically, I have this on a "let's learn groovy" project:
package com.mypackage.markupexercise
import groovy.xml.MarkupBuilder
println "Hello MarkupBuilder"
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
builder.records() {
example(id:1)
}
And I'm getting the following compilation error:
<path>\markupbuilderexercise\Main.groovy: 3: unable to resolve class groovy.xml.MarkupBuilder
# line 3, column 1.
import groovy.xml.MarkupBuilder
^
1 error
Now, I've seen [this question][1], and I have imported the groovy-xml-3.09.jar file (Through right click on project -> Properties -> Java Build Path -> Add Jars...)
There is nothing on the "Problems" tab, and if I try to run through the groovy console, I get the following error:
groovy.lang.MissingMethodException: No signature of method: groovy.xml.MarkupBuilder.records() is applicable for argument types: (com.neuro.groovyhelloworld.markupbuilderexercise.Main$_run_closure1) values: [com.neuro.groovyhelloworld.markupbuilderexercise.Main$_run_closure1#2e757861]
at com.neuro.groovyhelloworld.markupbuilderexercise.Main.run(Main.groovy:10)
at com.neuro.groovyhelloworld.markupbuilderexercise.Main.main(Main.groovy)
My take here is that I'm not adding the dependency in the right way, but I'm a Java developer and dependencies were either what I've done or just relying on Maven/Gradle, so I'm kind of out of ideas here.
What am I missing?
[1]: https://stackoverflow.com/questions/59132101/eclipse-groovy-unable-to-resolve-class
I see the same issue when choosing Run As > Groovy Console and then running the script. It does work fine for Run As > Groovy Script on the following source -- I used grab so I didn't need to add groovy-xml to my project's classpath:
#Grab('org.codehaus.groovy:groovy-xml:3.0.9')
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
new MarkupBuilder(writer).tap {
records {
example(id:1)
}
}
print writer
I get the following output:
<records>
<example id='1' />
</records>
You can also build the project and run the script using Run As > Java Application.
i use a method in telethon python3 library:
"client(GetMessagesRequest(peers,[pinnedMsgId]))"
this return :
ChannelMessages(pts=41065, count=0, messages=[Message(out=False, mentioned=False,
media_unread=False, silent=False, post=False, id=20465, from_id=111104071,
to_id=PeerChannel(channel_id=1111111111), fwd_from=None, via_bot_id=None,
reply_to_msg_id=None, date=datetime.utcfromtimestamp(1517325331),
message=' test message test', media=None, reply_markup=None,
entities=[], views=None, edit_date=None, post_author=None, grouped_id=None)],
chats=[Channel(creator=..............
i only need text of message ------> test message test
how can get that alone?
the telethon team say:
"This is not related to the library. You just need more Python knowledge so ask somewhere else"
thanks
Assuming you have saved the return value in some variable, say, result = client(...), you can access members of any instance through the dot operator:
result = client(...)
message = result.messages[0]
The [0] is a way to access the first element of a list (see the documentation for __getitem__). Since you want the text...:
text = message.message
Should do the trick.
Could some one help me how to mock this call?
Actual code
final ServicesLocal servicesBean = new WSDelegate().getServiceLocal();
here is my mock code
mockDelegate = mock(PortalDelegate.class);
PowerMockito.whenNew(PortalDelegate.class).withAnyArguments().thenReturn(mockPortalDelegate);
You have to add the when for the method invocation as well.
ServicesLocal mockServicesLocal = mock(ServicesLocal.class);
when(mockDelegate.getServiceLocal()).thenReturn(mockServicesLocal);
Using Scala Scripting Engine in 2.11 Milestone 7, how do I get a typed value back from the script engine? I'm getting error messages like "mypackage.Holler cannot be cast to mypackage.Holler".
Here is the use case (reduced to essentials). I want to use scripts to prepare and configure objects of a standard type that I will process in my main program. I have a trait:
package mypackage
trait Holler {
def shout: Unit
}
I have a user script in Scala, saved in the file /home/me/Foo.scala
object Foo extends mypackage.Holler {
def shout: Unit = println("Hello World!")
}
When I run this script using IMain.eval(Reader), I expect that the object Foo will be returned since it is the result of the last statement. Here is a program, including a couple useful printouts to run the script:
package mypackage
import javax.script.ScriptEngineManager
import scala.tools.nsc.interpreter.IMain
object Runner {
def main(args: Array[String]): Unit = {
// Create the script engine
val javaxEngine = new ScriptEngineManager().getEngineByName("scala")
val scalaEngine = javaEngine.asInstanceOf[IMain]
// Configure script engine to use the Java classpath
val useJavaClassPath = scalaEngine.settings.usejavacp.tryToSet(List("true"))
println("Use Java CP? " + useJavaClassPath)
val script = new java.io.FileReader("/home/me/Foo.scala")
val result = scalaEngine.eval(script)
println("Script Result Type: " + result.getClass.getName)
println("Defined Symbols: " + scalaEngine.definedSymbolList)
val myHoller = result.asInstanceOf[mypackage.Holler]
}
}
The script runs just fine under the script engine. But the result cannot be cast to Holler. The output of this program is as follows:
Use Java CP? Some(List(true))
Script Result Type: $line3.$read$$iw$$iw$Foo$
Defined Symbols: List(value engine, object iw$Foo)
Exception in thread "main" java.lang.ClassCastException: $line3.$read$$iw$$iw$Foo$ cannot be cast to mypackage.Holler
This tells me that the classpath is successfully recognized by the script engine, and that the Foo object is being constructed. But the trait mypackage.Holler (from the common classpath) inside the script is different from the trait mypackage.Holler in the main program.
If I add the following lines to the script:
Foo.shout
val result: Holler = Foo
I see:
The shout method being exercised ("Hello World!" prints out),
"result" is added to the list of defined symbols
result is clearly compatible with type Holler.
I can bind a "catcher" object to the script engine. Its code looks like this:
package mypackage
class Catcher {
var item: Holler = null
}
And I bind with
val mycatcher = new Catcher
scalaEngine.bind("catcher", mycatcher)
scalaEngine.eval("catcher = Foo")
Now "catcher" shows up in the list of defined symbols to the script engine and I can use the catcher to go into the script engine with a command like
scalaScriptEngine.eval("catcher.item = result")
But then I get strange "compile time" ClassCastExceptions saying:
mypackage.Holler cannot be cast to mypackage.Holler
If I make the "item" in the Catcher an Any, then I don't get the exception until I do
mycatcher.item.asInstanceOf[Holler]
in the main program. But I still get pretty much the same exception. It is as if two incompatible class loaders are being used with the same classpath. So how, from the main program, do I access the Foo object as an instance of Holler (which it clearly implements in the script engine)?
In Python I can execute arbitrary code using exec(string). How can I do this in Groovy? I'd like the code to execute in the context of my currently running application, not as if I were using the Groovy shell.
To execute a command-line program dynamically in Groovy:
"cmdstring".execute().text
You can also execute some Groovy code wrapped in a String with:
def myGroovyCode = 'println "hi"'
Eval.me(myGroovyCode) //prints hi
See http://groovy.codehaus.org/api/groovy/util/Eval.html
You can also pass in your current context parameters via the binding mechanism to the Groovy Shell.
def myname = 'Inigo Montoya'
def binding = new Binding( [ myname:myname ] )
new GroovyShell( binding ).evaluate( 'println "My Name is " + myname' )