JSON Parser End Of File Error - java

I have this program, sending request to receive weather information from the web in JSON format. I will sending one request per city in a for loop. However after the first JSON is received and parsed whenever it tries to parse the second one it gives end of file error and does not write the information into the database. What might be the problem ?
public static void getHistory()
{
Connection connection = connectToDatabase();; // manages connection
System.out.println("Getting History Data");
//Loops through every single city and requests, parses and inserts the history weather data.
PreparedStatement pStatement = null;
Scanner scanner = new Scanner(System.in);
for(int i = 35 ; 0 < cities.length ; i++)
{
int errorCount = 0;
int userInput;
System.out.printf("City no : %d. 1 to continue\n", i+1);
JSONParser parser = new JSONParser();
JSONObject jsonObj = new JSONObject();
Object obj = new Object();
String resultString = new String();
userInput = scanner.nextInt();
if(userInput != 1)
{
System.out.println("Terminating the program!");
break;
}else if(userInput == 1)
{
System.out.println("Continue...");
}
System.out.println("For Loop");
System.out.printf("!%d: %s!\n", i, cities[i]);
resultString = sendRequestForHistoryData(cities[i]);
try
{
obj = parser.parse(resultString);
jsonObj = (JSONObject)obj;
parseHistoryData(jsonObj);
}
catch(ParseException pe)
{
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
//Iterates through all the WeatherData objects and writes them into the database.
Iterator<WeatherData> vectorIterator = parsedWeatherObjects.iterator();
System.out.printf("Vector Length: %d\n", parsedWeatherObjects.size());
Statement statement = null;
while(vectorIterator.hasNext())
{
WeatherData weather = vectorIterator.next();
/*
* Table Structure for HistoryData Table in SQL Server
* 1) City_ID - int
* 2)City_Name - nvarchar(50)
* 3)Time - datetime
* 4)Received_Time - datetime
* 5)Humidity - float
* 6)Rain_info - float
* 7)Snow_info - float
* 8)Temperature - float
* 9)Min_Temperature - float
* 10)Max_Temperature - float
* 11)Description - nvarchar(50)
*/
try
{
String statementString = "INSERT INTO WeatherHistory("
+"City_ID,"
+"City_Name,"
+"Time,"
+"Received_Time,"
+"Humidity,"
+"Rain_Info,"
+"Snow_Info,"
+"Temperature,"
+"Min_Temperature,"
+"Max_Temperature,"
+"Description)"
+"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
pStatement = connection.prepareStatement(statementString);
java.sql.Date sqlDate = new java.sql.Date(weather.getDate());
java.sql.Date currentSqlDate = new java.sql.Date(currentTimestamp.getTime());
//java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(weather.getDate());
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+2"));
String formattedDate = convertEpochToDateString(weather.getDate());
//System.out.printf("Formatted Date: " + formattedDate + "\n");
java.sql.Timestamp sqlTimestamp = Timestamp.valueOf(formattedDate);
pStatement.setInt(1, weather.getCityCode());
pStatement.setString(2, weather.getCity());
pStatement.setTimestamp(3, sqlTimestamp, cal);
pStatement.setDate(4, currentSqlDate);
pStatement.setFloat(5, weather.getHumidity());
pStatement.setFloat(6, weather.getRainInfo());
pStatement.setFloat(7, weather.getSnowInfo());
pStatement.setFloat(8, weather.getTemperature());
pStatement.setFloat(9, weather.getMinTemperature());
pStatement.setFloat(10, weather.getMaxTemperature());
pStatement.setString(11, weather.getDescription());
pStatement.execute();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
//e.printStackTrace();
//System.out.println("SQL Key error.");
errorCount++;
}
}//While Loop End
System.out.printf("SQL Error Count: %d\n", errorCount);
try
{
if (pStatement != null)
{
pStatement.close();
System.out.println("Statement close.");
}
}catch (SQLException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
}//For Loop End
try
{
if (connection != null)
{
connection.close();
System.out.println("Connection close.");
}
} catch (SQLException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
}//Function End

Related

Strings can not be converted to DAO Receiver

I am trying to perform batch insertion operation with a list object but while inserting I am getting String cannot be converted to DAO.The receiver in the iterator loop.
I have tried to list the list object, at that time it is printing values from the list. but, when I use generics are normal list it is showing error and I don't find any solution to insert
From this method I am reading the excel file and storing into list
public List collect(Receiver rec)
{
//ReadFromExcel rd = new ReadFromExcel();
List<String> up = new ArrayList<String>();
//List<String> details = rd.reader();
//System.out.println(details);
try( InputStream fileToRead = new FileInputStream(new File(rec.getFilePath())))
{
XSSFWorkbook wb = new XSSFWorkbook(fileToRead);
wb.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
XSSFSheet sheet = wb.getSheetAt(0);
DataFormatter fmt = new DataFormatter();
String data ="";
for(int sn = 0;sn<wb.getNumberOfSheets()-2;sn++)
{
sheet = wb.getSheetAt(sn);
for(int rn =sheet.getFirstRowNum();rn<=sheet.getLastRowNum();rn++)
{
Row row = sheet.getRow(rn);
if(row == null)
{
System.out.println("no data in row ");
}
else
{
for(int cn=0;cn<row.getLastCellNum();cn++)
{
Cell cell = row.getCell(cn);
if(cell == null)
{
// System.out.println("no data in cell ");
// data = data + " " + "|";
}
else
{
String cellStr = fmt.formatCellValue(cell);
data = data + cellStr + "|";
}
}
}
}
}
up = Arrays.asList(data.split("\\|"));
// System.out.println(details);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
Iterator iter = up.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
String row="";
Receiver info = null;
String cid = "";
String cname = "";
String address = "";
String mid = "";
boolean b = false;
List<Receiver> res = new ArrayList<Receiver>();
int c = 0;
try
{
String str = Arrays.toString(up.toArray());
//System.out.println(str);
String s = "";
s = s + str.substring(1,str.length());
// System.out.println("S:"+s);
StringTokenizer sttoken = new StringTokenizer(s,"|");
int count = sttoken.countTokens();
while(sttoken.hasMoreTokens())
{
if(sttoken.nextToken() != null)
{
// System.out.print(sttoken.nextToken());
cid = sttoken.nextToken();
cname = sttoken.nextToken();
address = sttoken.nextToken();
mid = sttoken.nextToken();
info = new Receiver(cid,cname,address,mid);
res.add(info);
System.out.println("cid :"+cid+ " cname : "+cname +" address : "+address+" mid : "+mid);
c = res.size();
// System.out.println(c);
}
else
{
break;
}
}
System.out.println(count);
// System.out.println("s");
}
catch(NoSuchElementException ex)
{
System.out.println("No Such Element Found Exception" +ex);
}
return up;
}
with this method I'm trying to insert into database
public boolean insert(List res)
{
String sqlQuery = "insert into records(c_id) values (?)";
DBConnection connector = new DBConnection();
boolean flag = false;
// Iterator itr=res.iterator();
// while(it.hasNext())
// {
// System.out.println(it.next());
// }
try( Connection con = connector.getConnection();)
{
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(sqlQuery);
Iterator it = res.iterator();
while(it.hasNext())
{
Receiver rs =(Receiver) it.next();
pstmt.setString(1,rs.getcID());
pstmt.setString(2,rs.getcName());
pstmt.setString(3,rs.getAddress());
pstmt.setString(4,rs.getMailID());
pstmt.addBatch();
}
int [] numUpdates=pstmt.executeBatch();
for (int i=0; i < numUpdates.length; i++)
{
if (numUpdates[i] == -2)
{
System.out.println("Execution " + i +": unknown number of rows updated");
flag=false;
}
else
{
System.out.println("Execution " + i + "successful: " + numUpdates[i] + " rows updated");
flag=true;
}
}
con.commit();
} catch(BatchUpdateException b)
{
System.out.println(b);
flag=false;
}
catch (SQLException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
flag=false;
}
return flag;
}
I want to insert list object using JDBC batch insertion to the database.
Your method collect(Receiver rec) returns the List of strings called up.
return up;
However (if you are really using the method collect to pass the List into insert(List res) method), you are expecting this list to contain Receiver objects. Which is incorrect, since it collect(..) returns the list of Strings.
And that causes an error when you try to cast Receiver rs =(Receiver) it.next();
You need to review and fix your code, so you will pass the list of Receiver objects instead of strings.
And I really recommend you to start using Generics wherever you use List class. In this case compiler will show you all data-type errors immediately.

Thread automatically stop (freeze) in Eclipse

I am running a thread in eclipse to get data from mysql server. Thread works fine. The problem is after bit of time thread stop running(withing 6 to 8 hours). Thread get freeze. After that I have to manually close and re-run the program. Eclipse runs in a windows server 2012 r2 machine. No error or exception is shown.
Main class.
public class Main {
private final static int fONE_DAY = 1;
private final static int fZERO_MINUTES = 0;
public static void main(String[] argv) {
Timer timer1 = new Timer();
Timer timer4 = new Timer();
try {
timer1.scheduleAtFixedRate(new CearteSDQuatation(),500 , 1000*60*4);// 4min
System.out.println("timer 1 : createSDQuotation");
} catch (Exception e) {
e.printStackTrace();
}
try {
timer4.schedule(new GarbageCol(), 5000, 1000 * 60 * 60);// 60mins
System.out.println("timer 2 : garbageCollector");
} catch (Exception e) {
e.printStackTrace();
}
}
private static Date getTomorrowRunningTime(int Ftime){
Calendar tomorrow = new GregorianCalendar();
tomorrow.add(Calendar.DATE, fONE_DAY);
Calendar result = new GregorianCalendar(
tomorrow.get(Calendar.YEAR),
tomorrow.get(Calendar.MONTH),
tomorrow.get(Calendar.DATE),
Ftime,
fZERO_MINUTES
);
return result.getTime();
}
}
CearteSDQuatation class.
public class CearteSDQuatation extends TimerTask {
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");;
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
DBPool_SF pooler;
DataSource dataSource;
DataSource dataSource1;
DBTableQueryExcecutre qex = null;
DBTableQueryExcecutre qex3 = null;
DBTableQueryExcecutre qex1 = null;
DBTableQueryExcecutre qex2 = null;
ArrayList<String> dates = null;
HashSet<String> dateSet = null;
Iterator<String> itr = null;
StringBuilder inClause;
int rcount = 0;
StringBuilder sbDel = null;
int delStatus = 0;
ArrayList<String> elements = new ArrayList<String>();// for update query
int queryStatus = 0;
String delete_query1 = " ";
String strDate = "";
String strMatnr = "";
String strkunnr = "";
// Object for table data
private Object[][] itemData;
RFCHandler handler;
public CearteSDQuatation(){
handler = new RFCHandler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
CallItem_ListCreate();
CallRFC_CreateSDQuata();
System.out.println("Thread Run");
}
catch (Exception e){
e.printStackTrace();
}
}
private void CallItem_ListCreate() {
// TODO Auto-generated method stub
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
System.out.println("Create Quotation : Started sub excecutions List create...");
String sbQuery3 = "SELECT d.plant, h.dis_channel, h.order_no, h.Rep_no," +
"h.dealer_no,h.order_date,h.last_date, d.items_no," +
"d.quantity " +
"FROM tbl_item_list as d, " +
"tbl_items_header_t as h " +
"where d.order_no = h.order_no " +
"and h.status <> 'X'" ;
try {
pooler = DBPool_SF.getInstance();
dataSource1 = pooler.getDataSource();
System.out.println("pooler");
} catch (Exception e1)
{
e1.printStackTrace();
}
try {
Connection con3 = dataSource1.getConnection();
con3.setAutoCommit(false);
Statement st = con3.createStatement();
ResultSet rs = st.executeQuery(sbQuery3);
int lineitem = 0;
try {
rs.last();
rcount = rs.getRow();
rs.beforeFirst();
}
catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("while loop");
itemData = new Object[9][rcount];
while(rs.next())
{
itemData[0][lineitem] = rs.getString("plant");
lineitem = lineitem + 1;
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void CallRFC_CreateSDQuata()
{
System.out.println("Create Quotation : Started sub excecutions");
JCO.Table IT_LIST = null;
JCO.Table IT_LIST1 = null;
JCO.Table IT_REF = null;
JCO.Table IT_Msg = null;
try {
if(rcount > 0)
{
handler.createRFCFunction("ZSL");
IT_LIST = handler.getTablePara("IT_LIST");
IT_LIST1 = handler.getTablePara("IT_LIST1");
for(int x = 0; x < rcount; x++ )
{
IT_LIST.appendRow();
IT_LIST1.appendRow();
IT_LIST.setValue( itemData[0][x].toString().trim(), "SAL_ORG");
}
handler.excFunction();
IT_REF = handler.getTablePara("IT_REF");
IT_Msg = handler.getTablePara("IT_MSG");
handler.releaseClient();
int int_row = IT_REF.getNumRows();
if (int_row > 0) {
this.tableOparator(IT_REF , IT_Msg);
}
}
} catch (Exception ex) {
handler.releaseClient();
ex.printStackTrace();
}
finally {
// Release the client to the pool
//handler.releaseClient();
rcount = 0;
}
}
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
public void tableOparator(JCO.Table table , JCO.Table table1 ) throws Exception {
pooler = DBPool_SF.getInstance();
dataSource = pooler.getDataSource();
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
qex = new DBTableQueryExcecutre(con);
StringBuilder sbQuery = new StringBuilder(
"INSERT INTO tbl_RefQut (QuatationNo,RefOrderNumber) VALUES");
System.out.println("COL -->"+table.getNumRows()
+ " records to insert for tbl_RefQut");
// --- create query ---------------------------------
for (int i = 0; i < table.getNumRows(); i++) {
// table.setRow(i);
sbQuery.append("(?,?),");
}
sbQuery.deleteCharAt(sbQuery.length() - 1);
sbQuery.append(";");
qex.setUpdateQuery(sbQuery.toString());// *****************
elements.clear();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
elements.add(table.getString("SDOCUMENT").trim());
elements.add(table.getString("ONUMBER").trim());
}
qex.updateInsertQuery(elements);
con.commit();
StringBuilder sbQuery1 = new StringBuilder(
"INSERT INTO tbl_item_order_msg (order_no,msg) VALUES");
System.out.println("COL -->"+table1.getNumRows()
+ " records to insert for tbl_item_order_msg");
// --- create query ---------------------------------
for (int i = 0; i < table1.getNumRows(); i++) {
// table.setRow(i);
sbQuery1.append("(?,?),");
}
sbQuery1.deleteCharAt(sbQuery1.length() - 1);
sbQuery1.append(";");
qex.setUpdateQuery(sbQuery1.toString());// *****************
elements.clear();
for (int i = 0; i < table1.getNumRows(); i++) {
table1.setRow(i);
elements.add(table1.getString("ORDER_NUMBER").trim());
elements.add(table1.getString("MESSAGE").trim());
}
qex.updateInsertQuery(elements);
con.commit();
for (int i = 0; i < table.getNumRows(); i++) {
table.setRow(i);
String sbQuery2 = "update tbl_items_header_t set status = 'X' where order_no = '" + table.getString("ORDER_NUMBER").trim() + "';";
int rcount = qex.runQuery(sbQuery2);
System.out.println("tbl_items_header_t Rows -->"+rcount + "Status Updated");
con.commit();
}
qex.closeConnections();
System.out.println("COL --> Cycle Finished....");
}
}
a possible reason to this situation is, you are hitting mysql's max open connections error, because you are not closing connections in method CallItem_ListCreate. it seems mysql default max connection count is 151. you are openning 15 connections per hour and after 10 hour you will hit that mentiooned error.
p.s. : you should try running your code in debug mode (or using tools like visualvm, jstack) and view thread dumps as #saurav commented.

How to update data in table?

I finished making an encryption program that encrypts text and tried to apply this program to encrypt a field in a database table. I have a problem that all the data field is encrypted by on value (last record)
public static void main(String[] args) throws IOException {
String v_url = "jdbc:oracle:thin:#192.168.2.154:1522:orcl2";
String v_username = "scott";
String v_password = "tiger";
Connection con = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(v_url, v_username, v_password);
System.out
.println("Connection to Oracle database was Established");
String sql = "select JOB_NAME from job ";
Statement stmt = con.createStatement();
ResultSet srs = stmt.executeQuery(sql);
while (srs.next()) {
vname = srs.getString("job_name");
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
Scanner in = new Scanner(System.in);
System.out.println("Enter Your KeyText ");
String StrKey = in.nextLine();
// Print the Concatenated Data.
String ConcatenatedData = StrKey.concat(vname);
System.out.println("The plaintext Data is : " + ConcatenatedData);
// Convering the Concatenated data to Ascii data.
byte[] asciiText = null;
try {
// translating text String to 7 bit ASCII encoding
asciiText = ConcatenatedData.getBytes("US-ASCII");
// System.out.println(Arrays.toString(asciiText));
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
String binary = "";
for (byte b : asciiText) {
// binary = Integer.toBinaryString(b & 255 | 256).substring(1);
binary += Integer.toBinaryString(0x100 + (int) (b & 0xFF)).substring(1);
}
// System.out.println("Requested binary :" +binary);
String ReversedBinary = binary.replace('0', '2').replace('1', '0').replace('2', '1');
// System.out.println("Reveresd binary :" + ReversedBinary);
mainencdec decimalToBinary = new mainencdec();
String binary1 = decimalToBinary.convertBinaryStringToString(ReversedBinary);
try {
String sql_statment = "UPDATE job SET job_name =?";
PreparedStatement updatequery = con.prepareStatement(sql_statment);
updatequery.setString(1, binary1);
updatequery.executeQuery();
con.commit();
System.out.println("An existing user was updated successfully!");
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
the problem is that the data in job name field is encrypted by the same value as: JOB_NAME
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
I want each value in this field encrypted according to its data

How to customize the TotalRecordCount and Paging after filter in jTable jquery (Java-JSP)

I use a jTable jquery for jsp page, it work very well. It can display the showing count records in bottom right of table well (e.g. Showing 1-10 of 22). When I insert the Filtering into the page, the showing count record is not correctly.
I follow this for Filtering: http://www.jtable.org/Demo/Filtering
How to customize the code for showing count record (I use java-jsp and sql server). Sorry for my English language :))
Here is the code I am using right now in controller.
if (action.equals("list")) {
try {
int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
int numRecordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
String jtSorting = null;
//Fetch Data from Rejected_Product Table
lstSite = dao.**getAllSite**(filter_site, startPageIndex, numRecordsPerPage, jtSorting);
//Get Total Record Count for Pagination
int siteCount = dao.**getSiteCount**();
//Convert Java Object to Json
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(lstSite, new TypeToken<List<Site>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
//Return Json in the format required by jTable plugin
listData = "{\"Result\":\"OK\",\"Records\":"+listData+",\"TotalRecordCount\":"+siteCount+"}";
response.getWriter().print(listData);
System.out.println(listData);
} catch (Exception ex) {
String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getStackTrace() + "}";
response.getWriter().print(error);
ex.printStackTrace();
}
}
and here method getAllSite:
public List<Site> getAllSite (FilterSite filter_site, int jtStartIndex, int jtPageSize, String jtSorting) {
List<Site> siteList = new ArrayList<Site>();
String query = "";
String siteQ = filter_site.getSite();
String clientQ = filter_site.getClient(); // wait
String locationQ = filter_site.getLocation();
if (locationQ.isEmpty()) {
locationQ = "";
} else {
locationQ = "and location like '%"+locationQ+"' ";
}
String site_idQ = filter_site.getSite_id();
if (site_idQ.isEmpty()) {
site_idQ = "";
} else {
site_idQ = "and site_id = '"+site_idQ+"' ";
}
String divisionQ = filter_site.getDivision();
if (divisionQ.isEmpty()) {
divisionQ = "";
} else {
divisionQ = "and division = '"+divisionQ+"' ";
}
int range = jtStartIndex+jtPageSize;
query = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY CODE) as row FROM [site]) a "
+ "WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+") "
+ "and row > "+jtStartIndex+" and row <= "+range;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
System.out.println("query : "+query);
while (rs.next()) {
Site sitebean = new Site();
sitebean.setName(rs.getString("name"));
sitebean.setCode(rs.getString("code"));
.....
siteList.add(sitebean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return siteList;
}
and here method getSiteCount :
public int getSiteCount () {
int count = 0;
String query = "SELECT COUNT(*) as count FROM [site] ";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
count = rs.getInt("count");
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
If you mean by "not correctly" that the row count is larger than expected, then the solution would be to include the where clause in the siteCount query.
WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+")

java.sql.SQLException: No suitable driver found for jdbc:oracle:thin

I currently have a web app that has certain classes able to connect to my database, but one other class cant.For whatever reason, I have started to get this exception for one of my classes. Here is what I have done:
I am working with Java 7 and have ojdbc7 in both my class path and lib folder
I have multiple classes who can connect to the url file, yet my other class cant and throws "java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#someurl"
My class is able to access the database AFTER I have connected to it in another class
I have a config.properties file that contains the URL, so I know the URL is not at fault and never changes
Here is my code where the program fails. I don't connect to the database until I call this method too:
public SimpleEntry<String, String> loadOrders(File file) {
SimpleEntry<String, String> response = new SimpleEntry<String, String>(
"", "");
PreparedStatement st = null;
ResultSet rs = null;
Connection con = null;
try {
Scanner scan = new Scanner(file);
String header = "";
String trailer = "";
int orderCtr = 0;
int valueCtr = 0;
String request = "";
ArrayList<HashMap<String, String>> orders =
new ArrayList<HashMap<String, String>>();
log.info("Scanning content");
// start to scan content
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\t");
String type = sc.next();
// differentiates between header, trailer, and content
if (type.equals("H")) {
header = line;
} else if (type.equals("T")) {
trailer = line;
break;
} else {
// begin to enter in data appropriately from method's
// parameter
// key of map = column, value = data being inserted
HashMap<String, String> order = new HashMap<String, String>();
// Format:
/*
* CLIENT_CUSTOMER_ID, FIRST_NAME, LAST_NAME,___, ADDRESS1,
* ADDRESS2, CITY, STATE, POSTAL_CODE, PHONE, EMAIL_ADDRESS,
* STORE_NUMBER, DELIVERY_METHOD,___, REWARD_VALUE,___,___,
* CARD_ACTIVE_DATE, CARD_EXPIRED_DATE, REQUEST
*/
order.put("CLIENT_CUSTOMER_ID", sc.next());
String name = sc.next();
order.put("FIRST_NAME", name.substring(0, 1).toUpperCase()
+ name.substring(1).toLowerCase());
name = sc.next();
order.put("LAST_NAME", name.substring(0, 1).toUpperCase()
+ name.substring(1).toLowerCase());
sc.next();
order.put("ADDRESS1", sc.next());
order.put("ADDRESS2", sc.next());
order.put("CITY", sc.next());
order.put("STATE", sc.next());
order.put("POSTAL_CODE", sc.next());
order.put("PHONE", sc.next());
order.put("EMAIL_ADDRESS", sc.next());
order.put("STORE_NUMBER", sc.next());
order.put("DELIVERY_METHOD", sc.next());
sc.next();
// purpose of valueCtr -> count reward values for a total
String oVal = sc.next();
valueCtr += Integer.parseInt(oVal);
order.put("REWARD_VALUE", oVal);
sc.next();
sc.next();
order.put("CARD_ACTIVE_DATE", sc.next());
order.put("CARD_EXPIRED_DATE", sc.next());
// used later in program
request = sc.next();
order.put("REQUEST", request);
orders.add(order);
// count number of orders
orderCtr++;
}
sc.close();
}
scan.close();
log.info("Scanning complete");
// finds if the trailer contains the correct value and order amount
boolean ok = true;
if (!trailer.contains(Integer.toString(valueCtr))) {
ok = false;
}
if (!trailer.contains(Integer.toString(orderCtr))) {
ok = false;
}
// if the trailer doesnt, throw error
if (!ok) {
log.error("Error in loadOrders: Order Count
and/or total value of file \n does not match trailer amounts");
response = new SimpleEntry<String, String>("ERROR",
"Order Count and/or total value of file \n does
not match trailer amounts");
return response;
}
String className = "oracle.jdbc.driver.OracleDriver";
Class.forName(className);
con = DriverManager.getConnection(Env.getCardUrl(),
Env.getCardUser(), Env.getCardPass());
log.info("Starting insertion statement");
String query = "SELECT MAX(BATCH_ID) + 1 FROM INTEGRATION.OL_ORDER";
st = con.prepareStatement(query);
rs = st.executeQuery();
rs.next();
int batch = rs.getInt(1);
String insert = "INSERT INTO INTEGRATION.OL_ORDER ("
+ "BATCH_ID, "
+ "CLIENT_CUSTOMER_ID, "
+ "FIRST_NAME, "
+ "LAST_NAME, "
+ "ADDRESS1, "
+ "ADDRESS2, "
+ "CITY, "
+ "STATE, "
+ "POSTAL_CODE, "
+ "PHONE, "
+ "EMAIL_ADDRESS, "
+ "STORE_NUMBER, "
+ "DELIVERY_METHOD, "
+ "REWARD_VALUE, "
+ "CARD_ACTIVE_DATE, "
+ "CARD_EXPIRED_DATE, "
+ "REQUEST,"
+ "PASSPHRASE, "
+ "ITEM_CODE, "
+ "CONFIRMED_MAILADDR, "
+ "JET_CLIENT_ID) VALUES(?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
st = con.prepareStatement(insert);
log.info("Insertion complete, reorganizing data");
// add batch
for (HashMap<String, String> o : orders) {
st.setInt(1, batch);
// first, last, address1, address2, city, state, postal, phone,
// storenum, delivery
// validation and formatting
ArrayList<String> content = validateContent(
o.get("FIRST_NAME"), o.get("LAST_NAME"),
o.get("ADDRESS1"), o.get("ADDRESS2"), o.get("CITY"),
o.get("STATE"), o.get("POSTAL_CODE"), o.get("PHONE"),
o.get("STORE_NUMBER"), o.get("DELIVERY_METHOD"));
st.setString(2, o.get("CLIENT_CUSTOMER_ID"));
st.setString(3, content.get(0));
st.setString(4, content.get(1));
st.setString(5, content.get(2));
st.setString(6, content.get(3));
st.setString(7, content.get(4));
st.setString(8, content.get(5));
st.setString(9, content.get(6));
st.setString(10, content.get(7));
st.setString(11, o.get("EMAIL_ADDRESS"));
st.setString(12, content.get(8));
st.setString(13, content.get(9));
st.setInt(14, Integer.parseInt(o.get("REWARD_VALUE")));
st.setDate(15, stringToDate(o.get("CARD_ACTIVE_DATE")));
st.setDate(16, stringToDate(o.get("CARD_EXPIRED_DATE")));
st.setString(17, o.get("REQUEST"));
st.setString(18, getRandom());
st.setString(19, "17331-000002");
st.setString(20, "0");
st.setInt(21, 97);
st.addBatch();
}
st.executeBatch();
log.info("Reorganization complete");
response = new SimpleEntry<String, String>(Integer.toString(batch),
request);
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String temp = errors.toString();
log.fatal("Error inside loadOrders(): " + temp);
return null;
} finally {
Dir.close(rs, st, con);
}
return response;
}
My code for Dir.close:
public static void close(ResultSet rs, Statement ps, Connection conn) {
Logger logger =LogManager.getLogger("AE");
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("The result set cannot be closed.", e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
logger.error("The statement cannot be closed.", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error("The data source connection cannot be closed.", e);
}
}
}
As mentioned in my last comment, the JAR was on the webapp's class which meant the error couldn't be caused by a lack of drivers. Apparently when deploying my WAR file, tomcat was referencing an older WAR file or something with code that was not updated with the code I had posted above. After exporting my WAR file and renaming to an arbitrary name followed by deploying it under that name, I was not getting the error anymore. Something else to think about is the my messiness of code in the previous war file; I wasn't closing PreparedStatement, Result, and even the Connection variables correctly. Updating the war with a different name with the code posted above worked.

Categories