com.microsoft.azure.management.sql.SqlDatabase Java Examples

The following examples show how to use com.microsoft.azure.management.sql.SqlDatabase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AzureSQLDatabaseScanner.java    From clouditor with Apache License 2.0 6 votes vote down vote up
@Override
protected List<SqlDatabase> list() {
  var servers =
      new ArrayList<>(
          this.resourceGroup != null
              ? this.api.azure().sqlServers().listByResourceGroup(this.resourceGroup)
              : this.api.azure().sqlServers().list());

  List<SqlDatabase> databases = new ArrayList<>();

  for (var server : servers) {
    server
        .databases()
        .list()
        .forEach(
            database -> {
              // filter out master databases, since they are internal Azure structures
              if (!database.name().equals("master")) {
                databases.add(database);
              }
            });
  }

  return databases;
}
 
Example #2
Source File: Utils.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Prints information for the passed SQL Database.
 * @param database database to be printed
 */
public static void print(SqlDatabase database) {
    StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id())
            .append("Name: ").append(database.name())
            .append("\n\tResource group: ").append(database.resourceGroupName())
            .append("\n\tRegion: ").append(database.region())
            .append("\n\tSqlServer Name: ").append(database.sqlServerName())
            .append("\n\tEdition of SQL database: ").append(database.edition())
            .append("\n\tCollation of SQL database: ").append(database.collation())
            .append("\n\tCreation date of SQL database: ").append(database.creationDate())
            .append("\n\tIs data warehouse: ").append(database.isDataWarehouse())
            .append("\n\tCurrent service objective of SQL database: ").append(database.serviceLevelObjective())
            .append("\n\tId of current service objective of SQL database: ").append(database.currentServiceObjectiveId())
            .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes())
            .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation());

    System.out.println(builder.toString());
}
 
Example #3
Source File: RecommendedElasticPoolImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<SqlDatabase> listDatabasesAsync() {
    final RecommendedElasticPoolImpl self = this;
    return this.sqlServer.manager().inner().databases().listByRecommendedElasticPoolAsync(
        this.sqlServer.resourceGroupName(),
        this.sqlServer.name(),
        this.name())
        .flatMap(new Func1<List<DatabaseInner>, Observable<DatabaseInner>>() {
            @Override
            public Observable<DatabaseInner> call(List<DatabaseInner> databaseInners) {
                return Observable.from(databaseInners);
            }
        }).map(new Func1<DatabaseInner, SqlDatabase>() {
            @Override
            public SqlDatabase call(DatabaseInner databaseInner) {
                return new SqlDatabaseImpl(databaseInner.name(), self.sqlServer, databaseInner, self.manager());
            }
        });
}
 
Example #4
Source File: SqlDatabaseImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public void beforeGroupCreateOrUpdate() {
    if (this.importRequestInner != null && this.elasticPoolName() != null) {
        final SqlDatabaseImpl self = this;
        final String epName = this.elasticPoolName();
        this.addPostRunDependent(new FunctionalTaskItem() {
            @Override
            public Observable<Indexable> call(final Context context) {
                self.importRequestInner = null;
                self.withExistingElasticPool(epName);
                return self.createResourceAsync()
                    .flatMap(new Func1<SqlDatabase, Observable<Indexable>>() {
                        @Override
                        public Observable<Indexable> call(SqlDatabase sqlDatabase) {
                            return context.voidObservable();
                        }
                    });
            }
        });
    }
}
 
Example #5
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<SqlDatabase> listDatabasesAsync() {
    final SqlElasticPoolImpl self = this;
    return this.sqlServerManager.inner().databases()
        .listByElasticPoolAsync(self.resourceGroupName, self.sqlServerName, this.name())
        .flatMap(new Func1<List<DatabaseInner>, Observable<DatabaseInner>>() {
            @Override
            public Observable<DatabaseInner> call(List<DatabaseInner> databaseInners) {
                return Observable.from(databaseInners);
            }
        }).map(new Func1<DatabaseInner, SqlDatabase>() {
            @Override
            public SqlDatabase call(DatabaseInner databaseInner) {
                return new SqlDatabaseImpl(self.resourceGroupName, self.sqlServerName, self.sqlServerLocation, databaseInner.name(), databaseInner, self.sqlServerManager);
            }
        });
}
 
