use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.
the class RestService method callREST.
@Override
public AnswerItem<AppService> callREST(String servicePath, String requestString, String method, List<AppServiceHeader> headerList, List<AppServiceContent> contentList, String token, int timeOutMs, String system) {
AnswerItem result = new AnswerItem();
AppService serviceREST = factoryAppService.create("", AppService.TYPE_REST, method, "", "", "", "", "", "", "", "", null, "", null);
serviceREST.setProxy(false);
serviceREST.setProxyHost(null);
serviceREST.setProxyPort(0);
serviceREST.setProxyWithCredential(false);
serviceREST.setProxyUser(null);
serviceREST.setTimeoutms(timeOutMs);
MessageEvent message = null;
if (StringUtil.isNullOrEmpty(servicePath)) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_SERVICEPATHMISSING);
result.setResultMessage(message);
return result;
}
if (StringUtil.isNullOrEmpty(method)) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_METHODMISSING);
result.setResultMessage(message);
return result;
}
// If token is defined, we add 'cerberus-token' on the http header.
if (!StringUtil.isNullOrEmpty(token)) {
headerList.add(factoryAppServiceHeader.create(null, "cerberus-token", token, "Y", 0, "", "", null, "", null));
}
CloseableHttpClient httpclient;
if (proxyService.useProxy(servicePath, system)) {
String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", system, DEFAULT_PROXY_HOST);
int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", system, DEFAULT_PROXY_PORT);
serviceREST.setProxy(true);
serviceREST.setProxyHost(proxyHost);
serviceREST.setProxyPort(proxyPort);
HttpHost proxyHostObject = new HttpHost(proxyHost, proxyPort);
if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system, DEFAULT_PROXYAUTHENT_ACTIVATE)) {
String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", system, DEFAULT_PROXYAUTHENT_USER);
String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", system, DEFAULT_PROXYAUTHENT_PASSWORD);
serviceREST.setProxyWithCredential(true);
serviceREST.setProxyUser(proxyUser);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword));
LOG.debug("Activating Proxy With Authentification.");
httpclient = HttpClientBuilder.create().setProxy(proxyHostObject).setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()).setDefaultCredentialsProvider(credsProvider).build();
} else {
LOG.debug("Activating Proxy (No Authentification).");
httpclient = HttpClientBuilder.create().setProxy(proxyHostObject).build();
}
} else {
httpclient = HttpClients.createDefault();
}
try {
RequestConfig requestConfig;
// Timeout setup.
requestConfig = RequestConfig.custom().setConnectTimeout(timeOutMs).setConnectionRequestTimeout(timeOutMs).setSocketTimeout(timeOutMs).build();
AppService responseHttp = null;
switch(method) {
case AppService.METHOD_HTTPGET:
LOG.info("Start preparing the REST Call (GET). " + servicePath + " - " + requestString);
// Adding query string from requestString
servicePath = StringUtil.addQueryString(servicePath, requestString);
// Adding query string from contentList
String newRequestString = AppServiceService.convertContentListToQueryString(contentList);
servicePath = StringUtil.addQueryString(servicePath, newRequestString);
serviceREST.setServicePath(servicePath);
HttpGet httpGet = new HttpGet(servicePath);
// Timeout setup.
httpGet.setConfig(requestConfig);
// Header.
if (headerList != null) {
for (AppServiceHeader contentHeader : headerList) {
httpGet.addHeader(contentHeader.getKey(), contentHeader.getValue());
}
}
serviceREST.setHeaderList(headerList);
// Saving the service before the call Just in case it goes wrong (ex : timeout).
result.setItem(serviceREST);
LOG.info("Executing request " + httpGet.getRequestLine());
responseHttp = executeHTTPCall(httpclient, httpGet);
if (responseHttp != null) {
serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
}
break;
case AppService.METHOD_HTTPPOST:
LOG.info("Start preparing the REST Call (POST). " + servicePath);
serviceREST.setServicePath(servicePath);
HttpPost httpPost = new HttpPost(servicePath);
// Timeout setup.
httpPost.setConfig(requestConfig);
// Content
if (!(StringUtil.isNullOrEmpty(requestString))) {
// If requestString is defined, we POST it.
InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
InputStreamEntity reqEntity = new InputStreamEntity(stream);
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
serviceREST.setServiceRequest(requestString);
} else {
// If requestString is not defined, we POST the list of key/value request.
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (AppServiceContent contentVal : contentList) {
nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
serviceREST.setContentList(contentList);
}
// Header.
for (AppServiceHeader contentHeader : headerList) {
httpPost.addHeader(contentHeader.getKey(), contentHeader.getValue());
}
serviceREST.setHeaderList(headerList);
// Saving the service before the call Just in case it goes wrong (ex : timeout).
result.setItem(serviceREST);
LOG.info("Executing request " + httpPost.getRequestLine());
responseHttp = executeHTTPCall(httpclient, httpPost);
if (responseHttp != null) {
serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
} else {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
result.setResultMessage(message);
return result;
}
break;
case AppService.METHOD_HTTPDELETE:
LOG.info("Start preparing the REST Call (DELETE). " + servicePath);
servicePath = StringUtil.addQueryString(servicePath, requestString);
serviceREST.setServicePath(servicePath);
HttpDelete httpDelete = new HttpDelete(servicePath);
// Timeout setup.
httpDelete.setConfig(requestConfig);
// Header.
for (AppServiceHeader contentHeader : headerList) {
httpDelete.addHeader(contentHeader.getKey(), contentHeader.getValue());
}
serviceREST.setHeaderList(headerList);
// Saving the service before the call Just in case it goes wrong (ex : timeout).
result.setItem(serviceREST);
LOG.info("Executing request " + httpDelete.getRequestLine());
responseHttp = executeHTTPCall(httpclient, httpDelete);
if (responseHttp != null) {
serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
}
break;
case AppService.METHOD_HTTPPUT:
LOG.info("Start preparing the REST Call (PUT). " + servicePath);
serviceREST.setServicePath(servicePath);
HttpPut httpPut = new HttpPut(servicePath);
// Timeout setup.
httpPut.setConfig(requestConfig);
// Content
if (!(StringUtil.isNullOrEmpty(requestString))) {
// If requestString is defined, we POST it.
InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
InputStreamEntity reqEntity = new InputStreamEntity(stream);
reqEntity.setChunked(true);
httpPut.setEntity(reqEntity);
serviceREST.setServiceRequest(requestString);
} else {
// If requestString is not defined, we PUT the list of key/value request.
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (AppServiceContent contentVal : contentList) {
nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
serviceREST.setContentList(contentList);
}
// Header.
for (AppServiceHeader contentHeader : headerList) {
httpPut.addHeader(contentHeader.getKey(), contentHeader.getValue());
}
serviceREST.setHeaderList(headerList);
// Saving the service before the call Just in case it goes wrong (ex : timeout).
result.setItem(serviceREST);
LOG.info("Executing request " + httpPut.getRequestLine());
responseHttp = executeHTTPCall(httpclient, httpPut);
if (responseHttp != null) {
serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
} else {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
result.setResultMessage(message);
return result;
}
break;
case AppService.METHOD_HTTPPATCH:
LOG.info("Start preparing the REST Call (PUT). " + servicePath);
serviceREST.setServicePath(servicePath);
HttpPatch httpPatch = new HttpPatch(servicePath);
// Timeout setup.
httpPatch.setConfig(requestConfig);
// Content
if (!(StringUtil.isNullOrEmpty(requestString))) {
// If requestString is defined, we POST it.
InputStream stream = new ByteArrayInputStream(requestString.getBytes(StandardCharsets.UTF_8));
InputStreamEntity reqEntity = new InputStreamEntity(stream);
reqEntity.setChunked(true);
httpPatch.setEntity(reqEntity);
serviceREST.setServiceRequest(requestString);
} else {
// If requestString is not defined, we PUT the list of key/value request.
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (AppServiceContent contentVal : contentList) {
nvps.add(new BasicNameValuePair(contentVal.getKey(), contentVal.getValue()));
}
httpPatch.setEntity(new UrlEncodedFormEntity(nvps));
serviceREST.setContentList(contentList);
}
// Header.
for (AppServiceHeader contentHeader : headerList) {
httpPatch.addHeader(contentHeader.getKey(), contentHeader.getValue());
}
serviceREST.setHeaderList(headerList);
// Saving the service before the call Just in case it goes wrong (ex : timeout).
result.setItem(serviceREST);
LOG.info("Executing request " + httpPatch.getRequestLine());
responseHttp = executeHTTPCall(httpclient, httpPatch);
if (responseHttp != null) {
serviceREST.setResponseHTTPBody(responseHttp.getResponseHTTPBody());
serviceREST.setResponseHTTPCode(responseHttp.getResponseHTTPCode());
serviceREST.setResponseHTTPVersion(responseHttp.getResponseHTTPVersion());
serviceREST.setResponseHeaderList(responseHttp.getResponseHeaderList());
} else {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Any issue was found when calling the service. Coud be a reached timeout during the call (." + timeOutMs + ")"));
result.setResultMessage(message);
return result;
}
break;
}
// Get result Content Type.
if (responseHttp != null) {
serviceREST.setResponseHTTPBodyContentType(AppServiceService.guessContentType(serviceREST, AppService.RESPONSEHTTPBODYCONTENTTYPE_JSON));
}
result.setItem(serviceREST);
message = new MessageEvent(MessageEventEnum.ACTION_SUCCESS_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICEMETHOD%", method));
message.setDescription(message.getDescription().replace("%SERVICEPATH%", servicePath));
result.setResultMessage(message);
} catch (SocketTimeoutException ex) {
LOG.info("Exception when performing the REST Call. " + ex.toString());
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE_TIMEOUT);
message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath));
message.setDescription(message.getDescription().replace("%TIMEOUT%", String.valueOf(timeOutMs)));
result.setResultMessage(message);
return result;
} catch (Exception ex) {
LOG.error("Exception when performing the REST Call. " + ex.toString(), ex);
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICE%", servicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Error on CallREST : " + ex.toString()));
result.setResultMessage(message);
return result;
} finally {
try {
httpclient.close();
} catch (IOException ex) {
LOG.error(ex.toString());
}
}
return result;
}
use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.
the class DeleteAppService method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
final void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
response.setContentType("text/html;charset=UTF-8");
String charset = request.getCharacterEncoding();
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String service = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("service"), null, charset);
// Parameter that we cannot secure as we need the html --> We DECODE them
IAppServiceService soapLibraryService = appContext.getBean(IAppServiceService.class);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(service)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "AppService").replace("%OPERATION%", "Delete").replace("%REASON%", "AppService ID (service) is missing!"));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
AnswerItem resp = soapLibraryService.readByKey(service);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the error.
*/
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "AppService").replace("%OPERATION%", "Delete").replace("%REASON%", "SoapLibrary does not exist."));
ans.setResultMessage(msg);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can delete it.
*/
AppService soapl = (AppService) resp.getItem();
ans = soapLibraryService.delete(soapl);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/DeleteAppService", "DELETE", "Delete AppService : " + service, request);
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", ans.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.
the class UpdateAppService method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
final void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
response.setContentType("text/html;charset=UTF-8");
String charset = request.getCharacterEncoding();
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String service = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("service"), null, charset);
String application = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("application"), null, charset);
String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), null, charset);
String method = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("method"), "", charset);
String operation = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("operation"), null, charset);
String attachementurl = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("attachementurl"), null, charset);
String group = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("group"), null, charset);
String description = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("description"), null, charset);
// Parameter that we cannot secure as we need the html --> We DECODE them
String servicePath = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("servicePath"), null, charset);
String serviceRequest = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("serviceRequest"), null, charset);
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(service)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "AppService").replace("%OPERATION%", "Update").replace("%REASON%", "AppService ID (service) is missing."));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
appServiceService = appContext.getBean(IAppServiceService.class);
appServiceHeaderService = appContext.getBean(IAppServiceHeaderService.class);
appServiceContentService = appContext.getBean(IAppServiceContentService.class);
appServiceContentFactory = appContext.getBean(IFactoryAppServiceContent.class);
appServiceHeaderFactory = appContext.getBean(IFactoryAppServiceHeader.class);
AnswerItem resp = appServiceService.readByKey(service);
if (!(resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && resp.getItem() != null)) {
/**
* Object could not be found. We stop here and report the error.
*/
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) resp);
} else {
/**
* The service was able to perform the query and confirm the
* object exist, then we can update it.
*/
AppService appService = (AppService) resp.getItem();
appService.setGroup(group);
appService.setAttachementURL(attachementurl);
appService.setDescription(description);
appService.setServiceRequest(serviceRequest);
appService.setOperation(operation);
appService.setType(type);
appService.setApplication(application);
appService.setMethod(method);
appService.setServicePath(servicePath);
appService.setUsrModif(request.getRemoteUser());
ans = appServiceService.update(appService.getService(), appService);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successful. Adding Log entry.
*/
logEventService = appContext.getBean(ILogEventService.class);
logEventService.createForPrivateCalls("/UpdateAppService", "UPDATE", "Updated AppService : ['" + service + "']", request);
}
// Update content
if (request.getParameter("contentList") != null) {
JSONArray objContentArray = new JSONArray(request.getParameter("contentList"));
List<AppServiceContent> contentList = new ArrayList();
contentList = getContentListFromRequest(request, appContext, service, objContentArray);
// Update the Database with the new list.
ans = appServiceContentService.compareListAndUpdateInsertDeleteElements(service, contentList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
// Update header
if (request.getParameter("headerList") != null) {
JSONArray objHeaderArray = new JSONArray(request.getParameter("headerList"));
List<AppServiceHeader> headerList = new ArrayList();
headerList = getHeaderListFromRequest(request, appContext, service, objHeaderArray);
// Update the Database with the new list.
ans = appServiceHeaderService.compareListAndUpdateInsertDeleteElements(service, headerList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.
the class PropertyService method property_executeSoapFromLib.
private TestCaseExecutionData property_executeSoapFromLib(TestCaseExecutionData testCaseExecutionData, TestCaseExecution tCExecution, TestCaseStepActionExecution testCaseStepActionExecution, TestCaseCountryProperties testCaseCountryProperty, boolean forceCalculation) {
String result = null;
AnswerItem<String> answerDecode = new AnswerItem();
try {
AppService appService = this.appServiceService.findAppServiceByKey(testCaseExecutionData.getValue1());
if (appService != null) {
String decodedEnveloppe = appService.getServiceRequest();
String decodedServicePath = appService.getServicePath();
String decodedMethod = appService.getOperation();
String decodedAttachement = appService.getAttachementURL();
if (appService.getServiceRequest().contains("%")) {
answerDecode = variableService.decodeStringCompletly(appService.getServiceRequest(), tCExecution, testCaseStepActionExecution, false);
decodedEnveloppe = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
testCaseExecutionData.setPropertyResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "SOAP Service Request"));
testCaseExecutionData.setStopExecution(answerDecode.getResultMessage().isStopTest());
LOG.debug("Property interupted due to decode 'SOAP Service Request' Error.");
return testCaseExecutionData;
}
}
if (appService.getServicePath().contains("%")) {
answerDecode = variableService.decodeStringCompletly(appService.getServicePath(), tCExecution, testCaseStepActionExecution, false);
decodedServicePath = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
testCaseExecutionData.setPropertyResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "SOAP Service Path"));
testCaseExecutionData.setStopExecution(answerDecode.getResultMessage().isStopTest());
LOG.debug("Property interupted due to decode 'SOAP Service Path.");
return testCaseExecutionData;
}
}
if (appService.getOperation().contains("%")) {
answerDecode = variableService.decodeStringCompletly(appService.getOperation(), tCExecution, testCaseStepActionExecution, false);
decodedMethod = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
testCaseExecutionData.setPropertyResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "SOAP Operation"));
testCaseExecutionData.setStopExecution(answerDecode.getResultMessage().isStopTest());
LOG.debug("Property interupted due to decode 'SOAP Operation.");
return testCaseExecutionData;
}
}
if (appService.getAttachementURL().contains("%")) {
answerDecode = variableService.decodeStringCompletly(appService.getAttachementURL(), tCExecution, testCaseStepActionExecution, false);
decodedAttachement = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
testCaseExecutionData.setPropertyResultMessage(answerDecode.getResultMessage().resolveDescription("FIELD", "SOAP Attachement URL"));
testCaseExecutionData.setStopExecution(answerDecode.getResultMessage().isStopTest());
LOG.debug("Property interupted due to decode 'SOAP Attachement URL.");
return testCaseExecutionData;
}
}
// Call Soap and set LastSoapCall of the testCaseExecution.
AnswerItem soapCall = soapService.callSOAP(decodedEnveloppe, decodedServicePath, decodedMethod, decodedAttachement, null, null, 60000, tCExecution.getApplicationObj().getSystem());
AppService se1 = (AppService) soapCall.getItem();
if (soapCall.isCodeEquals(200)) {
// SOAPExecution lastSoapCalled = (SOAPExecution) tCExecution.getLastSOAPCalled().getItem();
String xmlResponse = se1.getResponseHTTPBody();
result = xmlUnitService.getFromXml(xmlResponse, appService.getAttachementURL());
}
if (result != null) {
testCaseExecutionData.setValue(result);
MessageEvent res = new MessageEvent(MessageEventEnum.PROPERTY_SUCCESS_SOAP);
testCaseExecutionData.setPropertyResultMessage(res);
} else {
MessageEvent res = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_SOAPFROMLIB_NODATA);
testCaseExecutionData.setPropertyResultMessage(res);
}
}
} catch (CerberusException exception) {
LOG.error(exception.toString());
MessageEvent res = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_TESTDATA_PROPERTYDONOTEXIST);
res.setDescription(res.getDescription().replace("%PROPERTY%", testCaseExecutionData.getValue1()));
testCaseExecutionData.setPropertyResultMessage(res);
} catch (CerberusEventException ex) {
LOG.error(ex.toString());
MessageEvent message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP);
message.setDescription(message.getDescription().replace("%SOAPNAME%", testCaseExecutionData.getValue1()));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", ex.getMessageError().getDescription()));
testCaseExecutionData.setPropertyResultMessage(message);
}
return testCaseExecutionData;
}
use of org.cerberus.crud.entity.AppService in project cerberus-source by cerberustesting.
the class ServiceService method callService.
@Override
public AnswerItem<AppService> callService(String service, String database, String request, String servicePathParam, String operation, TestCaseExecution tCExecution) {
MessageEvent message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
String decodedRequest;
String decodedServicePath = null;
String decodedOperation;
String decodedAttachement;
AnswerItem result = new AnswerItem();
String system = tCExecution.getApplicationObj().getSystem();
String country = tCExecution.getCountry();
String environment = tCExecution.getEnvironment();
LOG.debug("Starting callService : " + service + " with database : " + database);
try {
AppService appService;
// If Service information is not defined, we create it from request, servicePath and operation parameters forcing in SOAP mode.
if (StringUtil.isNullOrEmpty(service)) {
LOG.debug("Creating AppService from parameters.");
appService = factoryAppService.create("null", AppService.TYPE_SOAP, "", "", "", request, "Automatically created Service from datalib.", servicePathParam, "", operation, null, null, null, null);
service = "null";
} else {
// If Service information is defined, we get it from database.
LOG.debug("Getting AppService from service : " + service);
appService = appServiceService.convert(appServiceService.readByKeyWithDependency(service, "Y"));
}
String servicePath;
if (appService == null) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Service does not exist !!"));
} else if (StringUtil.isNullOrEmpty(appService.getServicePath())) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE).resolveDescription("DESCRIPTION", "Service path is not defined");
} else {
// We start by calculating the servicePath and decode it.
servicePath = appService.getServicePath();
if (!(StringUtil.isURL(servicePath))) {
if (StringUtil.isNullOrEmpty(database)) {
// We reformat servicePath in order to add the context from the application execution.
servicePath = StringUtil.getURLFromString(tCExecution.getCountryEnvironmentParameters().getIp(), tCExecution.getCountryEnvironmentParameters().getUrl(), appService.getServicePath(), "http://");
} else {
// We reformat servicePath in order to add the context from the databaseUrl definition and corresponding from the country and environment of the execution.
try {
CountryEnvironmentDatabase countryEnvironmentDatabase;
countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(this.countryEnvironmentDatabaseService.readByKey(system, country, environment, database));
if (countryEnvironmentDatabase == null) {
message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLNOTEXIST);
message.setDescription(message.getDescription().replace("%SERVICEURL%", appService.getServicePath()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
result.setResultMessage(message);
return result;
} else {
String soapURL = countryEnvironmentDatabase.getSoapUrl();
if (StringUtil.isNullOrEmpty(soapURL)) {
message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLEMPTY);
message.setDescription(message.getDescription().replace("%SERVICEURL%", appService.getServicePath()).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
result.setResultMessage(message);
return result;
}
// soapURL from database is not empty so we prefix the Service URL with it.
servicePath = StringUtil.getURLFromString(soapURL, "", servicePath, "");
if (!StringUtil.isURL(servicePath)) {
message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKO);
message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath).replace("%SOAPURL%", soapURL).replace("%SERVICEPATH%", appService.getServicePath()));
result.setResultMessage(message);
return result;
}
}
} catch (CerberusException ex) {
message = new MessageEvent(MessageEventEnum.PROPERTY_FAILED_GETFROMDATALIB_SERVICE_URLKOANDDATABASESOAPURLNOTEXIST);
message.setDescription(message.getDescription().replace("%SERVICEURL%", servicePath).replace("%SYSTEM%", system).replace("%COUNTRY%", country).replace("%ENV%", environment).replace("%DATABASE%", database));
result.setResultMessage(message);
return result;
}
}
}
// appService object and target servicePath is now clean. We can start to decode.
decodedServicePath = servicePath;
decodedRequest = appService.getServiceRequest();
LOG.debug("AppService with correct path is now OK : " + servicePath);
AnswerItem<String> answerDecode = new AnswerItem();
try {
// Decode Service Path
answerDecode = variableService.decodeStringCompletly(decodedServicePath, tCExecution, null, false);
decodedServicePath = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
message = answerDecode.getResultMessage().resolveDescription("FIELD", "Service Path");
LOG.debug("Property interupted due to decode 'Service Path'.");
result.setResultMessage(message);
return result;
}
// Decode Request
answerDecode = variableService.decodeStringCompletly(decodedRequest, tCExecution, null, false);
decodedRequest = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
message = answerDecode.getResultMessage().resolveDescription("FIELD", "Service Request");
LOG.debug("Property interupted due to decode 'Service Request'.");
result.setResultMessage(message);
return result;
}
// Decode Header List
List<AppServiceHeader> objectResponseHeaderList = new ArrayList<>();
for (AppServiceHeader object : appService.getHeaderList()) {
answerDecode = variableService.decodeStringCompletly(object.getKey(), tCExecution, null, false);
object.setKey((String) answerDecode.getItem());
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Header Key " + object.getKey();
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
answerDecode = variableService.decodeStringCompletly(object.getValue(), tCExecution, null, false);
object.setValue((String) answerDecode.getItem());
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Header Value " + object.getKey();
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
objectResponseHeaderList.add(object);
}
// Decode ContentDetail List
appService.setResponseHeaderList(objectResponseHeaderList);
List<AppServiceContent> objectResponseContentList = new ArrayList<>();
for (AppServiceContent object : appService.getContentList()) {
answerDecode = variableService.decodeStringCompletly(object.getKey(), tCExecution, null, false);
object.setKey((String) answerDecode.getItem());
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Content Key " + object.getKey();
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
answerDecode = variableService.decodeStringCompletly(object.getValue(), tCExecution, null, false);
object.setValue((String) answerDecode.getItem());
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Content Value " + object.getKey();
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
objectResponseContentList.add(object);
}
appService.setContentList(objectResponseContentList);
} catch (CerberusEventException cee) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICEWITHPATH);
message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
message.setDescription(message.getDescription().replace("%SERVICEPATH%", decodedServicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", cee.getMessageError().getDescription()));
result.setResultMessage(message);
return result;
}
// Get from parameter whether we define a token or not (in order to trace the cerberus calls in http header)
String token = null;
if (parameterService.getParameterBooleanByKey("cerberus_callservice_enablehttpheadertoken", system, true)) {
token = String.valueOf(tCExecution.getId());
}
// Get from parameter the call timeout to be used.
int timeOutMs = parameterService.getParameterIntegerByKey("cerberus_callservice_timeoutms", system, 60000);
// The rest of the data will be prepared depending on the TYPE and METHOD used.
switch(appService.getType()) {
case AppService.TYPE_SOAP:
LOG.debug("This is a SOAP Service");
/**
* SOAP. Decode Envelope and Operation replacing
* properties encapsulated with %
*/
decodedOperation = appService.getOperation();
decodedAttachement = appService.getAttachementURL();
try {
answerDecode = variableService.decodeStringCompletly(decodedOperation, tCExecution, null, false);
decodedOperation = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Operation";
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
answerDecode = variableService.decodeStringCompletly(decodedAttachement, tCExecution, null, false);
decodedAttachement = (String) answerDecode.getItem();
if (!(answerDecode.isCodeStringEquals("OK"))) {
// If anything wrong with the decode --> we stop here with decode message in the action result.
String field = "Attachement URL";
message = answerDecode.getResultMessage().resolveDescription("FIELD", field);
LOG.debug("Property interupted due to decode '" + field + "'.");
result.setResultMessage(message);
return result;
}
} catch (CerberusEventException cee) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSOAP);
message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
message.setDescription(message.getDescription().replace("%SERVICEPATH%", decodedServicePath));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", cee.getMessageError().getDescription()));
result.setResultMessage(message);
return result;
}
/**
* Call SOAP and store it into the execution.
*/
result = soapService.callSOAP(decodedRequest, decodedServicePath, decodedOperation, decodedAttachement, appService.getHeaderList(), token, timeOutMs, system);
LOG.debug("SOAP Called done.");
LOG.debug("Result message." + result.getResultMessage());
message = result.getResultMessage();
break;
case AppService.TYPE_REST:
/**
* REST.
*/
switch(appService.getMethod()) {
case AppService.METHOD_HTTPGET:
case AppService.METHOD_HTTPPOST:
/**
* Call REST and store it into the execution.
*/
result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
message = result.getResultMessage();
break;
case AppService.METHOD_HTTPDELETE:
result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
message = result.getResultMessage();
break;
case AppService.METHOD_HTTPPUT:
result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
message = result.getResultMessage();
break;
case AppService.METHOD_HTTPPATCH:
result = restService.callREST(decodedServicePath, decodedRequest, appService.getMethod(), appService.getHeaderList(), appService.getContentList(), token, timeOutMs, system);
message = result.getResultMessage();
break;
default:
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Method : '" + appService.getMethod() + "' for REST Service is not supported by the engine."));
result.setResultMessage(message);
}
break;
default:
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICE%", service));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Service Type : '" + appService.getType() + "' is not supported by the engine."));
result.setResultMessage(message);
}
}
} catch (CerberusException ex) {
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Cerberus exception on CallService : " + ex.getMessageError().getDescription()));
result.setResultMessage(message);
return result;
} catch (Exception ex) {
LOG.error("Exception when performing CallService Action. " + ex.toString());
message = new MessageEvent(MessageEventEnum.ACTION_FAILED_CALLSERVICE);
message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
message.setDescription(message.getDescription().replace("%DESCRIPTION%", "Cerberus exception on CallService : " + ex.toString()));
return result;
}
message.setDescription(message.getDescription().replace("%SERVICENAME%", service));
result.setResultMessage(message);
LOG.debug("Ended callService : " + service + " with database : " + database + " Result : " + message.getDescription());
return result;
}
Aggregations