use of org.cerberus.crud.entity.AppServiceHeader 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.AppServiceHeader in project cerberus-source by cerberustesting.
the class CreateAppService method getHeaderListFromRequest.
private List<AppServiceHeader> getHeaderListFromRequest(HttpServletRequest request, ApplicationContext appContext, String service, JSONArray json) throws CerberusException, JSONException, UnsupportedEncodingException {
List<AppServiceHeader> headerList = new ArrayList();
for (int i = 0; i < json.length(); i++) {
JSONObject objectJson = json.getJSONObject(i);
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
boolean delete = objectJson.getBoolean("toDelete");
int sort = objectJson.getInt("sort");
String key = objectJson.getString("key");
String value = objectJson.getString("value");
String active = objectJson.getString("active");
String description = objectJson.getString("description");
if (!delete) {
headerList.add(appServiceHeaderFactory.create(service, key, value, active, sort, description, request.getRemoteUser(), null, request.getRemoteUser(), null));
}
}
return headerList;
}
use of org.cerberus.crud.entity.AppServiceHeader 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.AppServiceHeader in project cerberus-source by cerberustesting.
the class FactoryAppServiceHeader method create.
@Override
public AppServiceHeader create(String service, String key, String value, String active, int sort, String description, String usrCreated, Timestamp dateCreated, String usrModif, Timestamp dateModif) {
AppServiceHeader newObject = new AppServiceHeader();
newObject.setService(service);
newObject.setKey(key);
newObject.setValue(value);
newObject.setActive(active);
newObject.setSort(sort);
newObject.setDescription(description);
newObject.setUsrCreated(usrCreated);
newObject.setUsrModif(usrModif);
newObject.setDateCreated(dateCreated);
newObject.setDateModif(dateModif);
return newObject;
}
use of org.cerberus.crud.entity.AppServiceHeader in project cerberus-source by cerberustesting.
the class FactoryAppServiceHeader method create.
@Override
public AppServiceHeader create(String service) {
AppServiceHeader newObject = new AppServiceHeader();
newObject.setService(service);
return newObject;
}
Aggregations