com.mkmeier.quickerbooks.LoadAccounts.java Source code

Java tutorial

Introduction

Here is the source code for com.mkmeier.quickerbooks.LoadAccounts.java

Source

/*
 * The MIT License
 *
 * Copyright 2014 Marcus.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.mkmeier.quickerbooks;

import com.google.gson.Gson;
import com.mkmeier.mkm_core.database.DatabaseConnection;
import com.mkmeier.quickerbooks.iif.IifData;
import com.mkmeier.quickerbooks.parser.IifParser;
import com.mkmeier.mkm_core.utils.ServletFileUploader;
import com.mkmeier.quickerbooks.exception.IifException;
import com.mkmeier.quickerbooks.parser.AccountParser;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Forwards the request to a form for the user to upload a file. If the request contains a form
 * submission, the file is uploaded and the account data is parsed.
 *
 * @author Marcus
 */
@WebServlet(name = "LoadAccounts", urlPatterns = { "/LoadAccounts" })
public class LoadAccounts extends HttpServlet {

    private static Logger logger = LogManager.getLogger(LoadAccounts.class);

    //    @Override
    //    public void init(){
    //   logger.error("Loading Properties");
    //   InputStream propInputStream = getClass().getResourceAsStream("QuickerBooks.properties");
    //   
    //   Properties properties = new Properties();
    //   try {
    //       properties.load(propInputStream);
    //       logger.error("Properties Loaded");
    //   } catch (IOException ex) {
    //       ex.printStackTrace();
    //   }
    //    }
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //If form hasn't been submitted, load the form.
        if (!ServletFileUpload.isMultipartContent(request)) {
            redirect(request, response);
            return;
        }

        //Extract files from form submission.
        ServletFileUploader up = new ServletFileUploader();
        up.parseRequest(request);

        File file = up.getFileMap().get("accountsIIF");

        //Parse the file
        try {
            IifParser parser = new IifParser(file);
            IifData iifData = parser.parse();

            AccountParser ap = new AccountParser(iifData);
            List<QbAccount> accounts = ap.parse();

            saveAccounts(accounts);
            response.sendRedirect("/QuickerBooks");
        } catch (IifException ex) {
            logger.error("Parsing Error", ex);
        }
    }

    /**
     * Redirect to the Load Accounts form.
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void redirect(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher rd = request.getRequestDispatcher("LoadAccounts.jsp");
        rd.forward(request, response);
    }

    private void saveAccounts(List<QbAccount> accounts) {
        String host = "jdbc:mysql://mysql.mdmeier.com";
        String db = "quickerbooks";
        String user = "quickerbooks";
        String password = "quickerbooks";

        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DatabaseConnection.getDatabaseConnection(host, db, user, password);

            //Clear table of existing data
            String sql = "TRUNCATE TABLE  account";
            stmt = conn.prepareStatement(sql);
            stmt.executeQuery();

            sql = "INSERT INTO account (" + "name, " + "ref_num, " + "timestamp, " + "acct_type, " + "oba_amount, "
                    + "description, " + "acct_num, " + "scd, " + "bank_num, " + "extra, " + "hidden, "
                    + "del_count, " + "use_id) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            stmt = conn.prepareStatement(sql);

            for (QbAccount acct : accounts) {
                stmt.setString(1, acct.getName());
                stmt.setInt(2, acct.getRefNum());
                stmt.setLong(3, acct.getTimeStamp());
                stmt.setString(4, acct.getAcctType());
                stmt.setBigDecimal(5, acct.getObaAmount());
                stmt.setString(6, acct.getDescription());
                stmt.setInt(7, acct.getAcctNum());
                stmt.setInt(8, acct.getScd());
                stmt.setString(9, acct.getBankNum());
                stmt.setString(10, acct.getExtra());
                stmt.setBoolean(11, acct.isHidden());
                stmt.setInt(12, acct.getDelCount());
                stmt.setBoolean(13, acct.isUseId());

                stmt.execute();
            }

        } catch (SQLException ex) {
            logger.error(ex);
        } finally {

            // Clean up connection.
            try {
                stmt.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

            try {
                conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}