GroovyRuntime Error when validating Schema - groovy

I am learning how to use ReadyAPI and trying to validate a response's XML content against a Schema file. My code is pretty simple, but I am receiving "Could not find named-arg compatible constructor". I have confirmed the existence of the schema file. And that there is an appropriate response in XML format. I have peppered the code with logs but still don't have any idea where to focus.
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory
import com.eviware.soapui.support.XmlHolder
// retrieve schema file
def xsdSchema = "/schema/v2_0/qm.xsd"
log.info xsdSchema.toString()
// get the XML Response
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def response = groovyUtils.getXmlHolder( 'Get Test Case Result#ResponseAsXML' )
log.info response
// create validation objects
def factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
def schema = factory.newSchema(new StreamSource(xsdSchema))
def validator = schema.newValidator()
log.info factory.toString()
log.info schema.toString()
log.info validator.toString()
// Validate the response against the schema
assert validator.validate(new StreamSource(new StringReader(response))) == null // This is line 28
The output of my logs are as follows:
Wed Jan 25 13:15:43 EST 2023: INFO: /schema/v2_0/qm.xsd
Wed Jan 25 13:15:43 EST 2023: INFO: com.eviware.soapui.support.XmlHolder#79c0a307
Wed Jan 25 13:15:44 EST 2023: INFO: org.apache.xerces.jaxp.validation.XMLSchemaFactory#a4effe4
Wed Jan 25 13:15:44 EST 2023: INFO: org.apache.xerces.jaxp.validation.XMLSchema#1a8a805d
Wed Jan 25 13:15:44 EST 2023: INFO: org.apache.xerces.jaxp.validation.ValidatorImpl#201dce24
Full Error message:
groovy.lang.GroovyRuntimeException: Could not find named-arg compatible constructor. Expecting one of:
java.io.StringReader(com.eviware.soapui.support.XmlHolder)
java.io.StringReader()
error at line: 28

Related

fix RelatedObjectDoesNotExist at /agents/ error in django

i am creating a django CRM website but i a have a problem once i want relate the User to an organisation.
Note :
the user must be logged in in order to be able to create agent
model.py
class User(AbstractUser):
pass
class UserProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)# every USER has one profile
def __str__(self):
return self.user.username
class Agent(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)# every agent has one user
organisation = models.ForeignKey(UserProfile,on_delete=models.CASCADE)
def __str__(self):
return self.user.email
# create signal to listen to event in order to create a profile user once a new user is created.
def post_user_created_signal(sender,instance,created,**kwargs):
if created:
UserProfile.objects.create(user = instance)
post_save.connect(post_user_created_signal,sender=User)
views.py
class AgentCreateView(LoginRequiredMixin, generic.CreateView)
template_name = "agent_create.html"
form_class = AgentModelForm
def get_success_url(self):
return reverse("agents:agent-list")
def form_valid(self, form):
agent = form.save(commit=False)
agent.organisation = self.request.user.userprofile
agent.save()
return super(AgentCreateView, self).form_valid(form)
once the user try to create an agent this error below is displayed.
RelatedObjectDoesNotExist at /agents/
User has no userprofile.
Request Method: GET Request URL: http://127.0.0.1:8000/agents/
Django Version: 4.0.6 Exception Type: RelatedObjectDoesNotExist
Exception Value:
User has no userprofile.
Exception Location: C:\Users\LT
GM\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py,
line 461, in get Python Executable: C:\Users\LT
GM\AppData\Local\Programs\Python\Python310\python.exe Python Version:
3.10.4 Python Path:
['F:\DJANGO', 'C:\Users\LT
GM\AppData\Local\Programs\Python\Python310\python310.zip',
'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\DLLs',
'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib',
'C:\Users\LT GM\AppData\Local\Programs\Python\Python310',
'C:\Users\LT '
'GM\AppData\Local\Programs\Python\Python310\lib\site-packages',
'C:\Users\LT '
'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32',
'C:\Users\LT '
'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib',
'C:\Users\LT '
'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin']
Server time: Sun, 17 Jul 2022 18:54:40 +0000
Problem string is here:
agent.organisation = self.request.user.userprofile
The self.request.user has no userprofile yet.
Perhaps you need to change the logic in your code.

Need help in looping input in Groovy Script

