How can I set the x-axis and y-axis in charts - java

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;
}
}

Related

Netsuite getting error while generating signature with filter

I am trying to create a RestAPI request to fetch details of a records with a filter 'START_WITH'. But every request I send is getting rejected with the error '401 Unauthorized. Invalid Signature'. But if I don't add the filter and only send the normal request, It gives correct response back.
My code for generating signature is:
public String generateOauthHeader(
String method, UserFields userFields, String baseUrl, String offset, String limit) {
long timestamp = new Date().getTime() / 1000;
String nonce = getAlphaNumericString();
ArrayList<String> parameters = new ArrayList<>();
parameters.add(
ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL
+ userFields.getConsumerKey());
parameters.add(ApplicationConstants.NONCE + ApplicationConstants.EQUAL + nonce);
parameters.add(
ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.SIGNATURE_METHOD_VAL);
parameters.add(ApplicationConstants.TIMESTAMP + ApplicationConstants.EQUAL + timestamp);
parameters.add(
ApplicationConstants.OAUTH_TOKEN + ApplicationConstants.EQUAL + userFields.getTokenId());
parameters.add(
ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL
+ ApplicationConstants.VERSION_VAL);
if (offset != null) {
parameters.add(ApplicationConstants.OFFSET + ApplicationConstants.EQUAL + offset);
}
if (limit != null) {
parameters.add(ApplicationConstants.LIMIT_CLAUSE + ApplicationConstants.EQUAL + limit);
}
parameters.add("q" + ApplicationConstants.EQUAL + "companyname START_WITH COMP1234");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? ApplicationConstants.AMPERSAND : "") + parameters.get(i));
}
String signature = null;
try {
String signatureString =
method
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(baseUrl, StandardCharsets.UTF_8)
+ ApplicationConstants.AMPERSAND
+ URLEncoder.encode(parametersList.toString(), StandardCharsets.UTF_8);
SecretKeySpec signingKey =
new SecretKeySpec(
(userFields.getConsumerSecret()
+ ApplicationConstants.AMPERSAND
+ userFields.getTokenSecret())
.getBytes(),
ApplicationConstants.HMACSHA256);
Mac m = Mac.getInstance(ApplicationConstants.HMACSHA256);
m.init(signingKey);
m.update(signatureString.getBytes());
byte[] res = m.doFinal();
signature = Base64Coder.encodeLines(res);
} catch (Exception e) {
e.printStackTrace();
}
return ApplicationConstants.OAUTH
+ ApplicationConstants.REALM
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getAccountId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.CONSUMER_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getConsumerKey()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.OAUTH_TOKEN
+ ApplicationConstants.EQUAL_START_QUOTES
+ userFields.getTokenId()
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.SIGNATURE_METHOD_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.TIMESTAMP
+ ApplicationConstants.EQUAL_START_QUOTES
+ timestamp
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.NONCE
+ ApplicationConstants.EQUAL_START_QUOTES
+ nonce
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.VERSION_KEY
+ ApplicationConstants.EQUAL_START_QUOTES
+ ApplicationConstants.VERSION_VAL
+ ApplicationConstants.END_QUOTES
+ ApplicationConstants.SIGNATURE
+ ApplicationConstants.EQUAL_START_QUOTES
+ URLEncoder.encode(signature, StandardCharsets.UTF_8)
+ ApplicationConstants.QUOTES;
}
Url generated without filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer/
Url generated with filter: https ://1212112-sb1.suitetalk.api.netsuite.com/services/rest/record/v1/customer?q="companyName START_WITH COMP1234"

My "for loop" on java only return the result on the first row of jtable and repeat it for the rest number of row

