Search in sources :

Example 21 with ConnectionFactory

use of org.vcell.db.ConnectionFactory in project vcell by virtualcell.

the class DBBackupAndClean method importOp.

private static void importOp(String[] args) {
    if (args.length != 7) {
        usageExit();
    }
    String importServerName = args[0];
    final String dumpFileHostPrefix = args[1];
    String vcellSchema = args[2];
    String password = args[3];
    String importDBSrvcName = args[4];
    File workingDir = new File(args[5]);
    File dumpFilesourceDir = new File(args[6]);
    String baseFileName = OP_IMPORT + "_" + createBaseFileName(importServerName, importDBSrvcName, vcellSchema);
    ;
    StringBuffer logStringBuffer = new StringBuffer();
    ConnectionFactory connectionFactory = null;
    Connection con = null;
    try {
        if (dumpFileHostPrefix.indexOf('.') != -1) {
            throw new Exception("Not expecting .(dot) in 'dumpFileHostPrefix'");
        }
        if (!workingDir.exists()) {
            throw new Exception("Working directory" + workingDir.getAbsolutePath() + " does not exist");
        }
        if (!dumpFilesourceDir.exists()) {
            throw new Exception("Export directory" + dumpFilesourceDir.getAbsolutePath() + " does not exist");
        }
        // Executable exec = new Executable(new String[] {"hostname"});
        // exec.start();
        // String localHostName = exec.getStdoutString().trim();
        // String inetLocalHost = InetAddress.getLocalHost().getHostName();
        // InetAddress[] inet0 = InetAddress.getAllByName(inetLocalHost);
        // InetAddress[] inet1 = InetAddress.getAllByName(dumpFileHostName);
        File[] oracleDumpFiles = dumpFilesourceDir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname.getName().startsWith(dumpFileHostPrefix + "_") && pathname.getName().endsWith(".dmp");
            }
        });
        Arrays.sort(oracleDumpFiles, new Comparator<File>() {

            @Override
            public int compare(File o1, File o2) {
                if (o1.lastModified() > o2.lastModified()) {
                    return -1;
                } else if (o1.lastModified() < o2.lastModified()) {
                    return 1;
                }
                return 0;
            }
        });
        if (oracleDumpFiles == null || oracleDumpFiles.length == 0) {
            throw new Exception("No dump files found to import");
        }
        // for (int i = 0; i < oracleDumpFiles.length; i++) {
        // String datePart = new SimpleDateFormat("MM/dd/yyyy HH_mm_ss").format(oracleDumpFiles[i].lastModified());
        // System.out.println(oracleDumpFiles[i].getName()+" "+oracleDumpFiles[i].lastModified()+" "+datePart);
        // }
        File latestDump = oracleDumpFiles[0];
        // sanity check
        // long latestDumpDate = latestDump.lastModified();
        // Calendar.getInstance().getTimeInMillis();
        long timediff = Calendar.getInstance().getTimeInMillis() - latestDump.lastModified();
        if (timediff <= 0) {
            throw new Exception("Expecting dump time to be earlier than current time");
        }
        if (timediff > (1000 * 60 * 60 * 48)) {
            throw new Exception("Not expecting very old dump");
        }
        final String beginWith = dumpFileHostPrefix.toLowerCase() + "_";
        if (!latestDump.getName().toLowerCase().startsWith(beginWith)) {
            throw new Exception("Expecting latestdump found name to begin with " + beginWith);
        }
        // dumpCopy = new File(workingDir,oracleDumpFiles[0].getName());
        // if(dumpCopy.exists()){
        // dumpCopy = null;
        // throw new Exception("dumpCopy already exists");
        // }
        System.out.println(/*" inetLocalHost="+inetLocalHost+*/
        "importServerName=" + importServerName + " importSrvcName=" + importDBSrvcName + " dumpFileHostName=" + dumpFileHostPrefix + " source=" + latestDump.getAbsolutePath());
        // BeanUtils.copyFileChannel(oracleDumpFiles[0], dumpCopy, true);
        // jdbc:oracle:<drivertype>:<username/password>@<database>
        // <database> = <host>:<port>:<SID>
        String url = "jdbc:oracle:thin:" + "system" + "/" + password + "@//" + importServerName + ":1521/" + importDBSrvcName;
        System.out.println(url);
        String dbDriverName = PropertyLoader.getRequiredProperty(PropertyLoader.dbDriverName);
        connectionFactory = DatabaseService.getInstance().createConnectionFactory(dbDriverName, url, "system", password);
        con = connectionFactory.getConnection(new Object());
        con.setAutoCommit(false);
        boolean bHasVCellUser = false;
        final String USERNAME = "username";
        String sql = "select " + USERNAME + " from dba_users where " + USERNAME + "='VCELL'";
        Statement stmt = null;
        stmt = con.createStatement();
        ResultSet rset = stmt.executeQuery(sql);
        while (rset.next()) {
            if (rset.getString(USERNAME).equals("VCELL")) {
                bHasVCellUser = true;
                break;
            }
        }
        rset.close();
        stmt.close();
        final String HOST_NAME = "host_name";
        sql = "select " + HOST_NAME + " from v$instance";
        stmt = con.createStatement();
        rset = stmt.executeQuery(sql);
        rset.next();
        String host_name = rset.getString(HOST_NAME);
        if (host_name.indexOf('.') != -1) {
            throw new Exception("Not expecting .(dot) in host_name");
        }
        if (host_name.toLowerCase().contains("dbs6")) {
            throw new Exception("Not expecting import host to be 'dbs6', hardcoded to disallow");
        }
        if (!importServerName.toLowerCase().equals(host_name.toLowerCase())) {
            throw new Exception("Expecting 'importServerName'=" + importServerName + " to match instance 'host_name'=" + host_name);
        }
        System.out.println("dumpFileHostPrefix=" + dumpFileHostPrefix + " instance host_name=" + host_name);
        if (host_name.toLowerCase().equals(dumpFileHostPrefix.toLowerCase())) {
            throw new Exception("Not expecting import host and dumpFileHostPrefix to be same");
        }
        rset.close();
        stmt.close();
        if (bHasVCellUser) {
            sql = "drop user VCELL cascade";
            logStringBuffer.append(sql + "\n");
            executeUpdate(con, sql, logStringBuffer);
            sql = "CREATE USER vcell PROFILE \"DEFAULT\" IDENTIFIED BY \"" + password + "\" DEFAULT TABLESPACE \"USERS\" TEMPORARY TABLESPACE \"TEMP\" ACCOUNT UNLOCK";
            executeUpdate(con, sql, logStringBuffer);
            executeUpdate(con, "GRANT UNLIMITED TABLESPACE TO vcell", logStringBuffer);
            executeUpdate(con, "GRANT \"CONNECT\" TO vcell", logStringBuffer);
            executeUpdate(con, "GRANT \"RESOURCE\" TO vcell", logStringBuffer);
            executeUpdate(con, "ALTER USER vcell DEFAULT ROLE  ALL", logStringBuffer);
        }
        final String importCommandWithPassword = createImportcommand(vcellSchema, password, importServerName, importDBSrvcName, latestDump);
        System.out.println(importCommandWithPassword);
        ProcessInfo exportProcessInfo = spawnProcess(importCommandWithPassword);
        String combinedExportOutput = combineStreamStrings(exportProcessInfo.normalOutput, exportProcessInfo.errorOutput);
        if (exportProcessInfo.normalOutput.getReaderException() != null || exportProcessInfo.errorOutput.getReaderException() != null) {
            throw new Exception("Error in script StreamRead:\r\n" + combinedExportOutput);
        }
        final String exportCommandWithoutPassword = createImportcommand(vcellSchema, null, importServerName, importDBSrvcName, latestDump);
        if (exportProcessInfo.returnCode != 0) {
            writeFile(workingDir, baseFileName, "Export Error: (return code=" + exportProcessInfo.returnCode + ")\r\n" + exportCommandWithoutPassword + "\r\n" + combinedExportOutput + "\r\nLogInfo\r\n" + logStringBuffer.toString(), true, null);
        } else {
            writeFile(workingDir, baseFileName, "Export output:\r\n" + exportCommandWithoutPassword + "\r\n" + combinedExportOutput + "\r\nLogInfo\r\n" + logStringBuffer.toString(), false, null);
        }
    } catch (Exception e) {
        e.printStackTrace();
        writeFile(workingDir, baseFileName, "Script Error:\r\n" + e.getClass().getName() + " " + e.getMessage() + "\r\nLogInfo\r\n" + logStringBuffer.toString(), true, null);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
                logStringBuffer.append("\n" + e.getClass().getName() + "\n" + e.getMessage());
            }
        }
        if (connectionFactory != null) {
            try {
                connectionFactory.close();
            } catch (Exception e) {
                logStringBuffer.append("\n" + e.getClass().getName() + "\n" + e.getMessage());
            }
        }
    }
}
Also used : Statement(java.sql.Statement) Connection(java.sql.Connection) SQLException(java.sql.SQLException) IOException(java.io.IOException) ConnectionFactory(org.vcell.db.ConnectionFactory) ResultSet(java.sql.ResultSet) FileFilter(java.io.FileFilter) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Aggregations

ConnectionFactory (org.vcell.db.ConnectionFactory)21 KeyFactory (org.vcell.db.KeyFactory)13 File (java.io.File)8 SQLException (java.sql.SQLException)7 DatabaseServerImpl (cbit.vcell.modeldb.DatabaseServerImpl)4 IOException (java.io.IOException)4 Connection (java.sql.Connection)4 VCMessagingService (cbit.vcell.message.VCMessagingService)3 AdminDBTopLevel (cbit.vcell.modeldb.AdminDBTopLevel)3 ZipFile (java.util.zip.ZipFile)3 ServerMessagingDelegate (cbit.vcell.message.server.ServerMessagingDelegate)2 ServiceInstanceStatus (cbit.vcell.message.server.ServiceInstanceStatus)2 RemoteProxyVCellConnectionFactory (cbit.vcell.message.server.bootstrap.client.RemoteProxyVCellConnectionFactory)2 LocalAdminDbServer (cbit.vcell.modeldb.LocalAdminDbServer)2 PropertyLoader (cbit.vcell.resource.PropertyLoader)2 AdminDatabaseServer (cbit.vcell.server.AdminDatabaseServer)2 FileFilter (java.io.FileFilter)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 JFrame (javax.swing.JFrame)2