How to send an element multiple times in the same request in SoapUI using groovy - web-services

Can someone help with soap ui mock service? I want to send one part of my request n times.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:inv="http://www.testSoap.com/InvoiceService/">
<soapenv:Header/>
<soapenv:Body>
<inv:addInvoice>
<invoice>
<fkId>2</fkId>
<dateTime>08/02/2023</dateTime>
<status>none</status>
<!--1 or more repetitions:-->
<invoiceData>
<id>1</id>
<MPK>test</MPK>
<RK>test</RK>
<value>500</value>
</invoiceData>
<payments>
<pid>2</pid>
<type>xd</type>
<valueTotal>3000</valueTotal>
</payments>
</invoice>
</inv:addInvoice>
</soapenv:Body>
</soapenv:Envelope>
How can I add the invoiceData element 3 times? Do I change something in eclipse to do that?
def holder = new com.eviware.soapui.support.XmlHolder(mockRequest.requestContent )
// get arguments
def fkId = Integer.parseInt( holder["//fkId"] )
def dateTime = holder["//dateTime"]
def status = holder["//status"]
def id = Integer.parseInt(holder["//id"])
def MPK = holder["//MPK"]
def RK = holder["//RK"]
def value = Float.parseFloat(holder["//value"])
def pid = Integer.parseInt( holder["//pid"] )
def type = holder["//type"]
def valueTotal = Float.parseFloat(holder["//valueTotal"])
context.operationLogs += fkId
context.operationLogs1 += dateTime
context.operationLogs2 += status
context.operationLogs3 += id
context.operationLogs4 += MPK
context.operationLogs5 += RK
context.operationLogs6 += value
context.operationLogs7 += pid
context.operationLogs8 += type
context.operationLogs9 += valueTotal
requestContext.result1 = fkId
requestContext.result2 = dateTime
requestContext.result3 = status
requestContext.result4 = id
requestContext.result5 = MPK
requestContext.result6 = RK
requestContext.result7 = value
requestContext.result8 = pid
requestContext.result9 = type
requestContext.result10 = valueTotal
requestContext.result = [fkId, dateTime,status,id,MPK,RK,value,pid,valueTotal ]
context.fkId = context.operationLogs.size
context.fkId = context.operationLogs1.size
context.fkId = context.operationLogs2.size
context.fkId = context.operationLogs3.size
context.fkId = context.operationLogs4.size
context.fkId = context.operationLogs5.size
context.fkId = context.operationLogs6.size
context.fkId = context.operationLogs7.size
context.fkId = context.operationLogs8.size
context.fkId = context.operationLogs9.size
How i can send multiple tiem this part request
<!--1 or more repetitions:-->
<invoiceData>
<id>1</id>
<MPK>test</MPK>
<RK>test</RK>
<value>500</value>
</invoiceData>
i have one or more repatitons by i always send only one time
The results should be something like this using
SupplierData elements, but when I try to add the invoiceData element using my Form 3 times I only get 1 invoiceData element and the 2nd and 3rd elements are missing.

Related

list indices must be integers or slices, not dict in django

I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict
payload:
[{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}]
views.py:
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = request.data[ran].get('AuditorId')
ticketid = request.data[ran].get('TicketId')
qid = request.data[ran].get('QId')
answer = request.data[ran].get('Answer')
sid = '0'
TicketType = request.data[ran].get('TicketType')
TypeSelected = request.data[ran].get('TypeSelected')
agents = request.data[ran].get('Agents')
supervisor = request.data[ran].get('Supervisor')
Comments = request.data[ran].get('Comments')
action = request.data[ran].get('Action')
subfunction = request.data[ran].get('AuditSubFunction')
region = request.data[ran].get('AuditRegion')
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] #auditorid=%s,#ticketid=%s,#qid=%s,#answer=%s,#sid=%s,#TicketType=%s,#TypeSelected=%s,#agents=%s, #supervisor =%s, #Comments=%s, #action=%s, #subfunction=%s, #region=%s',
(auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region))
return Response(True)
I ran this code on my machine and it works for the payload you provided.
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = ran.get('AuditorId')
ticketid = ran.get('TicketId')
qid = ran.get('QId')
answer = ran.get('Answer')
sid = '0'
TicketType = ran.get('TicketType')
TypeSelected = ran.get('TypeSelected')
agents = ran.get('Agents')
supervisor = ran.get('Supervisor')
Comments = ran.get('Comments')
action = ran.get('Action')
subfunction = ran.get('AuditSubFunction')
region = ran.get('AuditRegion')
If it doesn't then content of request.data must be different then payload you shared in original post

