I work in a java library working with database. I want to store the config datas for use them to connection and sql queries.
How can store config data?
It's ok to put them into abstract final class?
public final class MySQLConfig {
final public static String
DRIVER = "com.mysql.jdbc.Driver",
DBURL = "jdbc:mysql://localhost/dbname",
USER = "user",
PASS = "pass",
PREFIX = "vab_",
CARDS_TABLE = "cards",
CARDS_CARD_ID = "card_id",
CARDS_OWNER_ID = "owner_id",
CARDS_LABEL = "label",
CARDS_AMOUNT = "amount",
TRANSACTIONS_TABLE = "transactions",
TRANSACTIONS_TRANSACTION_ID = "transaction_id",
TRANSACTIONS_CARD_ID = "card_id",
TRANSACTIONS_USER_ID = "owner_id",
TRANSACTIONS_DESCRIPTION = "label",
TRANSACTIONS_AMOUNT = "amount",
TRANSACTIONS_DATE = "datetime",
TRANSACTIONS_TYPE = "type",
// Prevent create instance
private MySQLConfig() {
}
}
I use them like this:
public static Connection createConnection() {
try {
Class.forName(MySQLConfig.DRIVER);
return DriverManager.getConnection(MySQLConfig.DBURL, MySQLConfig.USER, MySQLConfig.PASS);
} catch (ClassNotFoundException | SQLException ex) {
}
return null;
}
Or in sql statement:
String sql = "INSERT INTO " + MySQLConfig.PREFIX + MySQLConfig.CARDS_TABLE + " ("
+ MySQLConfig.CARDS_OWNER_ID + ", "
+ MySQLConfig.CARDS_LABEL + ", "
+ MySQLConfig.CARDS_AMOUNT + " "
+ ") "
+ "VALUES ("
+ "'" + String.valueOf(ownerId) + "', "
+ "'" + label + "', "
+ "'" + initAmount.toPlainString() + "'"
+ ")";
How I can store correctly this data?
Related
I will tell you about my problem. I have a database in mysql and I do the queries from Java using javafx and JDBC. I am trying to do a data filter, since I want to be able to filter data not only by name, but also by other data. As you can see, my code has many SQL statements, I tried to put them together in an array, but only the first statement works, if I do others, exceptions are thrown, it only works if I do only 1 individual query. My problem is that and I would like to find a solution. I have a lot of silenced code, since my idea is to have a statement that encompasses everything.
public static Comics[] filtadroBBDD(String nombreC, String numeroC, String varianteC, String firmaC,
String nomEditorialC, String formatoC, String procedenciaC, String fechaC, String guionistaC,
String nomDibujanteC) {
reiniciarBBDD();
String nombreCom, numeroCom, varianteCom, firmaCom, editorialCom, formatoCom, procedenciaCom, fechaCom,
guionistaCom, dibujanteCom;
Comics comics[] = null;
String sql1 = "SELECT * FROM comicsbbdd where nomComic = '" + nombreC + "';";
String sql2 = "SELECT * FROM comicsbbdd where numComic = '" + numeroC + "';";
String sql3 = "SELECT * FROM comicsbbdd where nomVariante = '" + varianteC + "';";
String sql4 = "SELECT * FROM comicsbbdd where firma = '" + firmaC + "';";
String sql5 = "SELECT * FROM comicsbbdd where nomEditorial = '" + nomEditorialC + "';";
String sql6 = "SELECT * FROM comicsbbdd where formato = '" + formatoC + "';";
String sql7 = "SELECT * FROM comicsbbdd where procedencia = '" + procedenciaC + "';";
String sql8 = "SELECT * FROM comicsbbdd where anioPubli = '" + fechaC + "';";
String sql9 = "SELECT * FROM comicsbbdd where nomGuionistas = '" + guionistaC + "';";
String sql10 = "SELECT * FROM comicsbbdd where nomDibujantes = '" + nomDibujanteC + "';";
// String []sentenciasSQL = {sql1,sql2,sql3,sql4,sql5,sql6,sql7,sql8,sql9,sql10};
String[] sentenciasSQL = { sql1 };
// String sql = "SELECT * FROM comicsbbdd WHERE nomComic = '" + nombreC + "' AND numComic = '" + numeroC
// + "' AND nomVariante = '" + varianteC + "' AND firma = '" + firmaC + "' AND nomEditorial = '"
// + nomEditorialC + "' and formato = '" + formatoC + "' AND procedencia = '" + procedenciaC
// + "' AND anioPubli = '" + fechaC + "' AND nomGuionista = '" + guionistaC + "' AND nomDibujante = '"
// + nomDibujanteC + "';";
try {
for (int i = 0; i < sentenciasSQL.length; i++) {
ResultSet rs = DBManager.getComic(sentenciasSQL[i]);
do {
nombreCom = rs.getString("nomComic");
numeroCom = rs.getString("numComic");
varianteCom = rs.getString("nomVariante");
firmaCom = rs.getString("firma");
editorialCom = rs.getString("nomEditorial");
formatoCom = rs.getString("formato");
procedenciaCom = rs.getString("procedencia");
fechaCom = rs.getString("anioPubli");
guionistaCom = rs.getString("nomGuionista");
dibujanteCom = rs.getString("nomDibujante");
FiltrolistComics.add(new Comics(nombreCom, numeroCom, varianteCom, firmaCom, editorialCom,
formatoCom, procedenciaCom, fechaCom, guionistaCom, dibujanteCom));
} while (rs.next());
}
} catch (SQLException ex) {
System.err.println(ex);
}
comics = new Comics[FiltrolistComics.size()];
comics = FiltrolistComics.toArray(comics);
return comics;
}
public static void reiniciarBBDD() {
FiltrolistComics.clear();
listComics.clear();
}
How can I set the x-axis and y-axis in charts?
Here labels are displayed. But I want to display the x-axis and y-axis names(label) in the chart graph.
public class ChartUtils {
public static HashMap<String, String> getChartData(String projectName, String questionnaireName, String questionId,
String questionValue) throws Exception {
HashMap<String, String> cMap = new HashMap<String, String>();
String dailyResponseCounts = "";
String responseStringValues = "";
String responseStringValuesForTable = "";
int cumulativeCount = 0;
String questionniareSql = "Select questionnairedetails from questionnairedetails where projectname='"
+ projectName + "' and questionnairename='" + questionnaireName + "'";
String sql = " SELECT response, count(*) as count FROM surveyresponsedetails where isduplicate is null and surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "' " + " )and question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "') " + " and response is not null and response <> '' group by response order by count asc";
// String legendString="";
String tableHTML = "";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
boolean isMultiChoice = false;
try {
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(questionniareSql);
// Condition :1 && 2
if (!questionnaireJsonDB.equals("") && questionnaireJsonDB.contains(questionValue)) {
JsonObject questionnaireJson = (JsonObject) new JsonParser().parse(questionnaireJsonDB);
for (String key : questionnaireJson.keySet()) {
if (!key.equals("questionnaireTitle")) {
JsonObject sections = (JsonObject) questionnaireJson.get(key);
// get the questions
for (String key1 : sections.keySet()) {
if (key1.equals("questions")) {
JsonArray questions = (JsonArray) sections.get(key1);
for (int i = 0; i < questions.size(); i++) {
JsonObject indQuestions = (JsonObject) questions.get(i);
String questName = indQuestions.get("questionTitle").getAsString();
if (!questName.equals(questionValue)) {
continue;
}
// Condition 3
String qType = indQuestions.get("questionType").getAsString();
if (qType.equals("radio") || qType.equals("checkbox")) {
optionsArray = indQuestions.get("options").getAsJsonArray();
isMultiChoice = true;
}
}
}
}
}
}
} // End of condition 1 & 2
} catch (Exception e) {
System.out.println("Exception during retrieval of Questionnaire details with SQL : " + questionniareSql);
}
// Get the data values for the charts.
List<Map<String, String>> records = new ConnectionFactory().getArrayForSql(sql);
int i = 0;
final DecimalFormat df = new DecimalFormat("0.00");
float totalCount = 0;
if (records.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>Response</TH><TH>Count</TH></TR>";
HashMap<String, String> tableMap = new HashMap<String, String>();
for (Map<String, String> record : records) {
String countString = record.get("count");
int countPer = StringUtils.getIntFromString(countString);
totalCount = countPer + totalCount;
System.out.println("totalCount "+totalCount);
}
for (Map<String, String> record : records) {
String responseString = record.get("response");
String countString = record.get("count");
if (isMultiChoice) {
tableMap.put(responseString, countString);
} else {
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + i + "><TD>"
+ StringEscapeUtils.escapeJava(responseString) + "</TD><TD>" + countString + "</TD></TR>";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ responseString +"</span>";
i++;
int count = StringUtils.getIntFromString(countString);
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = responseString.split(" ");
if (responseString.length() > 15) {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString.substring(0, 14))
+ "...\"";
} else {
responseStringVal = "\"" + StringEscapeUtils.escapeJava(responseString) + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
}
}
if (isMultiChoice) {
for (int s = 0; s < optionsArray.size(); s++) {
JsonObject indOptions = (JsonObject) optionsArray.get(s);
String optionValue = indOptions.get("value").getAsString();
String optionValue1 = optionValue;
for (char c : optionValue.toCharArray()) {
if (c > 127) {
int sIndex = optionValue.indexOf(c);
// System.out.println(sIndex);
String replaced = optionValue.substring(sIndex);
optionValue1 = optionValue.replace(replaced, "");
// System.out.println(optionValue1);
break;
}
}
tableHTML = tableHTML + "<TR id=" + questionId + "_piechart" + "_" + s + "><TD>" + optionValue1
+ "</TD><TD>" + ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0") + "</TD></TR>";
int count = StringUtils
.getIntFromString((String) ObjectUtils.defaultIfNull(tableMap.get(optionValue), "0"));
cumulativeCount = cumulativeCount + count;
//dailyResponseCounts = dailyResponseCounts + "" + count + ",";
if(count!=0) {
String per = df.format((count/totalCount)*100);
System.out.println(totalCount);
dailyResponseCounts = dailyResponseCounts + "" + per + ",";
System.out.println(dailyResponseCounts);
}
String responseStringVal = "\"" + optionValue1 + "\"";
responseStringValuesForTable = responseStringValuesForTable + responseStringVal + ",";
// String [] responseStringArray = optionValue.split(" ");
if (optionValue1.length() > 15) {
// if (responseStringArray.length > 1) {
responseStringVal = "\"" + optionValue1.substring(0, 14) + "...\"";
} else {
responseStringVal = "\"" + optionValue1 + "\"";
}
responseStringValues = responseStringValues + "" + responseStringVal + ",";
// legendString=legendString+"<span class='dot' style='background-color:"+
// customColors[i % customColors.length]+"'></span><span
// style='margin-left:10px;margin-left:3px;'>"+ optionValue +"</span>";
i++;
}
}
} else {
// No records
}
cMap.put("responseStringValues", responseStringValues);
cMap.put("dailyResponseCounts", dailyResponseCounts);
cMap.put("responseStringValuesForTable", responseStringValuesForTable);
cMap.put("tableHTML", tableHTML);
return cMap;
}
public static String getChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String chartType) throws Exception {
String retVal = "";
String dailyResponseCounts = "[";
String responseStringValues = "[";
String responseStringValuesForTable = "[";
String questionnaireJsonDB = "";
JsonArray optionsArray = new JsonArray();
String sql = "Select questionnairedetails from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "'";
// Get the questionnaire JSON for this entry.
questionnaireJsonDB = new ConnectionFactory().getString(sql);
HashMap<String, String> dataValues = getChartData(projectName, questionnaireName, questionId, questionValue);
if (!StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")).equals("")) {
dailyResponseCounts = dailyResponseCounts
+ StringUtils.trimEndingComma(dataValues.get("dailyResponseCounts")) + "]";
responseStringValues = responseStringValues
+ StringUtils.trimEndingComma(dataValues.get("responseStringValues")) + "]";
responseStringValuesForTable = responseStringValuesForTable
+ StringUtils.trimEndingComma(dataValues.get("responseStringValuesForTable")) + "]";
// Constant strings across chart types.
String cToolbar = "toolbar: {show: true,offsetX: 0,offsetY: 0,tools: { download: true,selection: true,zoom: true,zoomin: true,zoomout: true, pan: true,customIcons: []}},";
String cFill = "fill: {colors: customColors},";
String cColors = "colors: customColors,";
String cLegend = "legend: {show: true,offsetY: -5,position: 'right',height:'100%'}";
// Only for Pie charts, the series and xaxis fields vary. Hence check and
// continue
if (chartType.equals("pie")) {
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: "
+ dailyResponseCounts + "," + " chart: { width: 480,height: 550,"
+ " type: '" + chartType + "'," + " data: "
+ dailyResponseCounts + "," + cToolbar +
" events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cColors
+ " labels: " + responseStringValues + "," + cLegend + " };";
} else {
retVal = "\n" + "<script> var " + questionId + "_options = {"
+ " series:[{ name: 'Count'," + " type: '" + chartType
+ "'," + " data:" + dailyResponseCounts + "" + " }],"
+ " chart: { width: 480,height: 550," + " type: '"
+ chartType + "'," + " data: " + dailyResponseCounts + ","
+ " xaxis: {categories:" + responseStringValues + ",}, " + cToolbar
+ " events: {"
+ " dataPointMouseEnter: function(event, chartContext, config) {"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,1);"
+ " },"
+ " dataPointMouseLeave: function(event,chartContext,config){"
+ " highlightRowfunc(chartContext.el.id, config.dataPointIndex,0);"
+ " }" + " }" + " }," + cFill
+ cColors + " tooltip: {intersect: true,shared: false}, markers: {size: 4},"
+ " labels: " + responseStringValues + "," + cLegend + " };";
}
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\""
+ dataValues.get("tableHTML") + "\"\n";
// Render the Legend
// if (chartType.equals("pie")) {
// retVal = retVal + "document.getElementById('legend_" + questionId +
// "').innerHTML=\""+ legendString+"\"\n";
// }
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
public static String getCrossTabChartHTMLString(String projectName, String questionnaireName, String questionId,
String questionValue, String crossTabQuestionValue, boolean stackedStyle) throws Exception {
String retVal = "";
String sql = " SELECT A.surveydetailsid as id, A.response as question1, B.response as question2, count(*) as count FROM surveyresponsedetails "
+ " as A Right Join surveyresponsedetails As B on A.surveydetailsid = B.surveydetailsid"
+ " where A.isduplicate is null and A.surveydetailsid in ("
+ " select generalkey from surveydetails where questionnaireid in ("
+ " select generalkey from questionnairedetails where projectname='" + projectName
+ "' and questionnairename='" + questionnaireName + "')" + " ) and A.question like '"
+ StringEscapeUtils.escapeSql(org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(questionValue))
+ "'" + " and B.question like '"
+ StringEscapeUtils.escapeSql(
org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(crossTabQuestionValue))
+ "'"
+ " and A.response is not null and A.response <> '' group by A.response, B.response order by A.response asc;";
String legendString = "";
String tableHTML = "";
// Constant Strings of the Chart Settings
String chartPart1 = "chart: { width:800, type: 'bar',stacked: true,";
String chartPart2 = "stackType: '100%',";
String chartPart3 = "toolbar: { show: true }, },";
String chart = "";
// If the stackedStyle is set to true, then display the chart with percentages.
// else with absolute numbers.
if (stackedStyle) {
chart = chartPart1 + chartPart2 + chartPart3;
} else {
chart = chartPart1 + chartPart2 + chartPart3;
}
String responsive = "responsive: [{ breakpoint: 480, options: { legend: { position: 'bottom', offsetX: -10, offsetY: 0}}}],";
String plotOptions = "plotOptions: {bar: {borderRadius: 8,horizontal: false, },},";
String legendNFill = "legend: {position: 'bottom',offsetX: 40},fill: {opacity: 1} ";
String xaxis = "xaxis: {categories:[";
// Create the series String. This is provide the data for the chart.
String series = "[";
List<Map<String, String>> recordsa = new ConnectionFactory().getArrayForSqlForCrossTab(sql);
System.out.println(recordsa);
if (recordsa.size() > 0) { // Check if any records are returned from the DB.
tableHTML = "<TR><TH>" + questionValue + "</TH><TH>" + crossTabQuestionValue + "</TH><TH>Count</TH></TR>";
// Get the unique options for Question1 and Question2
List<String> listQuestion1 = new ArrayList<String>(); // question1 containing duplicates options
List<String> listQuestion2 = new ArrayList<String>(); // question2 containing duplicates options
List<String> listQuestion3 = new ArrayList<String>(); // question3 containing duplicates options for legends
List<String> listQuestion4 = new ArrayList<String>(); // question4 containing duplicates options for legends
for (Map<String, String> record : recordsa) {
String question1Response = StringEscapeUtils.escapeJava(record.get("question1"));
String question1Response1 = record.get("question1");
for(char c: question1Response1.toCharArray()) {
if(c > 127) {
int sIndex = question1Response1.indexOf(c);
//System.out.println(sIndex);
String replaced = question1Response1.substring(sIndex);
question1Response1 = question1Response1.replace(replaced, "");
System.out.println(question1Response1);
break;
}
}
String question2Response = StringEscapeUtils.escapeJava(record.get("question2"));
String question2Response1 = record.get("question2");
System.out.println(question2Response1);
for(char c: question2Response1.toCharArray()) {
if(c > 127) {
int sIndex = question2Response1.indexOf(c);
System.out.println(sIndex);
String replaced = question2Response1.substring(sIndex);
question2Response1 = question2Response1.replace(replaced, "");
System.out.println(question2Response1);
break;
}
}
listQuestion1.add(question1Response);
//System.out.println(listQuestion1);
listQuestion2.add(question2Response);
listQuestion3.add(question1Response1);
listQuestion4.add(question2Response1);
tableHTML = tableHTML + "<TR><TD>" + question1Response1 + "</TD><TD>" + question2Response1 + "</TD><TD>"
+ record.get("count") + "</TD></TR>";
}
Set<String> setQuestion1 = new HashSet<String>(listQuestion1);
Set<String> setQuestion2 = new HashSet<String>(listQuestion2);
listQuestion1.clear();
listQuestion1.addAll(setQuestion1);
for (String qString : setQuestion2) {
// Initialize the temporary series count list.
List<String> seriesCount = new ArrayList<String>(listQuestion1.size());
for (int y = 0; y < listQuestion1.size(); y++) {
seriesCount.add("");
}
series = series + "{name: '" + qString + "', data: ";
for (Map<String, String> record : recordsa) {
String countString = record.get("count");
String questionString = StringEscapeUtils.escapeJava(record.get("question1"));
String crossTabquestionString = StringEscapeUtils.escapeJava(record.get("question2"));
if (qString.equals(crossTabquestionString)) {
seriesCount.set(listQuestion1.indexOf(questionString), countString);
}
}
for (int t = 0; t < listQuestion1.size(); t++) {
if (seriesCount.get(t) == null || seriesCount.get(t).equals("")) {
seriesCount.set(t, "0");
}
}
series = series + seriesCount.toString() + "},";
}
series = StringUtils.trimEndingComma(series) + "]";
String xAxisLegend = "";
for (int t = 0; t < listQuestion1.size(); t++) {
xAxisLegend = xAxisLegend + "'" + listQuestion1.get(t) + "',";
}
xaxis = xaxis + StringUtils.trimEndingComma(xAxisLegend) + "]},";
// return only stacked Bar graph
retVal = "\n" + "<script> var " + questionId + "_options = {" + " series: " + series + ","
+ chart + responsive + plotOptions + xaxis + legendNFill + " }; ";
// Render the chart
retVal = retVal + "var " + questionId + "_chart = new ApexCharts(document.querySelector(\"#" + questionId
+ "_piechart\")," + questionId + "_options);" + questionId + "_chart.render();";
// Render the table content
retVal = retVal + " document.getElementById('table_" + questionId + "').innerHTML=\"" + tableHTML + "\"\n";
// Render the Legend
retVal = retVal + "document.getElementById('legend_" + questionId + "').innerHTML=\"" + legendString
+ "\"\n";
retVal = retVal + "" + "" + "" + "</script>";
// retVal = retVal + legendString;
} else {// Return No records Found
retVal = "<script> document.getElementById('table_" + questionId
+ "').innerHTML='<TR><TH>No Records Found</TH></TR>'\n" + "document.getElementById('legend_"
+ questionId + "').innerHTML=\"\"\n </script>";
}
return retVal;
}
}
I've made a test of a getStudies method, that has a private method call inside itself. Now, how to mock that call in a test method (see down below)?
It's on a second line in a method for testing String query = setQueryForChangingState(filterParams);. I'll provide additional code, if necessary.
Method for testing
public Object getStudies(FilterInputModel filterParams) {
String query = setQueryForChangingState(filterParams);
logger.info("Get studies query: " + query);
LinkedMultiValueMap<String, String> queryMap = new LinkedMultiValueMap<>();
queryMap.add("q", query);
return Objects.requireNonNull(webClient.post()
.uri("/query")
.header(HttpHeaders.AUTHORIZATION, getSessionId())
.body(BodyInserters.fromMultipartData(queryMap))
.retrieve()
.bodyToMono(QueryResponse.class)
.block())
.data;
}
Private method
private String setQueryForChangingState(FilterInputModel filterParams) {
String query = "SELECT id, " +
"basf_study_id__cr.name__v, " +
"name__v, " +
"state__v, " +
"bas_core__cr.name__v, " +
"object_type__vr.name__v, " +
"external__c, " +
"contract_laboratory__cr.name__v, " +
"object_type__v " +
"FROM study__c " +
"WHERE object_type__vr.name__v = 'External Study' " +
"AND contract_laboratory__c != null " +
"AND state__v = 'study_setup_completed_state__c'";
if (!filterParams.getCores().isEmpty()) {
query = query + " AND bas_core__c CONTAINS('" + String.join("','", filterParams.getCores()) + "')";
}
if (!filterParams.getStudyStartDate().isEmpty()) {
if (filterParams.getStudyStartDate().size() == 1) {
query = query + " AND study_start_date__c = '" + filterParams.getStudyStartDate().get(0) + "'";
} else if (filterParams.getStudyStartDate().size() == 2) {
query = query + " AND study_start_date__c BETWEEN '" + filterParams.getStudyStartDate().get(0) + "' AND '" + filterParams.getStudyStartDate().get(1) + "'";
} else {
logger.info("Date range has to many inputs!");
}
}
return query;
}
My test
#Test
#DisplayName("Test getStudies")
void getStudies() throws IOException {
Path filePath = Path.of("src/test/resources/__files/jsonFile.json");
String body = Files.read(filePath.toFile(), Charset.defaultCharset());
wireMockServer.stubFor(post(urlEqualTo("/api/v16.1/query"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(body))
);
List<String> cores = List.of("core");
List<String> dates = List.of("startDate");
List<String> objectTypes = List.of("objectType");
inputModel = new FilterInputModel(cores,dates, "state",objectTypes,
"area","analytMethod", "wp", "subDesc", "analytMonitor", "ecoMonitor",
"subType", "analytNeeded", "8e6a2", "methodAvailable",
"analytPhase", "subAvailable","subShipped", "external",
"uploadValidator","contractLab");
Object response = vaultServiceTest.getStudies(inputModel);
QueryResponse jsonBody = new ObjectMapper().readValue(body, QueryResponse.class);
assertEquals(response, jsonBody.data);
I guess it could be done, but I'm not sure how.
protected void saveData() {
Map<String, String> allStationsParams = new HashMap<>();
List<String> stations = getAllStations();
stmt = Database.getUpdateableStatement();
today = (SysTime.currentTimeMillis() / DasStamp.TICKS_PER_DAY) *
DasStamp.TICKS_PER_DAY;
String changeTimestamp = DasStamp.asCompactString(today);
String keyName = "COM.MAPPINGTOOLTIP." + attributeValue;
for (int row = 0; row < this.getTableModel().getRowCount(); row++) {
String station = (String)this.getTableModel().getValueAt(row, 0);
putInStationParams(this, station, allStationsParams, row);
}
for (String station : stations) {
boolean sendToDB = false;
try (ResultSet rs = this.rsParameters) {
rs.beforeFirst();
while (rs.next()) {
if (rs.getString("station").equals(station)) {
sendToDB = true;
break;
}
}
if (sendToDB) {
if (!rs.getString("value_text").equals(allStationsParams.get(station)) || !allStationsParams.containsKey(station)) {
sendToDB = true;
} else {
sendToDB = false;
}
} else if (allStationsParams.containsKey(station)) {
sendToDB = true;
}
if (sendToDB) {
String sql = "REPLACE INTO dss_parameter (key_name, station, valid_from, value_text"
+ ", change_timestamp) VALUES ('"
+ keyName + "','" + station + "','" + DasStamp.asDateOnlyString(today) + "','"
+ Helper.nz(allStationsParams.get(station)) + "','"
+ changeTimestamp + "') ;";
if (null != stmt) {
stmt.execute(sql);
if (!isResultSetEmpty(rs) && !rs.isAfterLast()) {
AdminLogger.log("dss_parameter", Action.UPDATE,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"value_text='" + rs.getString("value_text") + "'",
"value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
} else {
AdminLogger.log("dss_parameter", Action.INSERT,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"", "value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
}
}
}
} catch (SQLException e) {
AppFrame.msgBox("Error on insert: " + e.getMessage());
Helper.printMessage(true, false, "Parameter save failed!!", e);
}
}
}
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
Your rsParameters parameter is of Type Resultset.
In first iteration, after try{} block is complete close() method of rsParameters:ResultSet is called.
This internally makes all the properties of resultSet NUll.
That is the reason for getting Null properties during second iteration.
SEE: http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.27/com/mysql/jdbc/ResultSetImpl.java#ResultSetImpl.realClose%28boolean%29
I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks
You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.