Example #6
Source File: RecommendedElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SqlDatabase> getDatabaseAsync(String databaseName) {
    final RecommendedElasticPoolImpl self = this;
    return this.sqlServer.manager().inner().databases().getByRecommendedElasticPoolAsync(
            this.sqlServer.resourceGroupName(),
            this.sqlServer.name(),
            this.name(),
            databaseName)
        .map(new Func1<DatabaseInner, SqlDatabase>() {
            @Override
            public SqlDatabase call(DatabaseInner databaseInner) {
                return new SqlDatabaseImpl(databaseInner.name(), self.sqlServer, databaseInner, self.manager());
            }
        });
}
 
Example #7
Source File: SqlSyncGroupImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlSyncGroupImpl withExistingSqlDatabase(SqlDatabase sqlDatabase) {
    this.resourceGroupName = sqlDatabase.resourceGroupName();
    this.sqlServerName = sqlDatabase.sqlServerName();
    this.sqlDatabaseName = sqlDatabase.name();
    return this;
}
 
Example #8
Source File: AzureSQLDatabaseScanner.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@Override
protected Asset transform(SqlDatabase database) throws ScanException {
  var asset = super.transform(database);

  enrich(asset, "transparentDataEncryption", database, SqlDatabase::getTransparentDataEncryption);

  enrich(
      asset,
      "auditingPolicy",
      database,
      x ->
          this.api
              .azure()
              .sqlServers()
              .manager()
              .inner()
              .databaseBlobAuditingPolicies()
              .get(database.resourceGroupName(), database.sqlServerName(), database.name()),
      DatabaseBlobAuditingPolicyInner::id,
      DatabaseBlobAuditingPolicyInner::name);

  enrichList(
      asset,
      "replicationLinks",
      database,
      x -> x.listReplicationLinks().values(),
      ReplicationLink::id,
      ReplicationLink::name);

  return asset;
}
 
Example #9
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SqlDatabase> listAsync() {
    if (sqlServer == null) {
        return null;
    }
    return this.listBySqlServerAsync(this.sqlServer.resourceGroupName(), this.sqlServer.name());
}
 
Example #10
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public List<SqlDatabase> list() {
    if (sqlServer == null) {
        return null;
    }
    return this.listBySqlServer(this.sqlServer.resourceGroupName(), this.sqlServer.name());
}
 
Example #11
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public List<SqlDatabase> listBySqlServer(SqlServer sqlServer) {
    List<SqlDatabase> firewallRuleSet = new ArrayList<>();
    if (sqlServer != null) {
        for (DatabaseInner inner : this.manager.inner().databases().listByServer(sqlServer.resourceGroupName(), sqlServer.name())) {
            firewallRuleSet.add(new SqlDatabaseImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager));
        }
    }
    return Collections.unmodifiableList(firewallRuleSet);
}
 
Example #12
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public List<SqlDatabase> listBySqlServer(String resourceGroupName, String sqlServerName) {
    List<SqlDatabase> databasesSet = new ArrayList<>();
    for (DatabaseInner inner : this.manager.inner().databases().listByServer(resourceGroupName, sqlServerName)) {
        databasesSet.add(new SqlDatabaseImpl(resourceGroupName, sqlServerName, inner.location(), inner.name(), inner, manager));
    }
    return Collections.unmodifiableList(databasesSet);
}
 
Example #13
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SqlDatabase> getByIdAsync(String id) {
    Objects.requireNonNull(id);
    return this.getBySqlServerAsync(ResourceUtils.groupFromResourceId(id),
        ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)),
        ResourceUtils.nameFromResourceId(id));
}
 
Example #14
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase getById(String id) {
    Objects.requireNonNull(id);
    return this.getBySqlServer(ResourceUtils.groupFromResourceId(id),
        ResourceUtils.nameFromResourceId(ResourceUtils.parentRelativePathFromResourceId(id)),
        ResourceUtils.nameFromResourceId(id));
}
 
Example #15
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SqlDatabase> getAsync(String name) {
    if (sqlServer == null) {
        return null;
    }
    return this.getBySqlServerAsync(this.sqlServer.resourceGroupName(), this.sqlServer.name(), name);
}
 
Example #16
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase get(String name) {
    if (sqlServer == null) {
        return null;
    }
    return this.getBySqlServer(this.sqlServer.resourceGroupName(), this.sqlServer.name(), name);
}
 
Example #17
Source File: SqlDatabaseOperationsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase getBySqlServer(SqlServer sqlServer, String name) {
    if (sqlServer == null) {
        return null;
    }
    DatabaseInner inner = this.manager.inner().databases().get(sqlServer.resourceGroupName(), sqlServer.name(), name);
    return (inner != null) ? new SqlDatabaseImpl(inner.name(), (SqlServerImpl) sqlServer, inner, manager) : null;
}
 
