List of usage examples for java.sql Connection createStatement
Statement createStatement() throws SQLException;
Statement
object for sending SQL statements to the database. From source file:com.alifi.jgenerator.spring.SpringGeneratorFactory.java
public static void main(String[] args) { @SuppressWarnings("unused") ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("META-INF/SpringContext.xml"); for (DataSourceMap m : DataSourceUtil.getDataSourceMap()) { DataSource ds = m.getDataSource(); try {//from w w w. j a v a 2 s. c om Connection con = ds.getConnection(); DatabaseMetaData dmd = con.getMetaData(); String catalog = con.getCatalog(); String schemaPattern = dmd.getSchemaTerm(); System.out.println("Catalog:" + con.getCatalog() + " schemaPattern:" + schemaPattern); ResultSet rs = dmd.getTables(catalog, schemaPattern, "time_zone_transition", null); Statement s = null; ResultSet xrs = null; try { s = con.createStatement(); xrs = s.executeQuery("select * from time_zone_transition"); if (xrs.next()) { p("xxxxxxxxxxxxxxxxxxxxxxxx:" + xrs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { } while (rs.next()) { p("-----------------------"); p("TABLE_CAT :" + rs.getString("TABLE_CAT")); p("TABLE_SCHEM:" + rs.getString("TABLE_SCHEM")); p("TABLE_NAME :" + rs.getString("TABLE_NAME")); p("TABLE_TYPE :" + rs.getString("TABLE_TYPE")); p("REMARKS: " + rs.getString("REMARKS")); p("11111111111111111:" + rs.getMetaData().getColumnClassName(1)); // ResultSet pkeyRs = dmd.getPrimaryKeys(catalog, schemaPattern, rs.getString("TABLE_NAME")); while (pkeyRs.next()) { p("M-------------M"); p("------COLUMN_NAME:" + pkeyRs.getString("COLUMN_NAME")); p("------KEY_SEQ:" + pkeyRs.getString("KEY_SEQ")); p("------PK_NAME:" + pkeyRs.getString("PK_NAME")); } // ResultSet rss = dmd.getColumns(catalog, schemaPattern, rs.getString("TABLE_NAME"), null); int cCount = rss.getMetaData().getColumnCount(); for (int i = 1; i <= cCount; i++) { p("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); p(" getColumnClassName:" + rss.getMetaData().getColumnClassName(i)); p(" getColumnLabel:" + rss.getMetaData().getColumnLabel(i)); p(" getColumnName:" + rss.getMetaData().getColumnName(i)); p(" getColumnTypeName:" + rss.getMetaData().getColumnTypeName(i)); p(" getColumnType:" + ColumnTypes.getType(rss.getMetaData().getColumnType(i))); } } rs = dmd.getTableTypes(); while (rs.next()) { p("========================="); p("TABLE_TYPE: " + rs.getString("TABLE_TYPE")); } // ResultSetMetaData rsmd = rs.getMetaData(); // int numberOfColumns = rsmd.getColumnCount(); // for (int i = 1; i <= numberOfColumns; i++) // p(rsmd.getColumnName(i)); } catch (SQLException e) { e.printStackTrace(); } p(m.toString()); } }
From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java
public static void main(String[] args) { long start = System.currentTimeMillis(); String fid = null;/*from w w w .j a va2s . c o m*/ logger.info( "args[0] = threadcount, args[1] = db connection string, args[2] = db username, args[3] = password"); if (args.length >= 4) { CONCURRENT_THREADS = Integer.parseInt(args[0]); db_url = args[1]; db_usr = args[2]; db_pwd = args[3]; } if (args.length > 4) { fid = args[4]; } Connection c = getConnection(); //String count_sql = "select count(*) as cnt from objects where bbox is null or area_km is null"; String count_sql = "select count(*) as cnt from objects where area_km is null and st_geometrytype(the_geom) <> 'ST_Point' "; if (StringUtils.isEmpty(fid)) { count_sql = count_sql + " and fid = '" + fid + "'"; } int count = 0; try { Statement s = c.createStatement(); ResultSet rs = s.executeQuery(count_sql); while (rs.next()) { count = rs.getInt("cnt"); } } catch (Exception e) { logger.error(e.getMessage(), e); } int iter = count / 200000; logger.info("Breaking into " + iter + " iterations"); for (int i = 0; i <= iter; i++) { long iterStart = System.currentTimeMillis(); // updateBbox(); updateArea(fid); logger.info("iteration " + i + " completed after " + (System.currentTimeMillis() - iterStart) + "ms"); logger.info("total time taken is " + (System.currentTimeMillis() - start) + "ms"); } }
From source file:CreateStores.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; String createTable;/*from ww w . j a v a 2 s . co m*/ String createArray; createArray = "CREATE TYPE COF_ARRAY AS ARRAY(10) OF VARCHAR(40)"; createTable = "CREATE TABLE STORES ( " + "STORE_NO INTEGER, LOCATION ADDRESS, " + "COF_TYPES COF_ARRAY, MGR REF MANAGER )"; Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createArray); stmt.executeUpdate(createTable); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:PrimaryKeysSuppliers.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; String createString = "create table SUPPLIERSPK " + "(SUP_ID INTEGER NOT NULL, " + "SUP_NAME VARCHAR(40), " + "STREET VARCHAR(40), " + "CITY VARCHAR(20), " + "STATE CHAR(2), " + "ZIP CHAR(5), " + "primary key(SUP_ID))"; Statement stmt;/*from ww w. ja va 2s. c o m*/ try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createString); DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getPrimaryKeys(null, null, "SUPPLIERSPK"); while (rs.next()) { String name = rs.getString("TABLE_NAME"); String columnName = rs.getString("COLUMN_NAME"); String keySeq = rs.getString("KEY_SEQ"); String pkName = rs.getString("PK_NAME"); System.out.println("table name : " + name); System.out.println("column name: " + columnName); System.out.println("sequence in key: " + keySeq); System.out.println("primary key name: " + pkName); System.out.println(""); } rs.close(); con.close(); } catch (SQLException ex) { System.err.print("SQLException: "); System.err.println(ex.getMessage()); } }
From source file:ForeignKeysCoffees.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; String createString = "create table COFFEESFK " + "(COF_NAME varchar(32) NOT NULL, " + "SUP_ID int, " + "PRICE float, " + "SALES int, " + "TOTAL int, " + "primary key(COF_NAME), " + "foreign key(SUP_ID) references SUPPLIERSPK)"; Statement stmt;//from w w w .j a v a2 s .c o m try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createString); DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getImportedKeys(null, null, "COFFEESFK"); while (rs.next()) { String pkTable = rs.getString("PKTABLE_NAME"); String pkColName = rs.getString("PKCOLUMN_NAME"); String fkTable = rs.getString("FKTABLE_NAME"); String fkColName = rs.getString("FKCOLUMN_NAME"); short updateRule = rs.getShort("UPDATE_RULE"); short deleteRule = rs.getShort("DELETE_RULE"); System.out.println("primary key table name : " + pkTable); System.out.print("primary key column name : "); System.out.println(pkColName); System.out.println("foreign key table name : " + fkTable); System.out.print("foreign key column name : "); System.out.println(fkColName); System.out.println("update rule: " + updateRule); System.out.println("delete rule: " + deleteRule); System.out.println(""); } rs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.print("SQLException: "); System.err.println(ex.getMessage()); } }
From source file:CreateNewType.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt;//from w ww. j a va 2 s .c o m try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); String typeToCreate = null; String prompt = "Enter 's' to create a structured type " + "or 'd' to create a distinct type\n" + "and hit Return: "; do { typeToCreate = getInput(prompt) + " "; typeToCreate = typeToCreate.toLowerCase().substring(0, 1); } while (!(typeToCreate.equals("s") || typeToCreate.equals("d"))); Vector dataTypes = getDataTypes(con, typeToCreate); String typeName; String attributeName; String sqlType; prompt = "Enter the new type name and hit Return: "; typeName = getInput(prompt); String createTypeString = "create type " + typeName; if (typeToCreate.equals("d")) createTypeString += " as "; else createTypeString += " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter an attribute name " + "(or nothing when finished) \nand hit Return: "; attributeName = getInput(prompt); if (firstTime) { if (attributeName.length() == 0) { System.out.print("Need at least one attribute;"); System.out.println(" please try again"); continue; } else { createTypeString += attributeName + " "; firstTime = false; } } else if (attributeName.length() == 0) { break; } else { createTypeString += commaAndSpace + attributeName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter an attribute type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTypeString += localTypeName + paramString; if (typeToCreate.equals("d")) break; } if (typeToCreate.equals("s")) createTypeString += ")"; System.out.println(""); System.out.print("Your CREATE TYPE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTypeString); System.out.println(""); stmt.executeUpdate(createTypeString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:CreateUDTs.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt;/*from w w w .j a va2s.com*/ String createAddress = "CREATE TYPE ADDRESS (NUM INTEGER, " + "STREET VARCHAR(40), CITY VARCHAR(40), " + "STATE CHAR(2), ZIP CHAR(5))"; String createManager = "CREATE TYPE MANAGER (MGR_ID INTEGER, " + "LAST_NAME VARCHAR(40), FIRST_NAME VARCHAR(40), " + "PHONE char(10))"; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); stmt.executeUpdate(createAddress); stmt.executeUpdate("CREATE TYPE PHONE_NO AS CHAR(10)"); stmt.executeUpdate(createManager); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("-----SQLException-----"); System.err.println("SQLState: " + ex.getSQLState()); System.err.println("Message: " + ex.getMessage()); System.err.println("Vendor: " + ex.getErrorCode()); } }
From source file:Main.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con; Statement stmt;//from w ww . ja va2s .c om try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); Vector dataTypes = getDataTypes(con); String tableName; String columnName; String sqlType; String prompt = "Enter the new table name and hit Return: "; tableName = getInput(prompt); String createTableString = "create table " + tableName + " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: "; columnName = getInput(prompt); if (firstTime) { if (columnName.length() == 0) { System.out.print("Need at least one column;"); System.out.println(" please try again"); continue; } else { createTableString += columnName + " "; firstTime = false; } } else if (columnName.length() == 0) { break; } else { createTableString += commaAndSpace + columnName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter a column type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTableString += localTypeName + paramString; } createTableString += ")"; System.out.println(""); System.out.print("Your CREATE TABLE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTableString); System.out.println(""); stmt.executeUpdate(createTableString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void main(String[] args) { log.info("GCM - Sender running"); do {/*from www.j a v a 2s. c o m*/ Connection conn = null; Connection conn2 = null; Statement stmt = null; Statement stmt2 = null; try { // STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 3: Open a connection // System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); conn2 = DriverManager.getConnection(DB_URL, USER, PASS); // STEP 4: Execute a query // System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId"; ResultSet rs = stmt.executeQuery(sql); // STEP 5: Extract data from result set while (rs.next()) { log.info("Notification found"); int userId = rs.getInt("userId"); stmt2 = conn2.createStatement(); String sql2; sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId=" + userId; ResultSet rs2 = stmt2.executeQuery(sql2); int notificationCounter = rs2.getInt("notificationCounter"); rs2.close(); stmt2.close(); // Retrieve by column name // Display values // System.out.print("userId: " + userId); // System.out.print(", notificationCounter: " + // notificationCounter); SendNotification(userId, notificationCounter); } // STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); conn2.close(); } catch (SQLException se) { // Handle errors for JDBC log.error(se.getMessage()); se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName log.error(e.getMessage()); e.printStackTrace(); } finally { // finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { log.error(se2.getMessage()); } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { log.error(se.getMessage()); se.printStackTrace(); } // end finally try } // end try try { Thread.sleep(1000); } catch (InterruptedException e) { log.error(e.getMessage()); e.printStackTrace(); } } while (1 != 0); }
From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java
public static void main(String[] args) { String exportIdPRPC, exportIdII, exportFileIdII, exportFileIdPRPC, queryII, queryPRPC; boolean hasArgs = false; if (args != null && args.length >= 1) { UsageAdjInvoiceRegenerator.PROPERTY_FILE_NAME = args[0]; hasArgs = true;//from ww w .j a va 2 s . c om } AppParamManager.initParameters(hasArgs); if (!AppParamManager.TASK_ID.equals("")) { try { zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME, AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION); zApiClient.login(); } catch (Exception ex) { Logger.print(ex); Logger.print("RefreshSession - There's exception in the API call."); } queryPRPC = AppParamManager.PRPCexportQuery; queryII = AppParamManager.IIexportQuery; exportIdPRPC = zApiClient.createExport(queryPRPC); exportIdII = zApiClient.createExport(queryII); // ERROR createExport fails if (exportIdII == null || exportIdII.equals("")) { Logger.print("Error. Failed to create Invoice Item Export"); //return false; } // ERROR createExport fails if (exportIdPRPC == null || exportIdPRPC.equals("")) { Logger.print("Error. Failed to create PRPC export"); //return false; } exportFileIdII = zApiClient.getExportFileId(exportIdII); if (exportFileIdII == null) { Logger.print("Error. Failed to get Invoice Item Export file Id"); //log.closeLogFile(); //return false; } exportFileIdPRPC = zApiClient.getExportFileId(exportIdPRPC); if (exportFileIdPRPC == null) { Logger.print("Error. Failed to get PRPC Export file Id"); //log.closeLogFile(); //return false; } // get the export file from zuora //zApiClient.getFile(exportFileIdII, exportFileIdTI); /* Logger.print("II export ID: "+exportFileIdII); Logger.print("TI export ID: "+exportFileIdTI); */ Logger.print("Opening Export file"); //Base64 bs64 = new BASE64Encoder(); /* String login = AppParamManager.USER_NAME+":"+AppParamManager.USER_PASSWORD; String authorization ="Basic "+ Base64.encodeBase64String(login.getBytes()); String zendpoint = ""; */ String authorization = ""; //Base64 bs64 = new BASE64Encoder(); if (AppParamManager.USER_SESSION.isEmpty()) { String login = AppParamManager.USER_NAME + ":" + AppParamManager.USER_PASSWORD; authorization = "Basic " + Base64.encodeBase64String(login.getBytes()); } else { authorization = "ZSession " + AppParamManager.USER_SESSION; } String zendpoint = ""; try { /* if( AppParamManager.API_URL.contains("api") ){ //look in api sandbox zendpoint = "https://apisandbox.zuora.com/apps/api/file/"; } else { //look in production zendpoint = "https://www.zuora.com/apps/api/file/"; } */ int index = AppParamManager.API_URL.indexOf("apps"); index = index + 5; zendpoint = AppParamManager.API_URL.substring(0, index) + "api/file/"; Logger.print(zendpoint); //zendpoint = AppParamManager.FILE_URL; //Start reading Invoice Items String zendpointII = zendpoint + exportFileIdII + "/"; URL url = new URL(zendpointII); URLConnection uc = url.openConnection(); //Logger.print("Opening invoice item file: "+exportFileIdII+" authorization: "+authorization); uc.setRequestProperty("Authorization", authorization); InputStream content = (InputStream) uc.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); CSVReader cvsReader = new CSVReader(in); List<String[]> batchOfRawDataList = null; while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "InvoiceItem"); } in.close(); String zenpointPRPC = zendpoint + exportFileIdPRPC + "/"; url = new URL(zenpointPRPC); uc = url.openConnection(); uc.setRequestProperty("Authorization", authorization); content = (InputStream) uc.getInputStream(); in = new BufferedReader(new InputStreamReader(content)); cvsReader = new CSVReader(in); while ((batchOfRawDataList = cvsReader.parseEntity()) != null) { UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(), "PRPCItem"); } in.close(); Logger.print("start processing values"); UsageAdjInvoiceRegenerator chargeAdjustment = new UsageAdjInvoiceRegenerator(); int[] results; int totalErrors = 0; String emailmsg = ""; Logger.print("----------------------------------------"); Logger.print("start creating usages"); results = zApiClient.createUsageItems(newUsageCollection); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage creation "; } totalErrors = totalErrors + results[1]; Logger.print("start cancelling invoices"); results = zApiClient.alterInvoices(newUsageCollection, "cancel"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice cancellation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting usages"); results = zApiClient.deleteUsageItems(deleteList); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage deletion "; } totalErrors = totalErrors + results[1]; Logger.print("start regenerating invoices"); results = zApiClient.alterInvoices(newUsageCollection, "generate"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice generation "; } totalErrors = totalErrors + results[1]; Logger.print("start deleting old invoices"); results = zApiClient.alterInvoices(newUsageCollection, "delete"); if (results[1] != 0) { emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice deletion "; } totalErrors = totalErrors + results[1]; // Create the attachment EmailAttachment attachment = new EmailAttachment(); if (totalErrors > 0) { String logFileName = AppParamManager.OUTPUT_FOLDER_LOCATION + File.separator + "runtime_log_" + AppParamManager.OUTPUT_FILE_POSTFIX + ".txt"; attachment.setPath(logFileName); attachment.setDisposition(EmailAttachment.ATTACHMENT); attachment.setDescription("System Log"); attachment.setName("System Log"); } MultiPartEmail email = new MultiPartEmail(); email.setSmtpPort(587); email.setAuthenticator( new DefaultAuthenticator(AppParamManager.EMAIL_ADDRESS, AppParamManager.EMAIL_PASSWORD)); email.setDebug(false); email.setHostName("smtp.gmail.com"); email.setFrom("zuora@gmail.com"); if (totalErrors > 0) { email.setSubject("Base Calc Processor Finished with Errors"); email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } else { email.setSubject("Base Calc Processor Finished Successfully"); emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice "; email.setMsg("The base calc processing has finished " + emailmsg + "records successfully."); } email.setTLS(true); email.addTo(AppParamManager.RECIPIENT_ADDRESS); if (totalErrors > 0) { email.attach(attachment); } email.send(); System.out.println("Mail sent!"); if (hasArgs) { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'completed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } } catch (Exception e) { Logger.print("Failure, gettingFile."); Logger.print("Error getting the export file: " + e.getMessage()); //System.out.println("Error getting the export file: "+e.getMessage()); try { Connection conn = AppParamManager.getConnection(); Statement stmt = conn.createStatement(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); java.util.Date date = new Date(); stmt.executeUpdate("UPDATE TASK SET STATUS = 'failed', END_TIME = '" + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID); Utility.saveLogToDB(conn); conn.close(); } catch (Exception e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } } else { Logger.print("No tasks in wait status"); } }