My goal is to test my services depending on their service HTTP status.
When I launch my request, just services set by the 200 value succeed but another status like 400, 500, etc. failed that can be seen on the logs.
I am using soaPUI for a testing application located on the Tomcat server. The tracks of my requests are logged on another application before that test, the HTTP status was unique and set for all called services.
Now, for my test I have to dissociate the HTTP status code of my services, that is to each service with its own HTTP status depending on my tests needs.
code:
import com.eviware.soapui.impl.rest.mock.RestMockResult
import java.nio.charset.Charset
import com.eviware.soapui.model.mock.MockRunListener
import groovy.json.JsonSlurper
httpStatus = 200
def writeOut(fileEndPath, mockResult, method) {
def jsonFile = new File(dataDir + fileEndPath)
log.info "jsonFile " + jsonFile
if("GET".equalsIgnoreCase(method)){
mockRequest.httpResponse.status = httpStatus
mockRequest.httpResponse.setContentType("application/json")
mockRequest.httpResponse.writer.print(jsonFile.getText("UTF-8"))
mockRequest.httpResponse.writer.flush()
}
}
def isFileToReturnExist(fileToReturn){
def fileExist = false
if(fileToReturn != null){
def fileToTest = new File(dataDir + fileToReturn)
if( fileToTest.exists() && fileToTest.canRead()){
fileExist = true
}
}
return fileExist
}
dataDir = new File(context.getMockService().getProject().path).parent
def services = ["Service1", "Service2", "Service3", "Service4",
"Service5", "Service6", "Service7","Service8"]
def status = [200, 400, 200, 200, 400, 200, 200, 200]
def temp =
mockRequest.getHttpRequest().getQueryString().split("fields=")
if ( temp.size() == 2){
temp = temp[1].split("&")
if ( temp.size() > 0){
infos = temp[0]
for(int i=0; i< services.size; i++){
el = services[i]
if ( infos.split(",").size() > 1 && (infos.split(",")
[1]== el || infos.split(",")[0]== el)){
infos = el
httpStatus = status[i]
break;
}
}
}
}
inf = infos.split(",")
log.info inf.size()
def docroot = "/pns/"+infos
def method = mockRequest.getHttpRequest().getMethod();
def queryString = mockRequest.getHttpRequest().getPathInfo()
log.info "method " + method
log.info "queryString " + queryString
if(queryString != null){
def list = queryString.trim().split("/")
def credValue = list[list.size()-1].tokenize('|')[0]
def typecredential = ""
def lstcredtemp = list[list.size()-2].tokenize('|')
if ( lstcredtemp.size() > 0){
typecredential = lstcredtemp[0] + "_"
}
if("GET".equalsIgnoreCase(method)){
fileToReturn = docroot + "/Response_" + typecredential +
credValue + ".json"
}
}
if(!isFileToReturnExist(fileToReturn)){
log.info "le fichier " + fileToReturn + " n'existe pas"
fileToReturn = docroot+"/error.json"
}
RestMockResult mockResult = new RestMockResult( mockRequest )
if (fileToReturn != null) {
writeOut(fileToReturn, mockResult, method)
}
log.info typecredential + " fileToReturn : " + fileToReturn
return mockResult
The log application is supposed to trace for services with status 200 a START line and STOP line with OK.
For services with status code 400 (according to the code) are traced with a START line and a STOP line with KORG, the return code and the description of the error.
But my actual results are that for services with the status code 400, I get just the START line, but not the STOP line with error description and so on.
NTL;NTL;FRO;GetMyServices;START;;;IBTIs;IBTIt;.......;
NTL;FRO;SP;getPns[Service1];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service1];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service5];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service2];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];START;;;IBTIs;IBTIt;
NTL;FRO;ADVISE;getProposal;START;;;IBTIs;IBTIt;
NTL;FRO;SPX;getProposal;STOP;OK;200;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service3];STOP;OK;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service6];START;;;IBTIs;IBTIt;
NTL;FRO;SP;getPns[Service4];STOP;KORG;Mapping
exception;IBTIs;IBTIt;Mapping exception reponse pnsGatape;
NTL;FRO;SP;getPns[Service6];STOP;OK;;IBTIs;IBTIt;
NTL;NTL;FRO;GetMyServices;STOP;OK;;IBTIs;IBTIt;....
Related
I get this error:
Message: exception
Details: 'Cannot get property \'data\' on null object
Here’s my code:
import javax.xml.bind.DatatypeConverter;
import com.carriots.sdk.utils.BasicHttp;
def APIKEY = '1c7021dfcc02e4f52a8db39'
//// Data Fetching ////
def inc_data = context.data.data;
def d1 = inc_data[0..1];
//// Custom Rules declaration ////
def device_id = context.data.id;
def devicename = device_id + '23A2B#User.User';
def rssi = context.data.rssi;
def avgSnr = context.data.avgSnr;
def D1 = Long.parseLong(d1, 16)
//// Filter Status ////
if (D1 >= 1) {
fltstatus = "motion detected";
} else {
fltstatus = "No motion";
}
//// Payload ////
// Build Stream to persist.
// I think the error from the data variable but I do not why...
def data = '{"motion detection": "' + fltstatus + '"}'
def payload_data = '{"at": "now", "protocol": "v2", "device": "' +
devicename + '", "data": "' + data +'"}'
def basicHttp = new BasicHttp();
basicHttp.verb = "POST";
basicHttp.payload = payload_data;
basicHttp.url = "http://api.m.om/status/";
basicHttp.headers = [
"Content-type": "application/json",
"Accept": "application/json",
"User-Agent": "Listener-Carriots",
"carriots.apikey": APIKEY
]
basicHttp.send();
Your first use of data as a property is this line:
def inc_data = context.data.data;
^ ^
(1) (2)
Since you use it twice, it’s impossible to know which use is throwing the exception. I recommend breakpointing this line, then using your debugger to determine that:
context is not null
context.data is not null
I have a bit of Groovy script that loops through the test steps in the current test case and sums the response time for each step and stores it in a custom property on the test case.
I am now trying to do the same for each test step's request and response size but cannot seem to get it to work.
def TestCase = testRunner.getTestCase()
def CurrentTestStep = context.testCase.getTestStepAt(context.getCurrentStepIndex()).getLabel()
def StepList = TestCase.getTestStepList().name - CurrentTestStep
def ResponseTime = 0
def RequestSize = 0
def ResponseSize = 0
StepList.each
{ Step ->
try
{
ResponseTime = ResponseTime + testRunner.testCase.testSteps[Step].testRequest.response.timeTaken
}
catch(Exception expObj)
{
}
}
testRunner.testCase.setPropertyValue("Test_Case_Response_Time", ResponseTime.toString())
You can us below statement for the Response size.
log.info "Size of " + Step + "is " + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
the full code would be
def TestCase = testRunner.getTestCase()
def CurrentTestStep =
context.testCase.getTestStepAt(context.getCurrentStepIndex()).getLabel()
def StepList = TestCase.getTestStepList().name - CurrentTestStep
def ResponseTime = 0
def RequestSize = 0
def ResponseSize = 0
StepList.each
{
Step ->
try
{
log.info "Size of " + Step + "is " + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
ResponseSize= ResponseSize + testRunner.testCase.testSteps[Step].testRequest.response.responseSize
}
catch(Exception e)
{
}
}
testRunner.testCase.setPropertyValue("Test_Case_Response_Size", ResponseSize.toString())
For request size i was not able to find the statement to get size. will Add once get it.
I have a java agent in lotus notes in which i receive an xml and parse this.
this is the code:
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Arrays;
public class JavaAgent extends AgentBase {
private static PrintWriter pw;
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
Database db = agentContext.getCurrentDatabase();
//domino 03
boolean ProductieDatabase = false;
String ApplicatieServer = "CN=Server01";
String OrderDB = "General\\Order.nsf";
String TestOrderDB = "General\\TestOrder.nsf";
String Relations= "General\\Relations.nsf";
String Tabel= "General\\Tabel.nsf";
org.w3c.dom.Document domdoc = null;
lotus.domino.Document doc = agentContext.getDocumentContext();
Item requestContent = null;
StringBuffer sb = new StringBuffer();
pw = getAgentOutput();
//Open databases
Database RelationDB= session.getDatabase(ApplicatieServer,Relations, false);
Database TabelDB= session.getDatabase(ApplicatieServer,Tabel, false);
//Open order database
Database TabelDB;
if(ProductieDatabase == true)
{
TabelDB= session.getDatabase(ApplicatieServer,OrderDB, false);
}
else
{
TabelDB= session.getDatabase(ApplicatieServer,TestOrderDB, false);
}
//Maak nieuw request document aan
lotus.domino.Document RequestDoc = db.createDocument();
//Alle velden uit de http post toevoegen aan document
Vector items = doc.getItems();
for (int j=0; j<items.size(); j++)
{
// System.out.println ("Testorders 3");
Item item = (Item)items.elementAt(j);
String fldName = item.getName();
String fldValue = item.getValueString();
RequestDoc.replaceItemValue(fldName, fldValue);
if ( fldName.matches("(?i).*request_content.*") )
{
sb.append( fldValue );
}
}
RequestDoc.replaceItemValue("Form", "Response");
RequestDoc.replaceItemValue("Status", "0");
RequestDoc.replaceItemValue("ID_Request", RequestDoc.getUniversalID());
Date currentDate=new Date(System.currentTimeMillis());
SimpleDateFormat formatterDatum=new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat formatterTijd=new SimpleDateFormat("HHmmss");
String HubwooBestandspad = "C:\\OCI\\asd\\";
String Bestnaam = cxvxcv+ "asdasd" + RequestDoc.getUniversalID() + "_" + formatterDatum.format(currentDate) + "_" + formatterTijd.format(currentDate) + ".xml";
Stream outStream = session.createStream();
if (outStream.open(Bestnaam, "ASCII")) {
if (outStream.getBytes() == 0) {
outStream.writeText(sb.toString());
outStream.close();
}
else
System.out.println("Output file exists and has content");
}
else{
System.out.println("Output file open failed");
}
File input = new File(Bestnaam);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
domdoc = dBuilder.parse(input);
domdoc.getDocumentElement().normalize();
NodeList nList = domdoc.getElementsByTagName("ItemOut");
String test = "TEST OCI AGENT";
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Element eElement = (Element) nNode;
System.out.println("\nCurrent Element :" + nList.getLength());
test = test + "**Delivery Date**" + eElement.getAttribute("requestedDeliveryDate") + "!END! [" + temp + "]";
test = test + " " + eElement.getElementsByTagName("SupplierPartID").item(0).getTextContent();
test = test + " " + eElement.getElementsByTagName("Description").item(0).getTextContent();
}
RequestDoc.replaceItemValue("JSON", sb.toString());
RequestDoc.replaceItemValue("JSON", test);
// OM HELE XML FILE TE KRIJGEN
RequestDoc.replaceItemValue("XmlTU",sb.toString());
RequestDoc.save();
//verander content-type
pw.println("Content-Type: text/xml");
//verander charset
pw.println("charset: UFT-8");
//stuur 200 OK terug
pw.println("200 OK");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
How can i change sucessfully the content type to text/xml and the charset to utf-8. I was thinking about creating an extra class which extends the HttpServlet and which has the doPost method. But how can i then implement that object in to this agent?
Now this service works, with firefox poster i also receive response 200 OK and also content-type= text/xml.. But if this service is getting called from a .net envorinment then the .net shows a protocol violation error.
Can someone help?
code of the .net application:
Public Function SubmitOrder(ByVal OrderXML, ByVal URL)
Dim objXMLHTTP 'MSXML2.ServerXMLHTTP
'We provide our own error handling
On Error Resume Next
'The MSXML2.ServerXMLHTTP object allows xml to be posted to
'external webpages.
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
If Err.Number <> 0 Then
SubmitOrder = "ERROR: Failed to create ServerXMLHTTP - " & Err.Description
Exit Function
End If
'Specify the webpage we wish to use
objXMLHTTP.Open "POST", URL, False
If Err.Number <> 0 Then
SubmitOrder = "ERROR: Failed to open URL - " & Err.Description
Exit Function
End If
'The type of information we are sending
objXMLHTTP.setRequestHeader "Content-Type", "text/xml"
If Err.Number <> 0 Then
SubmitOrder = "ERROR: Failed to setRequestHeader - " & Err.Description
Exit Function
End If
'Send the information
objXMLHTTP.send replace(OrderXML,"UTF-16","UTF-8")
If Err.Number <> 0 Then
SubmitOrder = "ERROR: Failed to send data to " & URL & " - " & Err.Description & ", Error number --> " & Err.Number
Exit Function
End If
'Return the result
SubmitOrder = objXMLHTTP.responseText
end Function
public Function CheckSuccess(ByVal Response)
'Check for any internal errors
If Left(Response, 6) = "ERROR:" Then
CheckSuccess = False
Exit Function
End If
'If the response includes the text code="200" then the
'export was a success
CheckSuccess = instr(Response, "code=""200""") <> 0
End Function
I have the unenviable task of editing a 2000 line javascript file inorder to maintain and add some new feature to a web app written in JSP, Json-RPC, jQuery and Java. I do not possess any deeper knowledge of jQuery and Json-RPC except basic Javascript knowledge and the original developer is not there anymore.
There is a JS function which accepts a few params, and calls a Json-RPC and here I am getting the error
arg 1 could not unmarshal
Can someone please tell me what this error means?
Here is my code
function distributeQuantityNew(pReportId, pDecimalPlaces, pRun) {
try {
alert('distributeQuantityNew: ' + pReportId + ', ' + pDecimalPlaces + ', ' + pRun);
var fieldValue = $("#distribution_quantity_" + pReportId).val();
if (fieldValue.length == 0) {
showErrorDialog(resourceBundleMap["error.no.distribution.quantity"]);
return;
} else {
$("#distribution_quantity_" + pReportId).val("");
}
var affectedRowIds = [];
var rows = $("#tableBody_" + pReportId + " tr:visible").has("input[type=text]").filter(function(index) {
var voucherType = this.cells[getVoucherColumnIndex()].innerHTML;
if ((voucherType == 'TRANSFER_CS') || (voucherType == 'PAYOUT_CS') || (voucherType == 'SOURCE_BON') || (voucherType == 'PAYOUT_BON')) {
return false;
}
affectedRowIds.push(parseInt(this.id.split("_")[3]));
return true;
}
);
var affectedReportRows = $.extend(true, {}, foreignReportMap[pReportId]);
$.each(affectedReportRows.map, function(i, row) {
if ($.inArray(row.partnerReportBillNr, affectedRowIds) == -1) {
delete affectedReportRows.map["row_" + row.partnerReportBillNr];
}
});
var report = getLoadedReportByRunId(pReportId);
var productType = report.partnerProductType;
SessionManager.extend();
var resultRows = jsonrpc.foreignReportObject.distributeQuantity(affectedReportRows, fieldValue, pDecimalPlaces, pRun);
alert('back after RPC');
$.each(resultRows.map, function(i, row) {
foreignReportMap[pReportId].map["row_" + row.partnerReportBillNr] = row;
updateForeignReportRow(row, true, productType);
});
updateSummaryRow(pReportId);
toggleApproveAllLink(pReportId);
sortForeignReportTable(pReportId, true);
} catch (e) {
handleError("Failed to distribute quantity: ", e);
}
}
I have peppered it with alerts so that I know whether RPC call was succesful, but I get the error arg 1 could not unmarshal before that from the catch block. Thanks for any hints
OK, got it solved. The first parameter to the remote function is expecting a list of Map<String, SomeBO>. SomeBO is a bean with several BigDecimals. I had another JS function which had set the values passed into the Map. This function was setting a BigNumber where I had a setter of String only. I wish the error I had gotten back from JSON unmarshaller was a bit more descriptive...Below is the code where I added .toString() to solve the issue
foreignReportMap[pReportId].map["row_" + pRowId].clientQuantity = clientQuantity.toString();
foreignReportMap[pReportId].map["row_" + pRowId].totalClientQuantity = totalClientQuantity.toString();
I want to get value from control oid from LDAP: For example when I use Linux ldapsearch:
ldapsearch -H ldap://host:port -x -wsecret -D "cn=manager,managedElementId=HSS1"
-b "dn" "objectClass=ConfigOAM" -E"1.3.6.1.4.1.637.81.2.10.10"
I get results:
...
**control: 1.3.6.1.4.1.637.81.2.10.10 false AgEB**
objectClass: top
objectClass: ConfigOAM
confOAMId: 1
...
My java code looks:
LDAPConnection connection = new LDAPConnection();
connection.connect(hostName, port);
connection.bind(LDAPConnection.LDAP_V3, userDN, password);
String returnedAttributes[] = {"+", "*"};
boolean attributeOnly = false;
String oid;
LDAPSearchResults results = connection.search("", LDAPConnection.SCOPE_BASE, "(objectClass=*)", returnedAttributes, attributeOnly);
LDAPEntry entry = results.next();
System.out.println("\n" + entry.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet = entry.getAttributeSet();
Iterator allAttributes = attributeSet.iterator();
while(allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues = attribute.getStringValues();
while(allValues.hasMoreElements()) {
oid = (String) allValues.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
and the result is:
...
supportedControl
2.16.840.1.113730.3.4.2
1.2.840.113556.1.4.319
1.2.826.0.1.3344810.2.3
1.3.6.1.1.12
1.3.6.1.4.1.637.81.2.10.11
**1.3.6.1.4.1.637.81.2.10.10**
1.3.6.1.4.1.637.81.2.10.9
1.3.6.1.4.1.637.81.2.10.6
...
Please suggest me or advice how can I get the additional value "false AgEB" in java as I get it in ldapsearch?
You would need to add the control to the search request and be able to interpret the response.
There are soem examples available:
http://www.novell.com/documentation/developer/samplecode/jldap_sample/
-jim
Thank you for your answer :)
I made something like this from samples available on this site and from others soruces:
lc.connect( ldapHost, ldapPort );
lc.bind( ldapVersion, loginDN, password.getBytes("UTF8"));
LDAPControl ldapCtrl = new LDAPControl("1.3.6.1.4.1.637.81.2.10.10", false, null);
LDAPSearchConstraints cons = lc.getSearchConstraints();
cons.setControls( ldapCtrl );
lc.setConstraints(cons);
LDAPSearchResults searchResults = lc.search("",LDAPConnection.SCOPE_BASE, "(objectclass=*)", returnedAttributes,attributeOnly , cons);
LDAPControl[] controls = searchResults.getResponseControls();
but my "controls" varaible is always null, even if supportedControls are listed
LDAPEntry entry1 = searchResults.next();
System.out.println("\n" + entry1.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet1 = entry1.getAttributeSet();
Iterator allAttributes1 = attributeSet1.iterator();
while(allAttributes1.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes1.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues1 = attribute.getStringValues();
while(allValues1.hasMoreElements()) {
oid = (String) allValues1.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
Maybe the searchResults options are wrong?