use of org.cerberus.crud.entity.SqlLibrary in project cerberus-source by cerberustesting.
the class SqlLibraryDAO method findSqlLibraryListByCriteria.
@Override
public List<SqlLibrary> findSqlLibraryListByCriteria(int start, int amount, String column, String dir, String searchTerm, String individualSearch) {
List<SqlLibrary> sqlLibraryList = new ArrayList<SqlLibrary>();
StringBuilder gSearch = new StringBuilder();
StringBuilder searchSQL = new StringBuilder();
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM sqllibrary ");
gSearch.append(" where (`type` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `name` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `database` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `script` like '%");
gSearch.append(searchTerm);
gSearch.append("%'");
gSearch.append(" or `description` like '%");
gSearch.append(searchTerm);
gSearch.append("%')");
if (!searchTerm.equals("") && !individualSearch.equals("")) {
searchSQL.append(gSearch.toString());
searchSQL.append(" and ");
searchSQL.append(individualSearch);
} else if (!individualSearch.equals("")) {
searchSQL.append(" where `");
searchSQL.append(individualSearch);
searchSQL.append("`");
} else if (!searchTerm.equals("")) {
searchSQL.append(gSearch.toString());
}
query.append(searchSQL);
query.append("order by `");
query.append(column);
query.append("` ");
query.append(dir);
query.append(" limit ");
query.append(start);
query.append(" , ");
query.append(amount);
SqlLibrary sqlLibrary;
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
ResultSet resultSet = preStat.executeQuery();
try {
while (resultSet.next()) {
sqlLibraryList.add(this.loadSqlLibraryFromResultSet(resultSet));
}
} catch (SQLException exception) {
LOG.warn("Unable to execute query : " + exception.toString());
} finally {
resultSet.close();
}
} catch (SQLException exception) {
LOG.warn("Unable to execute query : " + exception.toString());
} finally {
preStat.close();
}
} catch (SQLException exception) {
LOG.warn("Unable to execute query : " + exception.toString());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
LOG.warn(e.toString());
}
}
return sqlLibraryList;
}
use of org.cerberus.crud.entity.SqlLibrary in project cerberus-source by cerberustesting.
the class SqlLibraryDAO method readByCriteria.
@Override
public AnswerList readByCriteria(int start, int amount, String column, String dir, String searchTerm, Map<String, List<String>> individualSearch) {
AnswerList response = new AnswerList();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
List<SqlLibrary> objectList = new ArrayList<SqlLibrary>();
StringBuilder searchSQL = new StringBuilder();
List<String> individalColumnSearchValues = new ArrayList<String>();
StringBuilder query = new StringBuilder();
// SQL_CALC_FOUND_ROWS allows to retrieve the total number of columns by disrearding the limit clauses that
// were applied -- used for pagination p
query.append("SELECT SQL_CALC_FOUND_ROWS * FROM sqllibrary `sql` ");
query.append(" WHERE 1=1");
if (!StringUtil.isNullOrEmpty(searchTerm)) {
searchSQL.append(" and (`sql`.Name like ?");
searchSQL.append(" or `sql`.Type like ?");
searchSQL.append(" or `sql`.Database like ?");
searchSQL.append(" or `sql`.description like ?");
searchSQL.append(" or `sql`.script like ?)");
}
if (individualSearch != null && !individualSearch.isEmpty()) {
searchSQL.append(" and ( 1=1 ");
for (Map.Entry<String, List<String>> entry : individualSearch.entrySet()) {
searchSQL.append(" and ");
String q = SqlUtil.getInSQLClauseForPreparedStatement(entry.getKey(), entry.getValue());
if (q == null || q == "") {
q = "(`sql`." + entry.getKey() + " IS NULL OR " + entry.getKey() + " = '')";
}
searchSQL.append(q);
individalColumnSearchValues.addAll(entry.getValue());
}
searchSQL.append(" )");
}
query.append(searchSQL);
if (!StringUtil.isNullOrEmpty(column)) {
query.append(" order by `sql`.").append(column).append(" ").append(dir);
}
if ((amount <= 0) || (amount >= MAX_ROW_SELECTED)) {
query.append(" limit ").append(start).append(" , ").append(MAX_ROW_SELECTED);
} else {
query.append(" limit ").append(start).append(" , ").append(amount);
}
// Debug message on SQL.
if (LOG.isDebugEnabled()) {
LOG.debug("SQL : " + query.toString());
}
Connection connection = this.databaseSpring.connect();
try {
PreparedStatement preStat = connection.prepareStatement(query.toString());
try {
int i = 1;
if (!StringUtil.isNullOrEmpty(searchTerm)) {
preStat.setString(i++, "%" + searchTerm + "%");
preStat.setString(i++, "%" + searchTerm + "%");
preStat.setString(i++, "%" + searchTerm + "%");
preStat.setString(i++, "%" + searchTerm + "%");
preStat.setString(i++, "%" + searchTerm + "%");
}
for (String individualColumnSearchValue : individalColumnSearchValues) {
preStat.setString(i++, individualColumnSearchValue);
}
ResultSet resultSet = preStat.executeQuery();
try {
// gets the data
while (resultSet.next()) {
objectList.add(this.loadFromResultSet(resultSet));
}
// get the total number of rows
resultSet = preStat.executeQuery("SELECT FOUND_ROWS()");
int nrTotalRows = 0;
if (resultSet != null && resultSet.next()) {
nrTotalRows = resultSet.getInt(1);
}
if (objectList.size() >= MAX_ROW_SELECTED) {
// Result of SQl was limited by MAX_ROW_SELECTED constrain. That means that we may miss some lines in the resultList.
LOG.error("Partial Result in the query.");
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_WARNING_PARTIAL_RESULT);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", "Maximum row reached : " + MAX_ROW_SELECTED));
response = new AnswerList(objectList, nrTotalRows);
} else if (objectList.size() <= 0) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_NO_DATA_FOUND);
response = new AnswerList(objectList, nrTotalRows);
} else {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_OK);
msg.setDescription(msg.getDescription().replace("%ITEM%", OBJECT_NAME).replace("%OPERATION%", "SELECT"));
response = new AnswerList(objectList, nrTotalRows);
}
} catch (SQLException exception) {
LOG.error("Unable to execute query : " + exception.toString());
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
} finally {
if (resultSet != null) {
resultSet.close();
}
}
} catch (SQLException exception) {
LOG.error("Unable to execute query : " + exception.toString());
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
} finally {
if (preStat != null) {
preStat.close();
}
}
} catch (SQLException exception) {
LOG.error("Unable to execute query : " + exception.toString());
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", exception.toString()));
} finally {
try {
if (!this.databaseSpring.isOnTransaction()) {
if (connection != null) {
connection.close();
}
}
} catch (SQLException exception) {
LOG.warn("Unable to close connection : " + exception.toString());
}
}
response.setResultMessage(msg);
response.setDataList(objectList);
return response;
}
use of org.cerberus.crud.entity.SqlLibrary in project cerberus-source by cerberustesting.
the class ReadSqlLibrary method findSqlLibraryList.
private AnswerItem findSqlLibraryList(ApplicationContext appContext, boolean userHasPermissions, HttpServletRequest request) throws JSONException {
AnswerItem item = new AnswerItem();
JSONObject object = new JSONObject();
sqlLibraryService = appContext.getBean(SqlLibraryService.class);
int startPosition = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayStart"), "0"));
int length = Integer.valueOf(ParameterParserUtil.parseStringParam(request.getParameter("iDisplayLength"), "0"));
/*int sEcho = Integer.valueOf(request.getParameter("sEcho"));*/
String searchParameter = ParameterParserUtil.parseStringParam(request.getParameter("sSearch"), "");
int columnToSortParameter = Integer.parseInt(ParameterParserUtil.parseStringParam(request.getParameter("iSortCol_0"), "2"));
String sColumns = ParameterParserUtil.parseStringParam(request.getParameter("sColumns"), "para,valC,valS,descr");
String[] columnToSort = sColumns.split(",");
String columnName = columnToSort[columnToSortParameter];
String sort = ParameterParserUtil.parseStringParam(request.getParameter("sSortDir_0"), "asc");
List<String> individualLike = new ArrayList(Arrays.asList(ParameterParserUtil.parseStringParam(request.getParameter("sLike"), "").split(",")));
Map<String, List<String>> individualSearch = new HashMap<>();
for (int a = 0; a < columnToSort.length; a++) {
if (null != request.getParameter("sSearch_" + a) && !request.getParameter("sSearch_" + a).isEmpty()) {
List<String> search = new ArrayList(Arrays.asList(request.getParameter("sSearch_" + a).split(",")));
if (individualLike.contains(columnToSort[a])) {
individualSearch.put(columnToSort[a] + ":like", search);
} else {
individualSearch.put(columnToSort[a], search);
}
}
}
AnswerList resp = sqlLibraryService.readByCriteria(startPosition, length, columnName, sort, searchParameter, individualSearch);
JSONArray jsonArray = new JSONArray();
if (resp.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
// the service was able to perform the query, then we should get all values
for (SqlLibrary param : (List<SqlLibrary>) resp.getDataList()) {
jsonArray.put(convertSqlLibraryToJSONObject(param));
}
}
object.put("hasPermissions", userHasPermissions);
object.put("contentTable", jsonArray);
object.put("iTotalRecords", resp.getTotalRows());
object.put("iTotalDisplayRecords", resp.getTotalRows());
item.setItem(object);
item.setResultMessage(resp.getResultMessage());
return item;
}
use of org.cerberus.crud.entity.SqlLibrary in project cerberus-source by cerberustesting.
the class UpdateSqlLibrary 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
*/
protected void processRequest(HttpServletRequest request, 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");
PrintWriter out = response.getWriter();
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 name = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("name"), null, charset);
String type = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("type"), null, charset);
String database = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getParameter("database"), 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 script = ParameterParserUtil.parseStringParamAndDecode(request.getParameter("script"), 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(name)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "SqlLibrary").replace("%OPERATION%", "Update").replace("%REASON%", "SqlLibrary ID (name) is missing."));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ISqlLibraryService sqlLibraryService = appContext.getBean(ISqlLibraryService.class);
AnswerItem resp = sqlLibraryService.readByKey(name);
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.
*/
SqlLibrary sqlLib = (SqlLibrary) resp.getItem();
sqlLib.setType(type);
sqlLib.setDescription(description);
sqlLib.setDatabase(database);
sqlLib.setScript(script);
ans = sqlLibraryService.update(sqlLib);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Update was successful. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/UpdateSqlLibrary", "UPDATE", "Updated SqlLibrary : ['" + name + "']", request);
}
}
}
/**
* 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.SqlLibrary in project cerberus-source by cerberustesting.
the class CalculatePropertyForTestCase method doGet.
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.BLOCKS);
String type = policy.sanitize(httpServletRequest.getParameter("type"));
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
String result = null;
String description = null;
String system = "";
String property = httpServletRequest.getParameter("property");
String testName = policy.sanitize(httpServletRequest.getParameter("test"));
String testCaseName = policy.sanitize(httpServletRequest.getParameter("testCase"));
String country = policy.sanitize(httpServletRequest.getParameter("country"));
String environment = policy.sanitize(httpServletRequest.getParameter("environment"));
try {
if (type.equals("executeSoapFromLib")) {
IAppServiceService appServiceService = appContext.getBean(AppServiceService.class);
ISoapService soapService = appContext.getBean(ISoapService.class);
IXmlUnitService xmlUnitService = appContext.getBean(IXmlUnitService.class);
AppService appService = appServiceService.findAppServiceByKey(property);
if (appService != null) {
ExecutionUUID executionUUIDObject = appContext.getBean(ExecutionUUID.class);
UUID executionUUID = UUID.randomUUID();
executionUUIDObject.setExecutionUUID(executionUUID.toString(), null);
soapService.callSOAP(appService.getServiceRequest(), appService.getServicePath(), appService.getOperation(), appService.getAttachementURL(), null, null, 60000, system);
result = xmlUnitService.getFromXml(executionUUID.toString(), appService.getAttachementURL());
description = appService.getDescription();
executionUUIDObject.removeExecutionUUID(executionUUID.toString());
LOG.debug("Clean ExecutionUUID");
}
} else {
try {
ITestCaseService testCaseService = appContext.getBean(TestCaseService.class);
IApplicationService applicationService = appContext.getBean(ApplicationService.class);
TestCase testCase = testCaseService.findTestCaseByKey(testName, testCaseName);
if (testCase != null) {
system = applicationService.convert(applicationService.readByKey(testCase.getApplication())).getSystem();
} else {
throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NO_DATA_FOUND));
}
} catch (CerberusException ex) {
LOG.warn(ex);
}
if (system != null) {
String database = policy.sanitize(httpServletRequest.getParameter("database"));
ICountryEnvironmentDatabaseService countryEnvironmentDatabaseService = appContext.getBean(CountryEnvironmentDatabaseService.class);
CountryEnvironmentDatabase countryEnvironmentDatabase;
countryEnvironmentDatabase = countryEnvironmentDatabaseService.convert(countryEnvironmentDatabaseService.readByKey(system, country, environment, database));
String connectionName = countryEnvironmentDatabase.getConnectionPoolName();
if (type.equals("executeSqlFromLib")) {
ISqlLibraryService sqlLibraryService = appContext.getBean(SqlLibraryService.class);
SqlLibrary sl = sqlLibraryService.findSqlLibraryByKey(policy.sanitize(property));
property = sl.getScript();
if (!(StringUtil.isNullOrEmpty(connectionName)) && !(StringUtil.isNullOrEmpty(policy.sanitize(property)))) {
ISQLService sqlService = appContext.getBean(ISQLService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
Integer sqlTimeout = parameterService.getParameterIntegerByKey("cerberus_propertyexternalsql_timeout", system, 60);
result = sqlService.queryDatabase(connectionName, policy.sanitize(property), 1, sqlTimeout).get(0);
description = sl.getDescription();
}
}
}
}
} catch (CerberusException ex) {
LOG.warn(ex);
result = ex.getMessageError().getDescription();
description = ex.getMessageError().getDescription();
} catch (CerberusEventException ex) {
LOG.warn(ex);
result = ex.getMessageError().getDescription();
description = ex.getMessageError().getDescription();
}
if (result != null) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("resultList", result);
jsonObject.put("description", description);
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().print(jsonObject.toString());
} catch (JSONException exception) {
LOG.warn(exception.toString());
}
}
}
Aggregations