500 Internal Server Error error in Webservice request

I have an existing jar which sends web-service request from one of our application server to another. Below is the code for sending the request
public IUsbMessage executeOutboundRequest(IUsbMessage paramIUsbMessage)
{
IUsbMessage localIUsbMessage = UsbMessageFactory.createUbusMessage();
try
{
LogManager.logDebug("ServiceProvider:- Enter executeOutboundRequest");
Object[] arrayOfObject = (Object[])paramIUsbMessage.getPayload();
NVPVO localNVPVO = (NVPVO)arrayOfObject[1];
String str1 = (String)localNVPVO.getHashmap().get("endPointUrl");
String str2 = (String)localNVPVO.getHashmap().get("respTag");
String str3 = (String)localNVPVO.getHashmap().get("body");
str3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><FIXML xsi:schemaLocation=\"http://www.oracle.com/fixml AcctInq.xsd\" xmlns=\"http://www.oracle.com/fixml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + str3.trim();
LogManager.logDebug("ServiceProvider:- RequestXMLMsg" + str3);
MessageFactory localMessageFactory = MessageFactory.newInstance();
SOAPMessage localSOAPMessage1 = localMessageFactory.createMessage();
SOAPFactory localSOAPFactory = SOAPFactory.newInstance();
SOAPBody localSOAPBody = localSOAPMessage1.getSOAPBody();
SOAPElement localSOAPElement1 = localSOAPBody.addChildElement(localSOAPFactory.createName("executeService"));
SOAPElement localSOAPElement2 = localSOAPElement1.addChildElement(localSOAPFactory.createName("arg_0_0"));
localSOAPElement2.addTextNode(str3);
localSOAPMessage1.saveChanges();
localSOAPMessage1.writeTo(System.out);
SOAPConnectionFactory localSOAPConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection localSOAPConnection = localSOAPConnectionFactory.createConnection();
LogManager.logDebug("ServiceProvider:- endPointUrl" + str1);
LogManager.logDebug("ServiceProvider:- respTag" + str2);
URL localURL = new URL(str1);
SOAPMessage localSOAPMessage2 = localSOAPConnection.call(localSOAPMessage1, localURL);
DocumentBuilderFactory localDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder localDocumentBuilder = localDocumentBuilderFactory.newDocumentBuilder();
Document localDocument = localDocumentBuilder.newDocument();
Element localElement1 = null;
Element localElement2 = null;
Text localText = null;
Element localElement3 = null;
Iterator localIterator = localSOAPMessage2.getSOAPBody().getChildElements();
Object localObject2;
Object localObject3;
while (localIterator.hasNext())
{
localObject1 = (SOAPElement)localIterator.next();
localElement1 = localDocument.createElement(((SOAPElement)localObject1).getNodeName());
localObject2 = ((SOAPElement)localObject1).getAttributes();
Object localObject4;
if (((NamedNodeMap)localObject2).getLength() > 0) {
for (int i = 0; i < ((NamedNodeMap)localObject2).getLength(); i++)
{
localObject4 = ((NamedNodeMap)localObject2).item(i);
localElement1.setAttribute(((Node)localObject4).getNodeName(), ((Node)localObject4).getNodeValue());
}
}
localElement3 = localElement1;
localObject3 = ((SOAPElement)localObject1).getChildElements();
while (((Iterator)localObject3).hasNext())
{
localObject4 = (SOAPElement)((Iterator)localObject3).next();
localElement1 = localDocument.createElement(((SOAPElement)localObject4).getNodeName());
NamedNodeMap localNamedNodeMap = ((SOAPElement)localObject1).getAttributes();
if (localNamedNodeMap.getLength() > 0) {
for (int j = 0; j < localNamedNodeMap.getLength(); j++)
{
Node localNode = localNamedNodeMap.item(j);
localElement1.setAttribute(localNode.getNodeName(), localNode.getNodeValue());
}
}
localElement2 = localElement1;
localText = localDocument.createTextNode(((SOAPElement)localObject4).getValue());
localElement2.appendChild(localText);
localElement3.appendChild(localElement2);
}
The data which is being passed to the class file is as below containing the request XML and other details
respTag=AcctInqRs,
body=<Header>
<RequestHeader>
<MessageKey>
<RequestUUID>Req_159538426</RequestUUID>
<ServiceRequestId>AcctInq</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>OR</ChannelId>
<LanguageId></LanguageId>
</MessageKey>
<RequestMessageInfo>
<BankId>54</BankId>
<TimeZone></TimeZone>
<EntityId></EntityId>
<EntityType></EntityType>
<ArmCorrelationId></ArmCorrelationId>
<MessageDateTime>2020-02-23T14:27:22.627</MessageDateTime>
</RequestMessageInfo>
<Security>
<Token>
<PasswordToken>
<UserId></UserId>
<Password></Password>
</PasswordToken>
</Token>
<FICertToken></FICertToken>
<RealUserLoginSessionId></RealUserLoginSessionId>
<RealUser></RealUser>
<RealUserPwd></RealUserPwd>
<SSOTransferToken></SSOTransferToken>
</Security>
</RequestHeader>
</Header>
<Body>
<AcctInqRequest>
<AcctInqRq>
<AcctId>
<AcctId>1101614</AcctId>
</AcctId>
</AcctInqRq>
</AcctInqRequest>
</Body>
</FIXML>,
reqhdr.requestuuid=FINCORE240716215711,
endPointUrl=https://ORPREPROD.domain.com:20322/fiwebservice/FIWebService,
reqhdr.messagedatetime=2020-04-21T21:57:11.000,
reqhdr.servicerequestversion=10.2,
reqhdr.origchannelid=COR,
reqhdr.bankid=54,
reqhdr.servicerequestid=AcctInq
Now the issue is that the request is being sent from server A to server B. Once the request reaches server B it is throwing error "HTTP/1.1 500 Internal Server Error" and the below xml is seen in the logs
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header/>
<env:Body>
<env:Fault xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>**Failed to get operation name from incoming request**</faultstring>
</env:Fault>
</env:Body>
</env:Envelope>
On both the servers our application is deployed on Weblogic and the above errors are from weblogic logs. Can anyone please help me to determine the exact cause of this error, I am totally stuck and clueless about what to do.
The same request XML when sent through SOAP UI works perfectly.
The below request XML works in SOAPUI
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:web="http://webservice.fiusb.ci.ibm.com/">
<soapenv:Header/>
<soapenv:Body>
<web:executeService>
<arg_0_0><![CDATA[<FIXML xsi:schemaLocation="http://www.finacle.com/fixml AcctInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><RequestHeader><MessageKey><RequestUUID>Req_158495384262711</RequestUUID><ServiceRequestId>AcctInq</ServiceRequestId><ServiceRequestVersion>10.2</ServiceRequestVersion><ChannelId>COR</ChannelId><LanguageId></LanguageId></MessageKey><RequestMessageInfo><BankId>54</BankId><TimeZone></TimeZone><EntityId></EntityId><EntityType></EntityType><ArmCorrelationId></ArmCorrelationId><MessageDateTime>2020-02-23T14:27:22.627</MessageDateTime></RequestMessageInfo><Security><Token><PasswordToken><UserId></UserId><Password></Password></PasswordToken></Token><FICertToken></FICertToken><RealUserLoginSessionId></RealUserLoginSessionId><RealUser></RealUser><RealUserPwd></RealUserPwd><SSOTransferToken></SSOTransferToken></Security></RequestHeader></Header><Body><AcctInqRequest><AcctInqRq><AcctId><AcctId>1100161916154</AcctId></AcctId></AcctInqRq></AcctInqRequest></Body></FIXML>
]]></arg_0_0>
</web:executeService>
</soapenv:Body>
</soapenv:Envelope>
The below XML throws the same error "Failed to get operation name from incoming request"
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:web="http://webservice.fiusb.ci.ibm.com">
<soapenv:Header/>
<soapenv:Body>
<web:executeService>
<arg_0_0><![CDATA[<FIXML xsi:schemaLocation="http://www.finacle.com/fixml AcctInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Header><RequestHeader><MessageKey><RequestUUID>Req_158495384262711</RequestUUID><ServiceRequestId>AcctInq</ServiceRequestId><ServiceRequestVersion>10.2</ServiceRequestVersion><ChannelId>COR</ChannelId><LanguageId></LanguageId></MessageKey><RequestMessageInfo><BankId>54</BankId><TimeZone></TimeZone><EntityId></EntityId><EntityType></EntityType><ArmCorrelationId></ArmCorrelationId><MessageDateTime>2020-02-23T14:27:22.627</MessageDateTime></RequestMessageInfo><Security><Token><PasswordToken><UserId></UserId><Password></Password></PasswordToken></Token><FICertToken></FICertToken><RealUserLoginSessionId></RealUserLoginSessionId><RealUser></RealUser><RealUserPwd></RealUserPwd><SSOTransferToken></SSOTransferToken></Security></RequestHeader></Header><Body><AcctInqRequest><AcctInqRq><AcctId><AcctId>1100161916154</AcctId></AcctId></AcctInqRq></AcctInqRequest></Body></FIXML>
]]></arg_0_0>
</web:executeService>
</soapenv:Body>
</soapenv:Envelope>
Notice the forward slash(/) at the end of namespace. If the slash is not there in the namespace it throws the error in SOAP UI.
Please help me to understand how can I change namespace in my java code

django handle slowly when doing Stress Testing

i had built django server to handle some work.And when i sent 10000 requests to django,django will became slow after 4000th requests,it will report socket timeout randomly.And i take this one data to test it alone,it is ok.So,how can i fix this bug?
i have no idea to fix it
def handle(request) :
sys.stderr.write( "[info]request come in {} \n".format(sys._getframe().f_code.co_name))
ret_dict = dict()
ret_str = ""
if ("vid" in request.GET) and ("title" in request.GET):
id = request.GET["id"]
title = urllib.parse.unquote(request.GET["title"],encoding ='utf-8')
title = request.GET["title"]
req_video = dict()
req_video["vid"] = vid
req_video["title"] = title
tags = handle_function(req_video)
ret_dict["vid"] = vid
ret_dict["tags"] = tags
ret_str = json.dumps(ret_dict)
return HttpResponse(ret_str)
client codes:
for line in sys.stdin:
line = line.rstrip('\n')
fields = line.split("\t")
vid = fields[0]
title = fields[1]
page_params_mq = {'vid':vid,'title':title}
try :
rec_mq_res = get_rec_mingqiang(server_ip_mq, server_port_mq, web_page_mq, page_params_mq)
except:
print (line)
continue
vid = rec_mq_res["vid"]
tags = rec_mq_res["tags"]
fo.write(vid+"\t"+tags+"\n")
cat test_data|python client.py, there are 10000 rows in test_data,and it send request sequentially,and will be hunt randomly after 4000.
django can handle these requests quickly

Http body empty when adding customer via prestashop webservice

I'm trying to add a new customer via webservice to my prestashop database but in appearance, everything is OK, returned code 200 but response xml body is empty and database has no new customers.
I've enabled webservice for the GET and PUT crud methods and generate API Key.
Code for the customer addition is the next one:
require_once('../../../lib/PSWebServiceLibrary.php');
$id_customer = 0;
$id_address = 0;
$id_cart = 0;
$date_now = date("Y-m-d H:i:s");
try {
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
foreach ($pedidos->orders as $ord) {
if (!$id_customer) {
// Getting the empty XML document to send back completed
$xml = $webService->get(array('url' => PS_SHOP_PATH . 'api/customers?schema=blank'));
// Adding dinamic values
// Required
$xml->customer->passwd = Tools::encrypt($password = 'mypassword');
$xml->customer->lastname = $ord->customer->lastname;
$xml->customer->firstname = $ord->customer->firstname;
$xml->customer->email = $ord->customer->customer_id.'#example.com';
// Others
$xml->customer->id_lang = 1;//$id_lang;
$xml->customer->id_shop = 1;
$xml->customer->id_shop_group = 1;
$xml->customer->id_default_group = 3;//$id_group; // Customers
$xml->customer->active = 1;
$xml->customer->newsletter = 0;
$xml->customer->newsletter_date_add = $date_now;
$xml->customer->last_passwd_gen = $date_now;
$xml->customer->date_add = $date_now;
$xml->customer->date_upd = $date_now;
$xml->customer->id_gender = 0;
$xml->customer->associations->groups->group[0]->id = 3; // customers
// Adding the new customer
$opt = array('resource' => 'customers');
$opt['postXml'] = $xml->asXML();
$xml = $webService->add($opt);
$id_customer = $xml->customer->id;
}
}
}catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}
When executed, this one returns a code 200 but the response body is completely empty.
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<customer>
<id></id>
<id_default_group></id_default_group>
<id_lang></id_lang>
<newsletter_date_add></newsletter_date_add>
<ip_registration_newsletter></ip_registration_newsletter>
<last_passwd_gen></last_passwd_gen>
<secure_key></secure_key>
<deleted></deleted>
<passwd></passwd>
<lastname></lastname>
<firstname></firstname>
<email></email>
<id_gender></id_gender>
<birthday></birthday>
<newsletter></newsletter>
<optin></optin>
<website></website>
<company></company>
<siret></siret>
<ape></ape>
<outstanding_allow_amount></outstanding_allow_amount>
<show_public_prices></show_public_prices>
<id_risk></id_risk>
<max_payment_days></max_payment_days>
<active></active>
<note></note>
<is_guest></is_guest>
<id_shop></id_shop>
<id_shop_group></id_shop_group>
<date_add></date_add>
<date_upd></date_upd>
<associations>
<groups>
<group>
<id></id>
</group>
</groups>
</associations>
</customer>
</prestashop>
Anyone knows why is this happening? Thanks for your time.
Asked myself. In my case explained on top, I need one webservice per order so:
$webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, DEBUG);
This line must be inside foreach iteraction.

Get SOAP attachment

There is a lot of questions with same subject, but no replies, especially about receiving. There exist example how to send attachment, but I didn't found how to receive it.
Is there any solution on python for receiving attachments? I even agree to change my SOAP tool from suds to anything that will works.
Thank you in advance.
I solved it with suds.
def GetWithFile(self, client, servicename, modelthings):
func = client.get_suds_func('Retrieve' + servicename)
clientclass = func.clientclass({})
SoapClient = clientclass(func.client, func.method)
binding = func.method.binding.input
soap_xml = binding.get_message(func.method, [modelthings], {})
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentInfo="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentData="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'ignoreEmptyElements="true"')
SoapClient.last_sent(soap_xml)
plugins = PluginContainer(SoapClient.options.plugins)
plugins.message.marshalled(envelope=soap_xml.root())
if SoapClient.options.prettyxml:
soap_xml = soap_xml.str()
else:
soap_xml = soap_xml.plain()
soap_xml = soap_xml.encode('utf-8')
plugins.message.sending(envelope=soap_xml)
request = Request(SoapClient.location(), soap_xml)
request.headers = SoapClient.headers()
reply = SoapClient.options.transport.send(request)
print(reply)
Files = []
boundary = self.find_substring(reply.headers['content-type'], 'boundary="', '"')
if boundary is not "":
list_of_data = reply.message.split(boundary)
list_of_data.pop(0)
list_of_data.pop(len(list_of_data) - 1)
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(list_of_data[0], '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
for line in list_of_data[1:]:
File = SMFile()
Files.append(File)
File.filename = self.find_substring(line, 'Content-Location: ', '\r\n')
File.key = self.find_substring(line, 'Content-ID: ', '\r\n')
idx = line.index( 'Content-ID:' )
start_idx = line.index( '\r\n\r\n' , idx ) + len('\r\n\r\n')
fin_idx = line.rindex( '\r\n--', start_idx )
File.body = line[start_idx: fin_idx]
File.size = fin_idx - start_idx
else:
soap_body = '<SOAP-ENV:Envelope' + self.find_substring(reply.message, '<SOAP-ENV:Envelope', '</SOAP-ENV:Envelope>') + '</SOAP-ENV:Envelope>'
ctx = plugins.message.received(reply=soap_body)
soap_body = ctx.reply
if SoapClient.options.retxml:
answer = soap_body
else:
answer = SoapClient.succeeded(binding, soap_body)
dict = {}
self.FieldsToDict(answer.model.instance, dict)
return {u'body': answer, u'Files': Files}
Here we extract some low level of suds, being able to fix any field in envelope. Then, after reply was got, we parse all boundaries and receive as many files, as we got.