Example usage for java.sql Statement executeUpdate

List of usage examples for java.sql Statement executeUpdate

Introduction

In this page you can find the example usage for java.sql Statement executeUpdate.

Prototype

int executeUpdate(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

Usage

From source file:my.yelp.populate.java

public static void main(String[] args)
        throws FileNotFoundException, ParseException, IOException, java.text.ParseException {
    try {/*from  w  w w  .java2s . c  o m*/

        DbConnection A1 = new DbConnection();
        Connection con = A1.getConnection();

        JSONParser jsonParser;
        jsonParser = new JSONParser();

        Object obj1 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_user.json"));
        Object obj2 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_business.json"));
        Object obj3 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_review.json"));
        Object obj4 = jsonParser.parse(new FileReader("C:\\Users\\Sanjay Desai\\Desktop\\yelp_checkin.json"));

        JSONArray jsonArray1;
        jsonArray1 = (JSONArray) obj1;

        JSONArray jsonArray2;
        jsonArray2 = (JSONArray) obj2;

        JSONArray jsonArray3;
        jsonArray3 = (JSONArray) obj3;

        JSONArray jsonArray4;
        jsonArray4 = (JSONArray) obj4;

        // yelp_user
        String yelping_since, name1, user_id, type1;
        Long review_count1, fans;
        Double average_stars;
        Statement stmt;

        stmt = con.createStatement();
        stmt.executeUpdate("Delete from N_User");

        for (int i = 0; i < (jsonArray1.size()); i++)

        {
            JSONObject jsonObject = (JSONObject) jsonArray1.get(i);
            yelping_since = (String) jsonObject.get("yelping_since") + "-01";

            JSONArray friends = (JSONArray) jsonObject.get("friends");
            int friends_size = friends.size();

            review_count1 = (Long) jsonObject.get("review_count");
            name1 = (String) jsonObject.get("name");
            user_id = (String) jsonObject.get("user_id");
            fans = (Long) jsonObject.get("fans");
            average_stars = (Double) jsonObject.get("average_stars");
            type1 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt1 = con.prepareStatement(
                    "Insert INTO N_User(yelping_since,friends_size,review_count,name,user_id,fans,average_stars,type) VALUES(?,?,?,?,?,?,?,?)")) {

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(yelping_since);

                pstmt1.setDate(1, new java.sql.Date(myDate.getTime()));
                pstmt1.setInt(2, friends_size);
                pstmt1.setLong(3, review_count1);
                pstmt1.setString(4, name1);
                pstmt1.setString(5, user_id);
                pstmt1.setLong(6, fans);
                pstmt1.setDouble(7, average_stars);
                pstmt1.setString(8, type1);
                pstmt1.executeUpdate();
            } catch (java.text.ParseException ex) {
                Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //yelp_business

        String business_id, address, city, state, name, type_business;

        Double stars;

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray2.get(i);
            business_id = (String) jsonObject.get("business_id");
            address = (String) jsonObject.get("full_address");
            city = (String) jsonObject.get("city");
            state = (String) jsonObject.get("state");
            name = (String) jsonObject.get("name");
            stars = (Double) jsonObject.get("stars");
            type_business = (String) jsonObject.get("type");

            try (PreparedStatement pstmt2 = con.prepareStatement(
                    "Insert INTO N_Business(business_id,address,city,state,name,stars,type_business) VALUES(?,?,?,?,?,?,?)")) {
                pstmt2.setString(1, business_id);
                pstmt2.setString(2, address);
                pstmt2.setString(3, city);
                pstmt2.setString(4, state);
                pstmt2.setString(5, name);
                pstmt2.setDouble(6, stars);
                pstmt2.setString(7, type_business);
                pstmt2.executeUpdate();
                pstmt2.close();
            }

        }

        //Category Table
        String[] categories = { "Active Life", "Arts & Entertainment", "Automotive", "Car Rental", "Cafes",
                "Beauty & Spas", "Convenience Stores", "Dentists", "Doctors", "Drugstores", "Department Stores",
                "Education", "Event Planning & Services", "Flowers & Gifts", "Food", "Health & Medical",
                "Home Services", "Home & Garden", "Hospitals", "Hotels & travel", "Hardware stores", "Grocery",
                "Medical Centers", "Nurseries & Gardening", "Nightlife", "Restaurants", "Shopping",
                "Transportation" };

        JSONArray category;
        String[] individual_category = new String[100];
        int count = 0, flag = 0, m = 0, n = 0;
        String[] business_category = new String[50];
        String[] subcategory = new String[50];

        for (int i = 0; i < jsonArray2.size(); i++) {
            JSONObject jsonObject3 = (JSONObject) jsonArray2.get(i);
            String business_id2 = (String) jsonObject3.get("business_id");
            category = (JSONArray) jsonObject3.get("categories");
            for (int j = 0; j < category.size(); j++) {
                individual_category[j] = (String) category.get(j);
                count = count + 1;
            }
            for (int k = 0; k < count; k++) {
                for (String categorie : categories) {

                    if (individual_category[k].equals(categorie)) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 1) {
                    business_category[m] = individual_category[k];
                    m = m + 1;
                    flag = 0;
                } else {
                    subcategory[n] = individual_category[k];
                    n = n + 1;
                }
            }
            for (int p = 0; p < m; p++) {
                for (int q = 0; q < n; q++) {
                    try (PreparedStatement pstmt3 = con.prepareStatement(
                            "INSERT INTO N_Category(business_id,category,subcategory) VALUES(?,?,?)")) {
                        pstmt3.setString(1, business_id2);
                        pstmt3.setString(2, business_category[p]);
                        pstmt3.setString(3, subcategory[q]);
                        pstmt3.executeUpdate();

                    }
                }
            }
            count = 0;
            m = 0;
            n = 0;
        }

        //yelp_review

        String user_id3, review_id, type3, business_id3, text, text1, review_date;
        Long stars3;
        int votes = 0;
        Integer no_votes;

        JSONObject votes_info;
        Set<String> keys;

        for (int i = 0; i < jsonArray3.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray3.get(i);

            votes_info = (JSONObject) jsonObject.get("votes");
            keys = votes_info.keySet();
            for (String r_key : keys) {
                votes = (int) (votes + (Long) votes_info.get(r_key));
            }
            no_votes = toIntExact(votes);
            user_id3 = (String) jsonObject.get("user_id");

            review_id = (String) jsonObject.get("review_id");
            business_id3 = (String) jsonObject.get("business_id");
            review_date = (String) jsonObject.get("date");
            text1 = (String) jsonObject.get("text");
            text = text1.substring(0, Math.min(1000, text1.length()));
            stars3 = (Long) jsonObject.get("stars");
            type3 = (String) jsonObject.get("type");

            try (PreparedStatement pstmt4 = con.prepareStatement(
                    "Insert INTO N_Review(no_votes,user_id,review_id,business_id,review_date,text,stars,type) VALUES(?,?,?,?,?,?,?,?)")) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date myDate = format.parse(review_date);

                pstmt4.setInt(1, no_votes);
                pstmt4.setString(2, user_id3);
                pstmt4.setString(3, review_id);
                pstmt4.setString(4, business_id3);
                pstmt4.setDate(5, new java.sql.Date(myDate.getTime()));
                pstmt4.setString(6, text);
                pstmt4.setLong(7, stars3);
                pstmt4.setString(8, type3);
                pstmt4.executeUpdate();
                pstmt4.close();
            }

        }

        //Checkin_Info
        JSONObject checkin_info;
        String business_id4;
        Long check_in_count;
        Set<String> keys1;
        String[] timing = new String[10];
        int n1 = 0, time, hour;

        //Inserting into checkin_info
        for (int i = 0; i < jsonArray4.size(); i++) {
            JSONObject jsonObject4 = (JSONObject) jsonArray4.get(i);
            checkin_info = (JSONObject) jsonObject4.get("checkin_info");
            business_id4 = (String) jsonObject4.get("business_id");
            keys1 = checkin_info.keySet();

            for (String key : keys1) {
                check_in_count = (Long) checkin_info.get(key);
                for (String x : key.split("-")) {
                    timing[n1] = x;
                    n1 = n1 + 1;
                }
                n1 = 0;
                hour = Integer.parseInt(timing[0]);
                time = Integer.parseInt(timing[1]);

                try (PreparedStatement pstmt5 = con.prepareStatement(
                        "INSERT INTO check_info(business_id,hour,day,check_in_count)VALUES(?,?,?,?)")) {
                    pstmt5.setString(1, business_id4);
                    pstmt5.setInt(2, hour);
                    pstmt5.setInt(3, time);
                    pstmt5.setLong(4, check_in_count);
                    pstmt5.executeUpdate();
                }
            }

        }

        con.close();

    } catch (SQLException ex) {
        Logger.getLogger(populate.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//ww  w .jav a2 s.c o m
    Statement stmt = null;
    try {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

        // Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

From source file:SimpleProgramToAccessOracleDatabase.java

public static void main(String[] args) throws SQLException {
    Connection conn = null; // connection object
    Statement stmt = null; // statement object
    ResultSet rs = null; // result set object
    try {//from w  ww.ja  v a 2  s. c om
        conn = getConnection(); // without Connection, can not do much
        // create a statement: This object will be used for executing
        // a static SQL statement and returning the results it produces.
        stmt = conn.createStatement();
        // start a transaction
        conn.setAutoCommit(false);

        // create a table called cats_tricks
        stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))");
        // insert two new records to the cats_tricks table
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')");
        stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')");

        // commit the transaction
        conn.commit();

        // set auto commit to true (from now on every single
        // statement will be treated as a single transaction
        conn.setAutoCommit(true);

        // get all of the the records from the cats_tricks table
        rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks");

        // iterate the result set and get one row at a time
        while (rs.next()) {
            String name = rs.getString(1); // 1st column in query
            String trick = rs.getString(2); // 2nd column in query
            System.out.println("name=" + name);
            System.out.println("trick=" + trick);
            System.out.println("==========");
        }
    } catch (ClassNotFoundException ce) {
        // if the driver class not found, then we will be here
        System.out.println(ce.getMessage());
    } catch (SQLException e) {
        // something went wrong, we are handling the exception here
        if (conn != null) {
            conn.rollback();
            conn.setAutoCommit(true);
        }

        System.out.println("--- SQLException caught ---");
        // iterate and get all of the errors as much as possible.
        while (e != null) {
            System.out.println("Message   : " + e.getMessage());
            System.out.println("SQLState  : " + e.getSQLState());
            System.out.println("ErrorCode : " + e.getErrorCode());
            System.out.println("---");
            e = e.getNextException();
        }
    } finally { // close db resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }

    }
}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//w w  w  . j a  v  a  2 s  .c om
    Statement stmt = 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);

        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // STEP 5: Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // STEP 6: Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String user = "root";
    String pass = "root";

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial", user, pass);
    Statement st = con.createStatement();
    String table = "CREATE TABLE java_DataTypes2(typ_boolean BOOL, "
            + "typ_byte          TINYINT, typ_short         SMALLINT, "
            + "typ_int           INTEGER, typ_long          BIGINT, "
            + "typ_float         FLOAT,   typ_double        DOUBLE PRECISION, "
            + "typ_bigdecimal    DECIMAL(13,0), typ_string        VARCHAR(254), "
            + "typ_date          DATE,    typ_time          TIME, " + "typ_timestamp     TIMESTAMP, "
            + "typ_asciistream   TEXT,    typ_binarystream  LONGBLOB, " + "typ_blob          BLOB)";

    st.executeUpdate(table);
    con.close();//  w w w. j  a v  a 2  s .com
}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//from w w w  . ja v a  2 s  . c o m
    Statement stmt = null;
    boolean executeResult;
    try {
        String driver = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driver).newInstance();
        System.out.println("Connecting to database...");
        String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
        conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd");
        stmt = conn.createStatement();
        conn.setAutoCommit(false);
        if (!conn.getAutoCommit())
            System.out.println("Auto-commit is set to false");
        String sql = "INSERT INTO Location VALUES(715,'Houston')";
        stmt.executeUpdate(sql);
        sql = "INSERT INTO Employees VALUES" + "(8,'K','4351',{d '2000-02-00'},715)";
        stmt.executeUpdate(sql);
        conn.commit();
    } catch (SQLException se) {
        String msg = se.getMessage();
        msg = "SQLException occured with message: " + msg;
        System.out.println(msg);
        System.out.println("Starting rollback operations...");
        try {
            conn.rollback();
        } catch (SQLException se2) {
            se2.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:CreateUDTs.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from  w  w w.  j  a v a  2  s.  c  om*/
    Statement stmt;

    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:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;//from  w  w  w .  jav a 2s  . c  o m
    String sqlpath = "", host = "", port = "3306", username = "", password = "", database = "";
    Boolean query = false;
    Option option_sql = Option.builder("s").argName("sql").hasArg()
            .desc("Path to a file containing a valid MySQL sql statement").build();
    Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname")
            .build();
    Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build();
    Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username")
            .build();
    Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password")
            .build();
    Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name")
            .build();
    Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build();
    Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_sql);
    options.addOption(option_hostname);
    options.addOption(option_port);
    options.addOption(option_username);
    options.addOption(option_password);
    options.addOption(option_dbname);
    options.addOption(option_query);
    options.addOption(option_help);

    try {
        commandLine = parser.parse(options, params);
    } catch (MissingOptionException e) {
        help(options);
    } catch (MissingArgumentException e) {
        help(options);
    } catch (ParseException e) {
        System.out.println(e);
    }

    if (commandLine.hasOption("w") || params.length == 0) {
        help(options);
    }

    if (commandLine.hasOption("s")) {
        sqlpath = commandLine.getOptionValue("s");
    } else {
        System.out.println("Missing path to a SQL statement file");
        help(options);
    }
    if (commandLine.hasOption("h")) {
        host = commandLine.getOptionValue("h");
    } else {
        System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)");
        help(options);
    }
    if (commandLine.hasOption("n")) {
        port = commandLine.getOptionValue("n");
    } else {
        System.out.println("Missing ClearDB Port Value.  Defaulting to 3306");
    }
    if (commandLine.hasOption("u")) {
        username = commandLine.getOptionValue("u");
    } else {
        System.out.println("Missing ClearDB Username");
        help(options);
    }
    if (commandLine.hasOption("p")) {
        password = commandLine.getOptionValue("p");
    } else {
        System.out.println("Missing ClearDB Password");
        help(options);
    }
    if (commandLine.hasOption("d")) {
        database = commandLine.getOptionValue("d");
    } else {
        System.out.println("Missing ClearDB Database Name");
        help(options);
    }

    if (commandLine.hasOption("query")) {
        query = true;
    }

    String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port)
            .append("/").append(database).append("?reconnect=true").toString();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }

    try {
        Connection con = DriverManager.getConnection(connectionURL, username, password);
        Statement stmt = con.createStatement();
        if (query) {
            System.out.println("Querying target MySQL DB ...");
            ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset()));
            while (rs.next())
                System.out.println(rs.getInt("emp_no") + "  " + rs.getDate("birth_date") + "  "
                        + rs.getString("first_name") + "  " + rs.getString("last_name") + "  "
                        + rs.getString("gender") + "  " + rs.getDate("hire_date"));
        } else {
            System.out.println("Updating target MySQL DB ...");
            int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset()));
            System.out.println(result);
        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    String driverName = "com.jnetdirect.jsql.JSQLDriver";
    Class.forName(driverName);/*from w  w w  .  j  a v a2s  .  c  o  m*/

    String serverName = "127.0.0.1";
    String portNumber = "1433";
    String mydatabase = serverName + ":" + portNumber;
    String url = "jdbc:JSQLConnect://" + mydatabase;
    String username = "username";
    String password = "password";

    Connection connection = DriverManager.getConnection(url, username, password);

    Statement stmt = connection.createStatement();

    String sql = "CREATE TABLE mysql_all_table(" + "col_boolean       BOOL, " // boolean
            + "col_byte          TINYINT, " // byte
            + "col_short         SMALLINT, " // short
            + "col_int           INTEGER, " // int
            + "col_long          BIGINT, " // long
            + "col_float         FLOAT, " // float
            + "col_double        DOUBLE PRECISION, " // double
            + "col_bigdecimal    DECIMAL(13,0), " // BigDecimal
            + "col_string        VARCHAR(254), " // String
            + "col_date          DATE, " // Date
            + "col_time          TIME, " // Time
            + "col_timestamp     TIMESTAMP, " // Timestamp
            + "col_asciistream   TEXT, " // AsciiStream (< 2^16 bytes)
            + "col_binarystream  LONGBLOB, " // BinaryStream (< 2^32 bytes)
            + "col_blob          BLOB)"; // Blob (< 2^16 bytes)

    stmt.executeUpdate(sql);

}

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  2s. c o  m
    }
    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");
    }
}