Exporting data to PDF JAVA, Eclipse, Jasper - java

I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...

Related

how to check if your query is empty using java

I'm using a spring framework and the code I'm using won't work or check if the query is null, though I used a .isEmpty() method it doesn't mean that the query is empty. I wanted to make sure that my query is empty because a part of my code does invoke an id in which case I didn't even though its null so please help me T.T
public List<Object> searchEmployee(EmployeeSearchDto data) {
Session session = sessionFactory.openSession();
final String CRITERIA_EMPLOYEEID = "emp.employeeID =:id";
final String CRITERIA_EMPLOYEEID2 = "emp.employeeID LIKE:id";
final String CRITERIA_POSITION= "emp.positionID =:posID";
final String CRITERIA_DEPARTMENT="emp.departmentID =:deptID";
final String CRITERIA_WORKPLACE = "emp.workplaceID =:workID";
Boolean selected_dept = false;
Boolean selected_pos = false;
Boolean selected_work = false;
Boolean input_empID = false;
Boolean input_empName = false;
firstName = "";
middleName = "";
lastName = "";
completeName = "";
firstLastName = "";
List<String> criteria = new ArrayList<>();
List<Object> employees = null;
// checking the fields if all the fields is empty
try{
//one by one check the select field
String query = "Select"
+ " emp.employeeID,"
+"emp.firstName,"
+"emp.middleName,"
+"emp.lastName,"
+"pos.positionName,"
+"dept.deptName,"
+"work.workplaceName"
+"from Employee emp "
+ "INNER JOIN Department dept "
+ "ON emp.departmentID = dept.deptID "
+ "INNER JOIN Position pos "
+ "ON emp.positionID = pos.positionID "
+ "INNER JOIN Workplace work "
+ "ON emp.workplaceID = work.workplaceID ";
if(!data.isEmpty()) {
query = query.concat("WHERE ");
if(data.getEmployeeID()!="" && data.getEmployeeID()!=null) {
criteria.add(CRITERIA_EMPLOYEEID2);
System.out.println("Employee IDs");
input_empID = true;
}
if(data.getEmployeeName()!="" && data.getEmployeeName()!=null){
criteria.add(nameCriteriaHelper(data.getEmployeeName()));
System.out.println("Employee Name AKOOO");
input_empName = true;
}
if(data.getDepartmentID()!=0) {
criteria.add(CRITERIA_DEPARTMENT);
System.out.println("Dept ID ");
selected_dept = true;
}
if(data.getPositionID()!=0) {
criteria.add(CRITERIA_POSITION);
System.out.println("POS ID ");
selected_pos = true;
}
if(data.getWorkplaceID()!=0) {
criteria.add(CRITERIA_WORKPLACE);
selected_work = true;
}
query = query.concat(String.join(" OR ", criteria));
}
query = query.concat(" ORDER BY emp.joinDate DESC");
System.out.println("QUERY: " + query);
Query q = session.createQuery(query);
if(input_empID) {
q.setParameter("id", "%" + data.getEmployeeID() + "%");
}
if(input_empName) {
if(searchbyOne)
q.setParameter("inputName", "%" + data.getEmployeeName() + "%");
if(searchbyFandL)
q.setParameter("firstLastName", "%" +firstLastName+ "%");
if(searchbyCompName)
q.setParameter("completeName", "%" +completeName+ "%");
}
if(selected_dept) {
q.setParameter("deptID", data.getDepartmentID());
}
if(selected_pos) {
q.setParameter("posID", data.getPositionID());
}
if(selected_work) {
q.setParameter("workID", data.getWorkplaceID());
}
employees = (List<Object>) q.list();
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
return employees;
}
public String nameCriteriaHelper(String name) {
searchbyOne = false;
searchbyFandL = false;
searchbyCompName = false;
final String noOfTokens_1 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :inputName";
final String noOfTokens_2 = "(CONCAT(emp.lastName, ' ', emp.firstName) LIKE :firstLastName "
+ "OR CONCAT(emp.firstName, ' ', emp.lastName) LIKE :firstLastName)";
final String noOfTokens_3 = "CONCAT(emp.lastName,' ',emp.firstName, ' ',emp.middleName) LIKE :completeName";
StringTokenizer stringTokenizer = new StringTokenizer(name);
int no_of_tokens = stringTokenizer.countTokens();
switch(no_of_tokens) {
case 1: searchbyOne = true;
return noOfTokens_1;
case 2: firstName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
firstLastName = lastName + " " + firstName;
searchbyFandL = true;
return noOfTokens_2;
default: int counter = 0;
while( counter < (no_of_tokens - 2)) {
firstName = firstName.concat(stringTokenizer.nextToken() + " ");
counter++;
}
firstName = stringTokenizer.nextToken();
middleName = stringTokenizer.nextToken();
lastName = stringTokenizer.nextToken();
completeName = lastName + " " + firstName + " " + middleName;
searchbyCompName = true;
return noOfTokens_3;
}
You're using wrong order and wrong function to compare string:
Replace:
data.getEmployeeID()!="" && data.getEmployeeID()!=null
With
data.getEmployeeID() != null && !data.getEmployeeID().equals("")
Comparing string must use equals(). And check for null should be done first, before accessing the equals method
You should correct other conditions as above too.
Actually, the logic that Mr. Nguyễn provided here is faulty. An object or variable cannot both be null and initialized to a default value (such as foo == "") at the same time.
At the time of the logic check, if the String is in fact null, the second half of the logic statement will engage, checking to see if the String is equal to "", which will throw a null pointer exception. Instead of checking for both at the same time, check for one and then check for the other like so:
//since two logic checks are being performed,
//it is advantageous to put the data from the query
//into memory so you don't have to get the
//same result twice
String foo = data.getEmployeeID();
if (foo != null)
{
if (!(foo.equals("")))
{
//the result is neither null or empty
}
else
{
//the result is not null but it is empty
}
}
else
{
//the result is null
}

How to remove the quotes while converting a file from sql to tbl

Below is the code which converts the .sql file for insert statements into .tbl file. As the input file is .sql file it contains varchar(string) values inside single quotes. How can I prevent these quotes from getting in my tbl file?
Input:
INSERT INTO
post_tran(post_tran_id,tran_nr,datetime_tran_local,system_trace_audit_nr,settle_
amount_rsp,settle_tran_fee_rsp,post_tran_cust_id,prev_post_tran_id,next_post_tra
n_id,message_type,tran_postilion_originated,sink_node_name,settle_entity_id,batc
h_nr,tran_completed,tran_type,rsp_code_rsp,auth_type,auth_reason,retrieval_refer
ence_nr,settle_amount_req,settle_tran_fee_req,settle_currency_code,datetime_req,
recon_business_date,realtime_business_date,acquiring_inst_id_code) VALUES(
1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink',
1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11
12:00:00', '2004-02-11 12:00:00', '2200017000')
For example:
While processing sink_node_name, its data value should be LinkSink instead of 'LinkSink'.
public class SqlToTblCoverter {
private File source_folder = null;
private File destination_folder = null;
private String source_absolute_path = null;
private String destination_absolute_path = null;
private String absolute_file_name = null;
private String absolute_new_file_name = null;
private List<String> column_name_list = null;
private List<String> column_values_list = null;
public SqlToTblCoverter(String source_folder_name,
String destination_folder_name) {
source_folder = new File(source_folder_name);
destination_folder = new File(destination_folder_name);
source_absolute_path = source_folder.getAbsolutePath();
destination_absolute_path = destination_folder.getAbsolutePath();
column_name_list = new ArrayList<String>();
column_values_list = new ArrayList<String>();
}
public void run() throws IOException {
validateInputs();
migrateFiles();
}
private void validateInputs() {
if (source_folder.isDirectory() == false) {
System.out.println("Source must be a FOLDER");
} else if (destination_folder.isDirectory() == false) {
System.out.println("Destination must be a FOLDER");
}
}
private void migrateFiles() throws IOException {
String[] file_list = source_folder.list();
String file_name1 = file_list[0];
// System.out.println(file_name1);
String file_name2 = file_list[1];
// System.out.println(file_name2);
String f1 = migrateFileContains(file_name1);
String f2 = migrateFileContains(file_name2);
Migrator mg = new Migrator();
mg.migrate(f1, f2);
}
private String migrateFileContains(String file_name) throws IOException {
absolute_file_name = source_absolute_path + File.separator + file_name;
absolute_new_file_name = destination_absolute_path + File.separator
+ getNewFileName(file_name);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(absolute_file_name))));
String line_info = br.readLine();
StringBuffer new_query = new StringBuffer("");
FileWriter fw = new FileWriter(new File(absolute_new_file_name));
while (line_info != null) {
String convertQuery = convertQuery(line_info);
if (convertQuery.isEmpty()) {
line_info = br.readLine();
continue;
}
new_query.append(convertQuery);
new_query.append(System.getProperty("line.separator"));
fw.write(new_query.toString());
new_query.setLength(0);
line_info = br.readLine();
}
br.close();
fw.close();
return absolute_new_file_name;
}
private String convertQuery(String query) {
String new_query = "";
if (query.startsWith("INSERT")) {
int round_bracket_start = query.indexOf('(');
int round_bracket_end = query.indexOf(')');
int round_bracket_start_after_values = query.indexOf('(',
round_bracket_end);
String query_column_name = query.substring(round_bracket_start + 1,
round_bracket_end);
String query_column_values = query.substring(
round_bracket_start_after_values + 1, query.length() - 1);
covertColumnNameList(query_column_name);
covertColumnValueList(',' + query_column_values + ',');
new_query = createNewQuery() + "\n";
}
column_name_list.clear();
column_values_list.clear();
return new_query;
}
private void covertColumnNameList(String query_column_name) {
String[] column_list = query_column_name.split(",");
for (String column_name : column_list) {
column_name_list.add(column_name);
}
}
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}
private String createNewQuery() {
StringBuffer buffer = new StringBuffer("");
if (column_name_list.size() != column_values_list.size()) {
System.out.println("Error : " + absolute_file_name);
} else {
for (int index = 0; index < column_name_list.size(); index++) {
buffer.append(createNewColumn(column_name_list.get(index),
column_values_list.get(index)));
}
}
return buffer.toString();
}
private String createNewColumn(String column_name, String column_value) {
StringBuffer buffer = new StringBuffer("");
buffer.append("[name]".trim());
buffer.append(column_name.trim());
buffer.append("[/name]=[data]".trim());
buffer.append(column_value.trim());
buffer.append("[/data]".trim());
buffer.append("\r\n");
return buffer.toString();
}
private String getNewFileName(String file_name) {
String new_file_name = "";
int dot_index = file_name.indexOf('.');
new_file_name = file_name.subSequence(0, dot_index) + ".tbl";
return new_file_name;
}
}
You can replace covertColumnValueList with below code:
private void covertColumnValueList(String query_column_values) {
String temp_val = null;
for (String col_val : query_column_values.split(",")) {
if (col_val.contains("\'")) {
temp_val = col_val.replaceAll("\'", "");
column_values_list.add(temp_val.trim());
} else
column_values_list.add(col_val.trim());
}
}
I assume you have query_column_values something like below:
String query_column_values = "1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink', 1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11 12:00:00', '2004-02-11 12:00:00', '2200017000'";
replace '' by current date: Once you populate this list, replace list value at specified index.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
column_values_list.set( 23, dateFormat.format(cal.getTime()));
The code to remove the delimiting apostrophes is there in covertColumnValueList, but it doesn't handle the case where a space precedes the apostroph. See the simple fix below.
//....
int next_comma_index = 0;
// skip space(s)
while( query_column_values.charAt(comma_index + 1) == ' ' ){
comma_index++;
}
if (query_column_values.charAt(comma_index + 1) == '\'') {
//...
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
column_value=column_value.replace("\'","") ;
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
column_value=column_value.replace("\'","") ;
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}

