org.nocrala.tools.database.sentinel.plugin.TakeSnapshotOperation Maven / Gradle / Ivy
The newest version!
package org.nocrala.tools.database.sentinel.plugin;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import org.nocrala.tools.database.sentinel.BuildInformation;
import org.nocrala.tools.database.sentinel.Snapshot;
import org.nocrala.tools.database.sentinel.util.XUtil;
import org.nocrala.tools.database.tartarus.exception.ReaderException;
import org.nocrala.tools.database.tartarus.utils.JdbcUtil;
public class TakeSnapshotOperation {
private String alias = null;
private String driverclass = null;
private String url = null;
private String username = null;
private String password = null;
private String catalog = null;
private String schema = null;
private File snapshotfile = null;
public TakeSnapshotOperation(final String alias, final String driverclass, final String url, final String username,
final String password, final String catalog, final String schema, final File snapshotfile) {
this.alias = alias;
this.driverclass = driverclass;
this.url = url;
this.username = username;
this.password = password;
this.catalog = catalog;
this.schema = schema;
this.snapshotfile = snapshotfile;
}
public void execute(final Feedback feedback) throws Exception {
feedback.info("Sentinel " + BuildInformation.VERSION + " - build " + BuildInformation.BUILD_ID);
this.catalog = this.catalog == null || this.catalog.isEmpty() ? null : this.catalog;
this.schema = this.schema == null || this.schema.isEmpty() ? null : this.schema;
feedback.info("Inspecting live database (" + this.alias + ") at: " + this.url);
feedback.info(" ");
Connection conn = null;
try {
// 1. Connect to database
try {
conn = JdbcUtil.buildStandAloneConnection(this.driverclass, this.url, this.username, this.password, null);
} catch (ClassNotFoundException | SQLException e) {
throw new Exception("Could not connect to database: " + XUtil.renderThrowable(e));
}
// 2. Take the snapshot
Snapshot s;
try {
s = Snapshot.takeSnapshot(conn, this.catalog, this.schema, this.alias);
} catch (ReaderException | SQLException e) {
throw new Exception("Could not take database snapshot: " + XUtil.renderThrowable(e));
}
// 3. Store the snapshot into the destination file
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(this.snapshotfile))) {
s.writeTo(bos);
} catch (Throwable e) {
throw new Exception("Could not save snapshot: " + XUtil.renderThrowable(e));
}
// 4. Display snapshot's summary
s.renderHeader().stream().forEach(h -> feedback.info("" + h));
feedback.info(" ");
feedback.info("Saved to: " + this.snapshotfile.getPath());
feedback.info(" ");
} finally {
// 5. Close the database connection
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new Exception("Database error: " + XUtil.renderThrowable(e));
}
}
}
}
}