So I have some issue on my for loop. It only work on the first row of jtable and printed the same result to the whole rows. here's my code:
try {
int row = tblHasil.getRowCount();
for (int i = 0; i < row; i++) {
String tempA = (String) tblHasil.getModel().getValueAt(i, 3);
String tempB = (String) tblHasil.getModel().getValueAt(i, 4);
String tempC = (String) tblHasil.getModel().getValueAt(i, 5);
double a = Double.parseDouble(tempA);
double b = Double.parseDouble(tempB);
double c = Double.parseDouble(tempC);
VNilaiRataRata.setNilaiRataRata(a);
VTanggungan.setTanggungan(b);
VPenghasilan.setPenghasilan(c);
Rules.hitung_u();
Rules.hitung_z();
DecimalFormat df = new DecimalFormat("#########.###");
double hasildef = Double.parseDouble(df.format(Rules.defuzzifikasi()));
VKeterangan.setKeterangan(hasildef);
double keterangan = VKeterangan.getKeterangan();
double tidakLolos = VKeterangan.tidaklolos();
double cadangan = VKeterangan.cadangan();
double lolos = VKeterangan.lolos();
String desc;
if (lolos > cadangan && lolos > tidakLolos) {
desc = "Lolos";
tblHasil.setValueAt(desc, i, 6);
} else if (cadangan > tidakLolos && cadangan > lolos) {
desc = "Cadangan";
tblHasil.setValueAt(desc, i, 6);
} else {
desc = "Tidak Lolos";
tblHasil.setValueAt(desc, i, 6);
}
System.out.println("Nama : " + tblHasil.getModel().getValueAt(i, 1));
System.out.println("Hasil Fuzzi : " + hasildef);
System.out.println("Keterangan Value : " + keterangan);
System.out.println("Keterangan Tidak Lolos : " + tidakLolos);
System.out.println("Keterangan Cadangan : " + cadangan);
System.out.println("Keterangan Lolos : " + lolos);
System.out.println("Nilai Rata2 : " + VNilaiRataRata.getNilaiRataRata());
System.out.println("Tangungan : " + VTanggungan.getTanggungan());
System.out.println("Penghasilan : " + VPenghasilan.getPenghasilan());
System.out.println("Keterangan : " + desc);
System.out.println("================================");
System.out.println();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost/db_siswa", "root", "");
int nis = Integer.parseInt(tblHasil.getModel().getValueAt(i, 0).toString());
String sql = "UPDATE nilaisiswa SET hasil='" + desc + "' WHERE nis = '" + nis + "'";
cn.createStatement().executeUpdate(sql);
}
} catch (Exception e) {
e.printStackTrace();
java.util.logging.Logger.getLogger(Proses.class.getName()).log(Level.SEVERE, null, e);
}
And here's the result (marked with red circle) :
i don't know how to use this thing