I have an input from which I am converting unix time and passing values based on 30 days condition, However the below script fails , Can anyone help here as I am new to groovy
Groovy:
def outputResult = """
{"view":
{"User0":
[{"id":"0001"},
{"id":"0002","lastLogin":1579783088323},
{"id":"003"},
{"id":"004","lastLogin":1641740132988}]
}
}
"""
ObjectMapper mapper = new ObjectMapper()
def response = mapper.readValue(outputResult, Map.class)
def thirtyDaysAgo = System.currentTimeMillis() - (30*24*60*60*1000)
response['view']['User0'].findAll{ it['lastLogin'] && it['lastLogin'] <
thirtyDaysAgo }.each{
loggerApi.info("Disabling user ${it['userName']} - lastLogin: ${(new
Date(it['lastLogin']).toString())}")
userApi.changeUser(ChangeUserRequest.builder().id(string2Uuid(it['id'])).
enabled(false).build())
}
Something straight-forward:
import groovy.json.*
def outputResult = """
{"view":
{"User0":
[{"id":"0001"},
{"id":"0002","lastLogin":1579783088323},
{"id":"003"},
{"id":"004","lastLogin":1641740132988}]
}
}
"""
Map json = new JsonSlurper().parseText outputResult
long thirtyDaysAgo = System.currentTimeMillis() - (30*24*60*60*1000)
json.view.User0.each{
if( it.lastLogin && it.lastLogin < thirtyDaysAgo ){
println "Disabling user $it.id -> ${new Date( it.lastLogin )}"
}
}
would print
Disabling user 0002 -> Thu Jan 23 12:38:08 UTC 2020
Disabling user 004 -> Sun Jan 09 14:55:32 UTC 2022

cometd: published message to a channel does not show up in subscribed listener

I am trying to publish a test data into the cometd-demo server channel members/hello/. handshake done, can get a subscribed message on callback and can get published message on publish() callback. But i can't get that published message on subscribe() listener.
Groovy Script:
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Message.Mutable
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.client.ClientSessionChannel.MessageListener;
import org.cometd.client.BayeuxClient
import org.cometd.client.transport.ClientTransport
import org.cometd.client.transport.LongPollingTransport
import org.eclipse.jetty.client.HttpClient as MyHttpClient
ClientSessionChannel.MessageListener mylistener = new Mylistener();
def myurl = "http://localhost:8080/cometd/"
MyHttpClient httpClient = new MyHttpClient();
httpClient.start()
Map<String, Object> options = new HashMap<String, Object>();
ClientTransport transport = new LongPollingTransport(options, httpClient);
BayeuxClient client = new BayeuxClient(myurl, transport)
client.handshake(30000)
def channel = client.getChannel("/members/hello/")
channel.subscribe(mylistener,mylistener)
while (true)
{
sleep(5000)
channel.publish( 'hai' )
}
class Mylistener implements ClientSessionChannel.MessageListener {
public void onMessage(ClientSessionChannel channel, Message message) {
println message
}
}
While running this script I can't get the published data on listener even JVM not killed with the while loop. What am I missing?
You have specified incorrect channel path in:
def channel = client.getChannel("/members/hello/")
Channel path cannot end with / - it should be /members/hello.
Also double check if you use correct URL. I've used very simple CometD server application (https://github.com/wololock/dojo-jetty9-primer) that uses /dojo-jetty9-primer/ context path, so in my case URL to CometD server was:
def url = "http://localhost:8080/dojo-jetty9-primer/cometd/"
You can also simplify your script to something like that:
import org.cometd.bayeux.Message
import org.cometd.bayeux.client.ClientSessionChannel
import org.cometd.client.BayeuxClient
import org.cometd.client.transport.LongPollingTransport
import org.eclipse.jetty.client.HttpClient
final String url = "http://localhost:8080/dojo-jetty9-primer/cometd/"
final HttpClient httpClient = new HttpClient()
httpClient.start()
final BayeuxClient client = new BayeuxClient(url, new LongPollingTransport([:], httpClient))
client.handshake()
client.waitFor(1000, BayeuxClient.State.CONNECTED)
final ClientSessionChannel channel = client.getChannel("/members/hello")
channel.subscribe(new MyListener())
while (true) {
sleep(1000)
channel.publish("test")
}
class MyListener implements ClientSessionChannel.MessageListener {
#Override
void onMessage(ClientSessionChannel channel, Message message) {
println "[${new Date()}] Received message from channel (${channel.id}): ${message}"
}
}
Especially a part client.handshake(30000) can be simplified in your script - you don't have to wait 30 seconds here.
When you run it you will see a new message showing up in the console every 1 second:
[Mon Feb 19 10:15:02 CET 2018] Received message from channel (/members/hello): [data:test, channel:/members/hello]
[Mon Feb 19 10:15:03 CET 2018] Received message from channel (/members/hello): [data:test, channel:/members/hello]
[Mon Feb 19 10:15:04 CET 2018] Received message from channel (/members/hello): [data:test, channel:/members/hello]
[Mon Feb 19 10:15:05 CET 2018] Received message from channel (/members/hello): [data:test, channel:/members/hello]
[Mon Feb 19 10:15:06 CET 2018] Received message from channel (/members/hello): [data:test, channel:/members/hello]
Hope it helps.

Getting no response when I run the following database connection script from Groovy[Soapui]