Example #18
Source File: RecommendedElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase getDatabase(String databaseName) {
    DatabaseInner databaseInner = this.sqlServer.manager().inner().databases().getByRecommendedElasticPool(
        this.sqlServer.resourceGroupName(),
        this.sqlServer.name(),
        this.name(),
        databaseName);

    return new SqlDatabaseImpl(databaseInner.name(), this.sqlServer, databaseInner, this.manager());
}
 
Example #19
Source File: AzureScannerTest.java    From clouditor with Apache License 2.0 5 votes vote down vote up
static SqlDatabase createSqlDatabase(String id, String name, DatabaseInner inner) {
  var db = mock(SqlDatabase.class);

  when(db.id()).thenReturn(id);
  when(db.name()).thenReturn(name);
  when(db.inner()).thenReturn(inner);

  return db;
}
 
Example #20
Source File: SqlDatabaseImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SqlDatabase> renameAsync(final String newDatabaseName) {
    final SqlDatabaseImpl self = this;
    ResourceId resourceId = ResourceId.fromString(this.id());
    String newId = resourceId.parent().id() + "/databases/" + newDatabaseName;
    return this.sqlServerManager.inner().databases()
        .renameAsync(this.resourceGroupName, this.sqlServerName, self.name(), newId)
        .flatMap(new Func1<Void, Observable<SqlDatabase>>() {
            @Override
            public Observable<SqlDatabase> call(Void aVoid) {
                return self.sqlServerManager.sqlServers().databases()
                    .getBySqlServerAsync(self.resourceGroupName, self.sqlServerName, newDatabaseName);
            }
        });
}
 
Example #21
Source File: SqlDatabaseImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase rename(String newDatabaseName) {
    ResourceId resourceId = ResourceId.fromString(this.id());
    String newId = resourceId.parent().id() + "/databases/" + newDatabaseName;
    this.sqlServerManager.inner().databases()
        .rename(this.resourceGroupName, this.sqlServerName, this.name(), newId);
    return this.sqlServerManager.sqlServers().databases()
        .getBySqlServer(this.resourceGroupName, this.sqlServerName, newDatabaseName);
}
 
Example #22
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlElasticPoolImpl withExistingDatabase(SqlDatabase database) {
    if (this.sqlDatabases == null) {
        this.sqlDatabases = new SqlDatabasesAsExternalChildResourcesImpl(this.taskGroup(), this.sqlServerManager, "SqlDatabase");
    }

    return new SqlDatabaseForElasticPoolImpl(this, this.sqlDatabases
        .patchUpdateDatabase(database.name()).withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation))
        .attach();
}
 
Example #23
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase removeDatabase(String databaseName) {
    return this.getDatabase(databaseName)
        .update()
        .withoutElasticPool()
        .withStandardEdition(SqlDatabaseStandardServiceObjective.S0)
        .apply();
}
 
Example #24
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase addExistingDatabase(SqlDatabase database) {
    return database
        .update()
        .withExistingElasticPool(this)
        .apply();
}
 
Example #25
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase addExistingDatabase(String databaseName) {
    return this.getDatabase(databaseName)
        .update()
        .withExistingElasticPool(this)
        .apply();
}
 
Example #26
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase addNewDatabase(String databaseName) {
    return this.sqlServerManager.sqlServers().databases()
        .define(databaseName)
        .withExistingSqlServer(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation)
        .withExistingElasticPool(this)
        .create();
}
 
Example #27
Source File: SqlElasticPoolImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public SqlDatabase getDatabase(String databaseName) {
    DatabaseInner databaseInner = this.sqlServerManager.inner().databases()
        .get(this.resourceGroupName, this.sqlServerName, databaseName);

    return databaseInner != null ? new SqlDatabaseImpl(this.resourceGroupName, this.sqlServerName, this.sqlServerLocation, databaseName, databaseInner, this.sqlServerManager) : null;
}
 
Example #28
Source File: AzureSQLDatabaseScanner.java    From clouditor with Apache License 2.0 4 votes vote down vote up
public AzureSQLDatabaseScanner() {
  super(SqlDatabase::id, SqlDatabase::name);
}
 