Threaded application writing duplicate lines to log file

I have written a multithreaded application that analyzes rows in a database with regex and updates them appropriately. I am writing each row to a log file for logging purposes. I have noticed that the same row is being written to the log file several times...sometimes upwards of 15 times. Here are snippets of the code.
Setting up ThreadPoolExecuter:
private static BlockingQueue<Runnable> worksQueue = new ArrayBlockingQueue<Runnable>(blockingQueueSize);
private static ThreadPoolExecutor exec = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 10, TimeUnit.SECONDS, worksQueue);
In this part, I run a query, then go through the results:
rs = ps.executeQuery();
while (rs.next()) {
exec.execute(new UpdateMember(rs, conn, fileWriter));
if (worksQueue.size() == blockingQueueSize) {
//reach the maximum, stop refill
for (;;) {
Thread.yield();
//wait until the size of queue reached the minimum
if (worksQueue.size() == 0) {
//start refill
break;
}
}
}
}
UpdateMember (with only run and writeToLog methods showing):
public class UpdateMember implements Runnable {
ResultSet rs;
Connection conn;
FileWriter fw;
public UpdateMember(ResultSet rs, Connection conn, FileWriter fw) {
this.rs = rs;
this.conn = conn;
this.fw = fw;
}
#Override
public void run() {
try {
String regex = "((?<city>[a-zA-Z\\s\\.]+)\\s)?(?<provState>AB|ALB|Alta|alberta|BC|B\\.C\\.|British Columbia|LB|Labrador|MB|Man|Manitoba|N[BLTSU]|Nfld|NF|Newfoundland|NWT|Northwest Territories|Nova Scotia|New Brunswick|Nunavut|ON|ONT|Ontario|PE|PEI|Prince Edward Island|QC|PC|QUE|QU|Quebec|SK|Sask|Saskatchewan|YT|Yukon|Yukon Territories)(\\s(?<country>CA|CAN|CANADA))?$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
BigDecimal memrecno = rs.getBigDecimal(2);
String addressLineTwo = rs.getString(4);
String addressLineThree = rs.getString(5);
String addressLineFour = rs.getString(6);
BigDecimal attrrecno = rs.getBigDecimal(9);
String addressBeingParsed = "";
String city = null;
String province = null;
String country = null;
boolean usingAddressThree = false;
boolean usingAddressFour = false;
if (addressLineFour == null) {
if (addressLineThree == null) {
city = "Unknown";
}
else
{
addressBeingParsed = addressLineThree;
usingAddressThree = true;
}
}
else
{
addressBeingParsed = addressLineFour;
usingAddressFour = true;
}
if (usingAddressThree || usingAddressFour) {
Matcher matcher = pattern.matcher(addressBeingParsed);
// if matches are found
if (matcher.matches()) {
city = matcher.group("city");
province = matcher.group("provState");
country = matcher.group("country");
if (city == null || city.isEmpty()) {
// cities are alpha characters and spaces only
String cityRegex = "(?<city>^[a-zA-Z\\s\\.]+$)";
Pattern cityPattern = Pattern.compile(cityRegex, Pattern.CASE_INSENSITIVE);
if (usingAddressFour && (addressLineThree != null) && !addressLineThree.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineThree);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else if (usingAddressThree && (addressLineTwo != null) && !addressLineTwo.isEmpty()) {
Matcher cityMatcher = cityPattern.matcher(addressLineTwo);
if (cityMatcher.matches()) {
city = cityMatcher.group("city");
}
else
{
city = "Unknown";
}
}
else
{
city = "Unknown";
}
}
if (province != null && !province.isEmpty()) {
province = createProvinceCode(province);
}
}
else
{
city = "Unknown";
}
}
// update attributes in database
boolean success = updateRow(memrecno, attrrecno, city, province);
String logLine = memrecno.toString() + "|" + attrrecno.toString() + "|" + addressLineTwo + "|" + addressLineThree + "|" + addressLineFour + "|" + city + "|" + province + "|" + country + "|" + success + "|" + String.valueOf(Thread.currentThread().getId());
writeToLog(logLine);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private synchronized void writeToLog(String line) {
try {
fw.write(line + "\r\n");
fw.flush();
}
catch (IOException ex)
{
System.out.println("Error writing to log file. " + ex.getMessage());
}
}
}
I don't know if the threads are also calling the updateRow method multiple times, but I'm assuming they are and that's really bad.
Any ideas as to why it would be doing this?
I don't think ResultSet is thread safe. From your code, you should get the value first and then pass the value instead of rs into the thread.

Iterating through an array and checking values of the items

I'm populating an array by taking data from a mysql table, and what I'm trying to do is iterate through that array, check the value of each item and then do perform different actions depending on what the value is.
This is the code for the method where I connect to the database and try and iterate through the array
public void HomeRecord(){
ArrayList<HomeTeamResults> allResults = new ArrayList<>();
try
{
//Sets up the connedtion to the database and installs drivers which are required.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost", "username", "password");
String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE `HomeTeam` = ?";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
rs = prepst.executeQuery();
HomeTeamResults hometeamResults=null;
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result);
allResults.add(hometeamResults);
}
}
catch (Exception e)
{
System.out.println("Error " +e);
}
System.out.println("Size of HomeArrayList::"+allResults.size());
for(HomeTeamResults temp:allResults){
if(temp.getResult().equals("W")){
hometeamvalue = hometeamvalue + 50;
}
else if(temp.getResult().equals("D")){
hometeamvalue = hometeamvalue + 10;
}
else
{
hometeamvalue = hometeamvalue + 0;
}
}
}
And this is the code for the array
public class HomeTeamResults {
private String hometeam;
private String awayteam;
private String result;
public String getHomeTeam() {
return hometeam;
}
public void setHomeTeam(String hometeam) {
this.hometeam = hometeam;
}
public String getAwayTeam() {
return awayteam;
}
public void setAwayTeam(String awayteam) {
this.awayteam = awayteam;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
private HomeTeamResults(String hometeam, String awayteam, String result)
{
this.hometeam = hometeam;
this.awayteam = awayteam;
this.result = result;
}
#Override
public String toString()
{
return " "+hometeam+", "+awayteam+", "+result;
}
}
The problem I have is with the comparison. When I try if(temp.getResult().equals("W") then it doesn't work at all. And if I try if(result.equals("W") then what it does is take the first result from the array and then assumes that every other item in the array is the same.
Not sure where I'm going wrong, any ideas?
You are adding the object in the list but not initialize the object anywhere while iterating the result.
HomeTeamResults hometeamResults=null; // Object is null
while (rs.next())
{
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
custs = (hometeam + "," + awayteam + "," + result); // No idea abt usage
hometeamResults = new HomeTeamResults(hometeam,awayteam,result); // Initial It
allResults.add(hometeamResults); // Now List will contain proper object
}
You are initiallizing the reference with null value what you have to do first is to create your object then set the values in it somewhat like
HomeTeamResults hometeamResults= null;
while (rs.next())
{ hometeamResults=new HomeTeamResults()
hometeam = rs.getString("HomeTeam");
awayteam = rs.getString("AwayTeam");
result = rs.getString("Result");
hometeamResults.setHomeTeam(hometeam);
hometeamResults.setAwayTeam(awayteam);
hometeamResults.setResult(result);
allResults.add(hometeamResults);
}

Fetch an entire row with jdbc as a List

I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}

Categories

Resources