how to interact over a list of objects return consolidated data [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Why does my Java code return a memory address and not a string? [duplicate]
(4 answers)
Closed 2 years ago.
I'm trying to make my object list "revogacaoData"
show the data as "name", "date", "login", but the return is always the memory space.
How to interact to return this data?
This is the code
#GetMapping(value = { "/gerarCsv/{inicio}&{fim}" })
#ResponseBody
public ResponseEntity<?> gerarCsv(HttpServletRequest request,
#PathVariable(value = "inicio", required = true) String inicio,
#PathVariable(value = "fim", required = true) String fim) {
try {
Date dataInicio = new SimpleDateFormat("dd-MM-yyyy").parse(inicio);
Date dataFim = new SimpleDateFormat("dd-MM-yyyy").parse(fim);
List<Object> revogacaoConsolidado = revogacao.consultarRevogacaoconsolidado(dataInicio, dataFim);
File arquivo = new File("C:\\src\\main\\resources\\revogacao.csv");
if(!arquivo.exists()) {
arquivo.createNewFile();
}
FileWriter fw = new FileWriter(arquivo);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Date" + ";" + "login" + ";" + "nome");
for(int i = 0 ; i < revogacaoConsolidado.size() ; i++) {
System.out.println(revogacaoConsolidado.get(i));
bw.newLine();
bw.write( revogacaoConsolidado.get(0) + ";" + revogacaoConsolidado.get(1));
}
System.out.println("Finished");
bw.close();
fw.close();
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId() + ", usuario:"
+ request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado CSV ]");
return new ResponseEntity<Object>(revogacaoConsolidado, HttpStatus.OK);
} catch (Exception e) {
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId() + ", usuario:"
+ request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado] error: " +e);
return new ResponseEntity<String>("{\"msg\":\" Não foi possivel obter a lista consolidada}",
HttpStatus.EXPECTATION_FAILED);
}
}
And this is the return
[Ljava.lang.Object;#585e2103
I tried interate like this :
revogacaoConsolidado[i][1]
but didn't work
I made some changes, created a model class where I can create the necessary toString.
these were the changes.
Controller:
#GetMapping(value = { "/gerarCsv/{inicio}&{fim}" })
#ResponseBody
public ResponseEntity<?> gerarCsv(HttpServletRequest request,
#PathVariable(value = "inicio", required = true) String inicio,
#PathVariable(value = "fim", required = true) String fim) {
try {
Date dataInicio = new SimpleDateFormat("dd-MM-yyyy").parse(inicio);
Date dataFim = new SimpleDateFormat("dd-MM-yyyy").parse(fim);
List<RevogacaoConsolidado> revogacaoConsolidado = revogacao.consultarRevogacaoconsolidado(dataInicio, dataFim);
File arquivo =newFile("C:\\src\\\\main\\\\resources\\\\revogacao.csv");
if(!arquivo.exists()) {
arquivo.createNewFile();
}
FileWriter fw = new FileWriter(arquivo);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Data" + ";" + "login" + ";" + "nome");
for(int i = 0 ; i < revogacaoConsolidado.size() ; i++) {
String[] revog = new String[revogacaoConsolidado.size()];
int index = 0;
for(Object value : revogacaoConsolidado) {
revog[index] = String.valueOf(value);
index++;
System.out.println("Data : " + revog[0].toString());
}
bw.newLine();
bw.write( revog[0] + ";" + revogacaoConsolidado.get(1));
}
System.out.println("Finished");
bw.close();
fw.close();
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId() + ", usuario:"
+ request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado CSV ]");
return new ResponseEntity<Object>(revogacaoConsolidado, HttpStatus.OK);
} catch (Exception e) {
logger.info("[Recurso:/admin/revogacao/revogacaoPorDataCSV, sessao:" + request.getSession().getId() + ", usuario:"
+ request.getUserPrincipal().getName() + "]"
+ "[Verificação de Revogações por data de processado] error: " +e);
return new ResponseEntity<String>("{\"msg\":\" Não foi possivel obter a lista consolidada}",
HttpStatus.EXPECTATION_FAILED);
}
}
Model:
package br.com.claro.tcc.web.portalsega.model;
import java.util.Date;
public class RevogacaoConsolidado {
private Date data_processo;
private String login;
private String nome;
private String eucesso;
private String erro;
private String nao_cadastrado;
private String ja_removido;
private String total;
private String porcent_erro;
//getters and setters
#Override
public String toString() {
return "revogacaoConsolidado [data_processo=" + data_processo + ", login=" + login + ", nome=" + nome + ", eucesso="
+ eucesso + ", erro=" + erro + ", nao_cadastrado=" + nao_cadastrado + ", ja_removido=" + ja_removido
+ ", total=" + total + ", porcent_erro=" + porcent_erro + "]";
}
}
ConsultaRevogacaoConsolidada Service
#Transactional
public List<RevogacaoConsolidado> consultarRevogacaoconsolidado(Date inicio, Date fim) {
return revogacaoDAO.consultarRevogacaoconsolidado(inicio, fim);
}
ConsultaRevogacaoConsolidada DAO
#Override
public List<RevogacaoConsolidado> consultarRevogacaoconsolidado(Date inicio,Date fim) {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String inicioData =dateFormat.format(inicio);
String fimData =dateFormat.format(fim);
Query query = sessionFactory.getCurrentSession()
.createNativeQuery("select \r\n" +
"to_char(a.dh_processado,'dd/mm/yyyy') as data_processo,\r\n" +
"count(b.login) as login\r\n" +
",c.nome,\r\n" +
"sum(case when e.nome = 'SUCESSO' then 1 else 0 end) SUCESSO,\r\n" +
"sum(case when e.nome = 'ERRO' then 1 else 0 end) ERRO,\r\n" +
"sum(case when e.nome = 'NAO CADASTRADO' then 1 else 0 end) NAO_CADASTRADO,\r\n" +
"sum(case when e.nome = 'JA REMOVIDO' then 1 else 0 end) JA_REMOVIDO,\r\n" +
"sum(case when e.nome = 'SUCESSO' then 1 else 0 end) + \r\n" +
"sum(case when e.nome = 'ERRO' then 1 else 0 end) +\r\n" +
"sum(case when e.nome = 'NAO CADASTRADO' then 1 else 0 end) +\r\n" +
"sum(case when e.nome = 'JA REMOVIDO' then 1 else 0 end) TOTAL,\r\n" +
"round((sum(case when e.nome = 'ERRO' then 1 else 0 end) / sum(case when e.nome = 'SUCESSO' then 1 end))*100,2) as porcentagem_erro\r\n" +
"\r\n" +
"from tb_revogacao_exec a\r\n" +
"inner join tb_revogacao b on b.login = a.login\r\n" +
"inner join tb_revogacao_processo c on c.id = a.id_processo\r\n" +
"inner join tb_revogacao_sistema d on d.id = a.id_sistema\r\n" +
"inner join tb_revogacao_status e on e.id = a.id_status\r\n" +
"where a.dh_processado BETWEEN to_date(:inicio,'dd/MM/yyyy') \r\n" +
"AND to_date(:fim,'dd/MM/yyyy') \r\n" +
"group by c.nome,to_char(a.dh_processado,'dd/mm/yyyy') "
+ "order by to_char(a.dh_processado,'dd/mm/yyyy') desc");
query.setParameter("inicio", inicioData);
query.setParameter("fim",fimData);
return query.getResultList();
}

