001/**
002 * Copyright 2005-2015 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016/*
017 * To change this template, choose Tools | Templates
018 * and open the template in the editor.
019 */
020package org.kuali.rice.krad.devtools.maintainablexml;
021
022import java.sql.ResultSet;
023import java.sql.SQLException;
024import java.util.HashMap;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027import javax.sql.DataSource;
028import org.springframework.jdbc.core.JdbcTemplate;
029import org.springframework.jdbc.core.RowCallbackHandler;
030import org.springframework.jdbc.datasource.DriverManagerDataSource;
031
032/**
033 * Used to upgrade the maintenance document xml stored in krns_maint_doc_t.doc_cntnt
034 * to be able to still open and use any maintenance documents that were enroute at the time of an upgrade to Rice 2.0.
035 *
036 * @author Kuali Rice Team (rice.collab@kuali.org)
037 */
038
039public class FileConverter {
040
041    private JdbcTemplate jdbcTemplate;
042    private int totalDocs = 0;
043
044    /**
045     * Selects all the encrypted xml documents from krns_maint_doc_t, decrypts them, runs the rules to upgrade them,
046     * encrypt them and update krns_maint_doc_t with the upgraded xml.
047     *
048     * @param settingsMap - the settings
049     * @throws Exception
050     */
051    public void runFileConversion(HashMap settingsMap, final String runMode, final String fromRange,
052            final String toRange, final boolean hasRangeParameters) throws Exception {
053
054        final EncryptionService encryptService = new EncryptionService((String) settingsMap.get("encryption.key"));
055
056        String docSQL = "SELECT DOC_HDR_ID, DOC_CNTNT FROM krns_maint_doc_t ";
057
058        // If user entered range add the sql parameters and filter results because DOC_HDR_ID is a varchar field.
059        if (hasRangeParameters) {
060            docSQL = docSQL.concat(" WHERE DOC_HDR_ID >= '" + fromRange + "' AND DOC_HDR_ID <= '" + toRange + "'");
061        }
062        System.out.println("SQL to run:"  + docSQL);
063
064        jdbcTemplate = new JdbcTemplate(getDataSource(settingsMap));
065        jdbcTemplate.query(docSQL, new RowCallbackHandler() {
066
067            public void processRow(ResultSet rs) throws SQLException {
068                // Check that all docId's is in range
069                if (hasRangeParameters) {
070                    int docId = Integer.parseInt(rs.getString(1));
071                    if (docId >= Integer.parseInt(fromRange) && docId <= Integer.parseInt(toRange)) {
072                        processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
073                    }
074                } else {
075                    processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
076                }
077            }
078        });
079
080        System.out.println(totalDocs + " maintenance documents upgraded.");
081
082    }
083
084    /**
085     * Creates the data source from the settings map
086     *
087     * @param settingsMap - the settingMap containing the db connection settings
088     * @return the DataSource object
089     */
090    public static DataSource getDataSource(HashMap settingsMap) {
091        String driver;
092        if ("MySQL".equals(settingsMap.get("datasource.ojb.platform"))) {
093            driver = "com.mysql.jdbc.Driver";
094        } else if ("Oracle9i".equals(settingsMap.get("datasource.ojb.platform"))) {
095            driver = "oracle.jdbc.driver.OracleDriver";
096        } else {
097            driver = (String) settingsMap.get("datasource.driver.name");
098        }
099
100        DriverManagerDataSource dataSource = new DriverManagerDataSource();
101        dataSource.setDriverClassName(driver);
102        dataSource.setUrl((String) settingsMap.get("datasource.url"));
103        dataSource.setUsername((String) settingsMap.get("datasource.username"));
104        dataSource.setPassword((String) settingsMap.get("datasource.password"));
105        return dataSource;
106    }
107
108    /**
109     * Called for each row in the processRow method of the spring query. Upgrades the xml and update the
110     * krns_maint_doc_t table.
111     *
112     * @param docId - the document id string
113     * @param docCntnt - the old xml string
114     * @param encryptServ - the encryption service used to encrypt/decrypt the xml
115     */
116    public void processDocumentRow(String docId, String docCntnt, EncryptionService encryptServ, String runMode) {
117        System.out.println(docId);
118        try {
119            String oldXml = docCntnt;
120            if (encryptServ.isEnabled()) {
121                oldXml = encryptServ.decrypt(docCntnt);
122            }
123            if ("2".equals(runMode)) {
124                System.out.println("------ ORIGINAL DOC XML --------");
125                System.out.println(oldXml);
126                System.out.println("--------------------------------");
127            }
128
129            MaintainableXMLConversionServiceImpl maintainableXMLConversionServiceImpl = new MaintainableXMLConversionServiceImpl();
130            String newXML = maintainableXMLConversionServiceImpl.transformMaintainableXML(oldXml);
131
132            if ("2".equals(runMode)) {
133                System.out.println("******* UPGRADED DOC XML ********");
134                System.out.println(newXML);
135                System.out.println("*********************************\n");
136            }
137            if ("1".equals(runMode)) {
138                 if (encryptServ.isEnabled()) {
139                    jdbcTemplate.update("update krns_maint_doc_t set DOC_CNTNT = ? where DOC_HDR_ID = ?",
140                        new Object[]{encryptServ.encrypt(newXML), docId});
141                 } else {
142                     jdbcTemplate.update("update krns_maint_doc_t set DOC_CNTNT = ? where DOC_HDR_ID = ?",
143                             new Object[]{newXML, docId});
144                 }
145            }
146            totalDocs++;
147        } catch (Exception ex) {
148            Logger.getLogger(FileConverter.class.getName()).log(Level.SEVERE, null, ex);
149            System.exit(1);
150        }
151    }
152}