SeunMatt / mysql-backup4j

mysql-backup4j is a library for programmatically exporting mysql databases and sending the zipped dump to email, Amazon S3, Google Drive or any other cloud storage of choice
MIT License
124 stars 71 forks source link

How to upload on any cloud? #8

Closed ypkkhatri closed 4 years ago

ypkkhatri commented 5 years ago

Can you please show the information or code to upload on any cloud? Because in your code its not mentioned.

SeunMatt commented 4 years ago

Hello @ypkkhatri

Here's an example snippet from one of my projects.


public boolean backup() {

    Properties properties = new Properties();
    properties.setProperty(MysqlExportService.JDBC_CONNECTION_STRING, dataSourceProperties.getUrl());
    properties.setProperty(MysqlExportService.DB_USERNAME, dataSourceProperties.getUsername());
    properties.setProperty(MysqlExportService.DB_PASSWORD, dataSourceProperties.getPassword());

    properties.setProperty(MysqlExportService.PRESERVE_GENERATED_ZIP, "true");
    properties.setProperty(MysqlExportService.ADD_IF_NOT_EXISTS, "true");

    String basePath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
    File tempFile = new File(basePath, "/backup");

    properties.setProperty(MysqlExportService.TEMP_DIR, tempFile.getPath());
    MysqlExportService mySqlExportService = new MysqlExportService(properties);
    try {
        mySqlExportService.export();
        storageService.storeBackupFile(mySqlExportService.getGeneratedZipFile());
        return true;
    } catch (Exception e) {
        logger.error("Error Occurred in DatabaseBackupService: " + e.getLocalizedMessage());
        e.printStackTrace();
        return false;
    } finally {
        mySqlExportService.clearTempFiles(false);
    }
}

I configured the properties PRESERVE_GENERATED_ZIP to true. What this means is that when I call the mySqlExportService.export(); method, the generated zip file will be preserved and I can access it as java.io.File object.

Which is exactly what I did here storageService.storeBackupFile(mySqlExportService.getGeneratedZipFile());

In my case, the StorageService makes use of the AWS S3 SDK to upload the generated zip file to an S3 bucket.

Here is the implementation of that storeBackupFile() method:


public void storeBackupFile(File file) {

    if(!Objects.isNull(file)) {
        String newFileName = RandomStringUtils.randomAlphanumeric(5) + "_" + file.getName();
        AmazonS3 s3 = s3Factory();
        String bucketName = storageProperties.getAwsS3BucketName() + "/backup";

        Try.of(() -> s3.putObject(
                new PutObjectRequest(bucketName, newFileName, new FileInputStream(file), null)
                        .withCannedAcl(CannedAccessControlList.PublicRead)))
                .onFailure(e -> logger.error("Error Storing Object to S3: " + e.getLocalizedMessage())).get();
    }
}

I hope this helps you.

Cheers

ypkkhatri commented 4 years ago

@SeunMatt Thanks, for example,.