Java: Create CSV from Get Array with Object

I have
data= [{
id=1,
employee_name=Tiger Nixon,
employee_salary=320800,
employee_age=61,
profile_image=
},
{
id=2,
employee_name=Garrett Winters,
employee_salary=170750,
employee_age=63,
profile_image=
},
{
id=3,
employee_name=Ashton Cox,
employee_salary=86000,
employee_age=66,
profile_image=
},
{
id=4,
employee_name=Cedric Kelly,
employee_salary=433060,
employee_age=22,
profile_image=
}
]
I have employee class
public class Employee {
private String employee_name;
private String employee_salary;
private String employee_age;
private String id;
private String profile_image;
public String toCsvRow() {
String csvRow = "";
for (String value : Arrays.asList(employee_name,employee_salary,employee_age)) {
String processed = value;
if (value.contains("\"") || value.contains(",")) {
processed = "\"" + value.replaceAll("\"", "\"\"") + "\"";
}
csvRow += "," + processed;
}
return csvRow.substring(1);
}
public String getEmployee_name() {
return employee_name;
}
public String getEmployee_salary() {
return employee_salary;
}
public String getEmployee_age() {
return employee_age;
}
}
I tried for
Map<String, ArrayList<Employee>> map = mapper.readValue(url, Map.class);
ArrayList<Employee> emps = map.get("data");
emps.get(0).toCsvRow()
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.example.model.Employee
Now I cannot call toCSVRow using emps.
Use Gson to parse JSON to ArrayList, for CSV conversion you can use org.json.CDL
See this is working fine
String str = "[{" +
" id=1," +
" employee_name=\"Tiger Nixon\"," +
" employee_salary=320800," +
" employee_age=61," +
" profile_image=\"khkjh\"" +
" }," +
" {" +
" id=2," +
" employee_name=\"Garrett Winters\"," +
" employee_salary=170750," +
" employee_age=63," +
" profile_image=\"\"" +
" }," +
" {" +
" id=3," +
" employee_name=\"Ashton Cox\"," +
" employee_salary=86000," +
" employee_age=66," +
" profile_image=\"\"" +
" }," +
" {" +
" id=4," +
" employee_name=\"Cedric Kelly\"," +
" employee_salary=433060," +
" employee_age=22," +
" profile_image=\"\"" +
" }" +
" ]";
try{
Gson gson = new Gson();
ArrayList<Employee> list = gson.fromJson(str, ArrayList.class);
String csv = CDL.toString(new JSONArray(list));
}catch (Exception e){
e.printStackTrace();
}
Output:
id,employee_name,employee_salary,employee_age,profile_image
1.0,Tiger Nixon,320800.0,61.0,khkjh
2.0,Garrett Winters,170750.0,63.0,
3.0,Ashton Cox,86000.0,66.0,
4.0,Cedric Kelly,433060.0,22.0

Trouble Updating a Table Row in Java

Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now

Categories