Example #29
Source File: ManageWebAppSqlConnection.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix         = ".azurewebsites.net";
    final String appName        = SdkContext.randomResourceName("webapp1-", 20);
    final String appUrl         = appName + suffix;
    final String sqlServerName  = SdkContext.randomResourceName("jsdkserver", 20);
    final String sqlDbName      = SdkContext.randomResourceName("jsdkdb", 20);
    final String admin          = "jsdkadmin";
    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
    final String password       = "StrongPass!123";
    final String rgName         = SdkContext.randomResourceName("rg1NEMV_", 24);

    try {


        //============================================================
        // Create a sql server

        System.out.println("Creating SQL server " + sqlServerName + "...");

        SqlServer server = azure.sqlServers().define(sqlServerName)
                .withRegion(Region.US_WEST)
                .withNewResourceGroup(rgName)
                .withAdministratorLogin(admin)
                .withAdministratorPassword(password)
                .create();

        System.out.println("Created SQL server " + server.name());

        //============================================================
        // Create a sql database for the web app to use

        System.out.println("Creating SQL database " + sqlDbName + "...");

        SqlDatabase db = server.databases().define(sqlDbName).create();

        System.out.println("Created SQL database " + db.name());

        //============================================================
        // Create a web app with a new app service plan

        System.out.println("Creating web app " + appName + "...");

        WebApp app = azure.webApps().define(appName)
                .withRegion(Region.US_WEST)
                .withExistingResourceGroup(rgName)
                .withNewWindowsPlan(PricingTier.STANDARD_S1)
                .withPhpVersion(PhpVersion.PHP5_6)
                .defineSourceControl()
                    .withPublicGitRepository("https://github.com/ProjectNami/projectnami")
                    .withBranch("master")
                    .attach()
                .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName())
                .withAppSetting("ProjectNami.DBName", db.name())
                .withAppSetting("ProjectNami.DBUser", admin)
                .withAppSetting("ProjectNami.DBPass", password)
                .create();

        System.out.println("Created web app " + app.name());
        Utils.print(app);

        //============================================================
        // Allow web app to access the SQL server

        System.out.println("Allowing web app " + appName + " to access SQL server...");

        SqlServer.Update update = server.update();
        for (String ip : app.outboundIPAddresses()) {
            update = update.withNewFirewallRule(ip);
        }
        server = update.apply();

        System.out.println("Firewall rules added for web app " + appName);
        Utils.print(server);

        System.out.println("Your WordPress app is ready.");
        System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit.");
        System.in.read();

        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
 
Example #30
Source File: ManageLinuxWebAppSqlConnection.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix         = ".azurewebsites.net";
    final String appName        = SdkContext.randomResourceName("webapp1-", 20);
    final String appUrl         = appName + suffix;
    final String sqlServerName  = SdkContext.randomResourceName("jsdkserver", 20);
    final String sqlDbName      = SdkContext.randomResourceName("jsdkdb", 20);
    final String admin          = "jsdkadmin";
    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
    final String password       = "StrongPass!123";
    final String rgName         = SdkContext.randomResourceName("rg1NEMV_", 24);

    try {


        //============================================================
        // Create a sql server

        System.out.println("Creating SQL server " + sqlServerName + "...");

        SqlServer server = azure.sqlServers().define(sqlServerName)
                .withRegion(Region.US_WEST)
                .withNewResourceGroup(rgName)
                .withAdministratorLogin(admin)
                .withAdministratorPassword(password)
                .create();

        System.out.println("Created SQL server " + server.name());

        //============================================================
        // Create a sql database for the web app to use

        System.out.println("Creating SQL database " + sqlDbName + "...");

        SqlDatabase db = server.databases().define(sqlDbName).create();

        System.out.println("Created SQL database " + db.name());

        //============================================================
        // Create a web app with a new app service plan

        System.out.println("Creating web app " + appName + "...");

        WebApp app = azure.webApps().define(appName)
                .withRegion(Region.US_WEST)
                .withExistingResourceGroup(rgName)
                .withNewLinuxPlan(PricingTier.STANDARD_S1)
                .withBuiltInImage(RuntimeStack.PHP_5_6)
                .defineSourceControl()
                    .withPublicGitRepository("https://github.com/ProjectNami/projectnami")
                    .withBranch("master")
                    .attach()
                .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName())
                .withAppSetting("ProjectNami.DBName", db.name())
                .withAppSetting("ProjectNami.DBUser", admin)
                .withAppSetting("ProjectNami.DBPass", password)
                .create();

        System.out.println("Created web app " + app.name());
        Utils.print(app);

        //============================================================
        // Allow web app to access the SQL server

        System.out.println("Allowing web app " + appName + " to access SQL server...");

        SqlServer.Update update = server.update();
        for (String ip : app.outboundIPAddresses()) {
            update = update.withNewFirewallRule(ip);
        }
        server = update.apply();

        System.out.println("Firewall rules added for web app " + appName);
        Utils.print(server);

        System.out.println("Your WordPress app is ready.");
        System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit.");
        System.in.read();

        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}