I am trying to run this script from Groovy[soapUI] but i am not getting errors and not the sql command is not returning any results. am I missing anything crucial here?
import groovy.sql.Sql
import java.sql.*
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
// ssh login
String sshHost = 'test.com'
String sshUser = 'test'
String sshPass = 'test'
int sshPort = 22
// database login
targetHost = 'localhost'
targetUser = 'test'
targetPass = 'test'
targetPort = 3306
lport = 4328
JSch jsch = new JSch();
Session session = jsch.getSession(sshUser, sshHost, sshPort);
session.setPassword(sshPass);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, targetHost, targetPort);
Connection con = null;
String driver = "org.mariadb.jdbc.Driver";
String connectionString = "jdbc:mariadb://" + targetHost +":" + lport + "/";
con = DriverManager.getConnection(connectionString, targetUser, targetPass);
Statement st = con.createStatement();
String sql = "select * from SS_System.tblcompanies where companyid=495555"
st.executeQuery(sql);
st.close()
session.disconnect()
Also, after adding bunch of log.info statements I am getting the following response:
Sun Nov 13 21:39:30 EST 2016:INFO:com.jcraft.jsch.Session#4e6b3063
Sun Nov 13 21:39:31 EST 2016:INFO:null
Sun Nov 13 21:39:31 EST 2016:INFO:4336
Sun Nov 13 21:39:31 EST 2016:INFO:jdbc:mysql://localhost:4336/
Sun Nov 13 21:39:31 EST 2016:INFO:org.mariadb.jdbc.MariaDbConnection#14f67389
Sun Nov 13 21:39:31 EST 2016:INFO:org.mariadb.jdbc.MariaDbStatement#401b321f
Sun Nov 13 21:39:31 EST 2016:INFO:org.mariadb.jdbc.internal.queryresults.resultset.MariaSelectResultSet#74b9f5af
Perhaps you should do something with the query result
// instead of this
st.executeQuery(sql)
// do something like
java.sql.ResultSet rs = st.executeQuery(query);
and then iterate results as described here https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html#processing_resultset_objects
while (rs.next()) {
String value = rs.getString("COLUMN_NAME");
log.info("COLUMN_NAME:"+value)
}

Using XMLParser on SoapUI response

Trouble using XmlParser in SoapUI Pro
Hi, I am trying to use 'xml parser' to validate my xml responses in SoapUI Pro.
I have been playing around with this in a groovy script and I can access the tags if I declare and assign my xml within the groovy script like so
This works if I declare the xml in the script ..
def xml = """
<NS1:createShipmentResponse xmlns:NS1="http://www.royalmailgroup.com/api/ship/V1">
<NS1:integrationHeader>
<dateTime xmlns="http://www.royalmailgroup.com/integration /core/V1">2013-12-24T22:20:34</dateTime>
<version xmlns="http://www.royalmailgroup.com/integration/core/V1">1</version>
<identification xmlns="http://www.royalmailgroup.com/integration/core/V1">
<applicationId>111111113</applicationId>
<transactionId>420642961</transactionId>
</identification>
</NS1:integrationHeader>
<NS1:completedShipmentInfo>
//xml not complete, other info in here.
</NS1:completedShipmentInfo>
<NS1:integrationFooter>
<warnings xmlns="http://www.royalmailgroup.com/integration/core/V1">
<warning>
<warningCode>W0022</warningCode>
<warningDescription>The customerReference specified is longer than 12 characters and has been truncated</warningDescription>
</warning>
<warning>
<warningCode>W0026</warningCode>
<warningDescription>The departmentReference specified is invalid and will be ignored</warningDescription>
</warning>
</warnings>
</NS1:integrationFooter>
</NS1:createShipmentResponse>
"""
def parser = new XmlParser().parseText(xml)
parser.'NS1:integrationFooter'.warnings.warning.warningCode.each{
log.info it.text()
}
But it doesn't seem to work within a running test instance when I instantiate the xmlParser variable from my Soap response as below.
def response = context.expand( '${createShipment_v04#Response}' );
I know that the parser variable has been assigned the xml response because when I can print it to the log ..
i.e. log.info parser prints ...
Wed Jan 08 16:33:38 GMT 2014:INFO:{http://schemas.xmlsoap.org/soap/envelope /}Envelope[attributes={}; value=[{http://schemas.xmlsoap.org/soap/envelope/}Body[attributes={}; value=[{http://www.royalmailgroup.com/api/ship/V1}createShipmentResponse[attributes={}; value=[{http://www.royalmailgroup.com/api/ship/V1}integrationHeader[attributes={}; .......
But below code does not print anything when I instantiate the xmlParser request from the soap response.
parser.'NS1:integrationFooter'.warnings.warning.warningCode.each{
log.info it.text()
}
Any help would be much appreciated.
I believe you are working at the wrong level.
parser.Body….
Ok. It turns out I don't need the 'NS1:' part. The below works ..
slurper.Body.createShipmentResponse.integrationFooter.warnings.warning.warningCode.each{
log.info it.text()
}
Following should work:
def response = context.expand( '${createShipment_v04#Response}' );
def parser = new XmlSlurper().parseText(response)
def warningCodes = parser.'**'.findAll {
it.name()=='warningCode'
}
warningCodes.each {
log.info it
}

Resources