Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.dasein.cloud.azure.platform;
  
  import org.dasein.cloud.*;
 
 import  javax.annotation.Nonnull;
 import java.util.*;

Created by Vlad_Munthiu on 10/28/2014.
 
 
 public class AzureSqlDatabaseSupport implements RelationalDatabaseSupport {
     private Azure provider;
 
     public AzureSqlDatabaseSupport(Azure provider) {
         this. = provider;
     }
 
     @Override
     public void addAccess(String providerDatabaseIdString sourceCidrthrows CloudExceptionInternalException {
         Database database = getDatabase(providerDatabaseId);
         if(database == null)
             throw new InternalException("Invaid database provider Id");
 
         if(sourceCidr == null)
             throw new InternalException("Invalid parameter sourceCirs. The parameter cannot be null");
 
         List<StringruleParts = Arrays.asList(sourceCidr.split("::"));
         if(ruleParts.size() != 2)
             throw new InternalException("Invalid parameter sourceCidr");
 
         IpUtils.IpRange ipRange = new IpUtils.IpRange(ruleParts.get(0), ruleParts.get(1));
 
         ServerServiceResourceModel firewallRule = new ServerServiceResourceModel();
         firewallRule.setName(String.format("%s_%s"database.getName(), new Date().getTime()));
         firewallRule.setStartIpAddress(ipRange.getLow().toDotted());
         firewallRule.setEndIpAddress(ipRange.getHigh().toDotted());
 
         String serverName = Arrays.asList(database.getProviderDatabaseId().split(":")).get(0);
 
         HttpUriRequest createRuleRequest = new AzureSQLDatabaseSupportRequests().addFirewallRule(serverNamefirewallRule).build();
         new AzureRequester(createRuleRequest).execute();
     }
 
     @Override
     public void alterDatabase(String providerDatabaseIdboolean applyImmediatelyString productSizeint storageInGigabytesString configurationIdString newAdminUserString newAdminPasswordint newPortint snapshotRetentionInDaysTimeWindow preferredMaintenanceWindowTimeWindow preferredBackupWindowthrows CloudExceptionInternalException {
 
     }
 
     @Override
     public String createFromScratch(String dataSourceNameDatabaseProduct productString databaseVersionString withAdminUserString withAdminPasswordint hostPortthrows CloudExceptionInternalException {
         if(!isValidAdminUserName(withAdminUser)){
             throw new InternalException("Invalid admin user name");
         }
 
         if(product == null && product.getName() == null){
             throw new InternalException("Cannot create database. Database product or database product name cannot be empty");
         }
 
         ServerModel serverToCreate = new ServerModel();
         serverToCreate.setAdministratorLogin(withAdminUser);
         serverToCreate.setAdministratorLoginPassword(withAdminPassword);
         serverToCreate.setLocation(this..getContext().getRegionId());
 
         HttpUriRequest createServerRequest =  new AzureSQLDatabaseSupportRequests().createServer(serverToCreate).build();
         ServerNameModel resultServerName = new AzureRequester(createServerRequest).withXmlProcessor(ServerNameModel.class).execute();
 
         try {
             String productGUID = getProductGUID(product);
 
             DatabaseServiceResourceModel dbToCreate = new DatabaseServiceResourceModel();
             dbToCreate.setName(dataSourceName);
             dbToCreate.setEdition(product.getName());
             dbToCreate.setServiceObjectiveId(productGUID);
 
             HttpUriRequest createDatabaseRequest = new AzureSQLDatabaseSupportRequests().createDatabase(resultServerName.getName(), dbToCreate).build();
             DatabaseServiceResourceModel database = new AzureRequester(createDatabaseRequest).withXmlProcessor(DatabaseServiceResourceModel.class).execute();
             return String.format("%s:%s"resultServerName.getName(), database.getName());
         }
         catch (Exception ex) {
             //delete server
             HttpUriRequest deleteServerRequest = new AzureSQLDatabaseSupportRequests().deleteServer(resultServerName.getName()).build();
             new AzureRequester(deleteServerRequest).execute();
             throw new CloudException("Could not create database. " + ex.getMessage());
         }
     }
    private boolean isValidAdminUserName(String name){
        List<StringillegalUserName = Arrays.asList("administrator""admin""sa""root""dbmanager""loginmanager""dbo""guest""public");
        if(illegalUserName.contains(name)){
            return false;
        }
        return true;
    }
    @Override
    public String createFromLatest(String dataSourceNameString providerDatabaseIdString productSizeString providerDataCenterIdint hostPortthrows InternalExceptionCloudException {
        return null;
    }
    @Override
    public String createFromSnapshot(String dataSourceNameString providerDatabaseIdString providerDbSnapshotIdString productSizeString providerDataCenterIdint hostPortthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public String createFromTimestamp(String dataSourceNameString providerDatabaseIdlong beforeTimestampString productSizeString providerDataCenterIdint hostPortthrows InternalExceptionCloudException {
        return null;
    }

    
Provides access to meta-data about RDS capabilities in the current region of this cloud.

Returns:
a description of the features supported by this region of this cloud
Throws:
org.dasein.cloud.InternalException an error occurred within the Dasein Cloud API implementation
org.dasein.cloud.CloudException an error occurred within the cloud provider
    @Nonnull
    @Override
        return new AzureSqlDatabaseCapabilities();
    }
    @Override
    public DatabaseConfiguration getConfiguration(String providerConfigurationIdthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public Database getDatabase(final String providerDatabaseIdthrows CloudExceptionInternalException {
        if(providerDatabaseId == null)
            throw new InternalException("Provider database id cannot be null");
        final List<StringproviderDatabaseIdParts = Arrays.asList(providerDatabaseId.split(":"));
        if(providerDatabaseIdParts.size() != 2)
            throw new InternalException("Invalid name for the provider database id");
        HttpUriRequest listServersRequest = new AzureSQLDatabaseSupportRequests(this.).listServersNonGen().build();
        ServersModel serversModel = new AzureRequester(listServersRequest).withXmlProcessor(ServersModel.class).execute();
        if(serversModel == null || serversModel.getServers() == null)
            return null;
        Object serverFound = CollectionUtils.find(serversModel.getServers(), new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return providerDatabaseIdParts.get(0).equalsIgnoreCase(((ServerModel)object).getName());
            }
        });
        if(serverFound == null)
            return null;
        HttpUriRequest httpUriRequest = new AzureSQLDatabaseSupportRequests()
                .getDatabase(providerDatabaseIdParts.get(0), providerDatabaseIdParts.get(1)).build();
        Database database = new AzureRequester(httpUriRequest).withXmlProcessor(new DriverToCoreMapper<DatabaseServiceResourceModelDatabase>() {
            @Override
            public Database mapFrom(DatabaseServiceResourceModel entity) {
                return databaseFrom(entityproviderDatabaseIdParts.get(0));
            }
        }, DatabaseServiceResourceModel.class).execute();
        //getDatabase is a global search so set server location for database
        database.setProviderRegionId(((ServerModelserverFound).getLocation());
        return database;
    }
    @Override
        return Arrays.asList(.);
    }
    @Override
    public String getDefaultVersion(@Nonnull DatabaseEngine forEnginethrows CloudExceptionInternalException {
        return "2.0";
    }
    @Nonnull
    @Override
    public Iterable<StringgetSupportedVersions(@Nonnull DatabaseEngine forEnginethrows CloudExceptionInternalException {
        return Arrays.asList("2.0");
    }

    
List supported database products

Parameters:
forEngine database engine, e.g. MySQL, SQL Server EE, etc.
Returns:
iteration of the database products supported by the engine
Throws:
org.dasein.cloud.CloudException
org.dasein.cloud.InternalException
Since:
2014.08 for consistency
    @Nonnull
    @Override
        if(forEngine == null)
            throw new InternalException("Please specify the DatabaseEngine for which you want to retrieve the products.");
        if(!forEngine.name().toString().equalsIgnoreCase("sqlserver_ee"))
            return Arrays.asList();
        final ArrayList<DatabaseProductproducts = new ArrayList<DatabaseProduct>();
        CollectionUtils.forAllDo(versionResult.getEditions(), new Closure() {
            @Override
            public void execute(Object input) {
                ServerServiceResourceModel.Edition edition = (ServerServiceResourceModel.Edition)input;
                for(ServerServiceResourceModel.ServiceLevelObjective serviceLevelObjective : edition.getServiceLevelObjectives()){
                    DatabaseProduct product = new DatabaseProduct(serviceLevelObjective.getName(), edition.getName());
                    product.setProviderDataCenterId(.getDataCenterId(.getContext().getRegionId()));
                    product.setEngine(.);
                    product.setLicenseModel(.);
                    products.add(product);
                }
            }
        });
        return products;
    }
    @Override
    public DatabaseSnapshot getSnapshot(String providerDbSnapshotIdthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public boolean isSubscribed() throws CloudExceptionInternalException {
        return true;
    }
    @Override
    public Iterable<StringlistAccess(String toProviderDatabaseIdthrows CloudExceptionInternalException {
        final ArrayList<Stringrules = new ArrayList<String>();
        Database database = getDatabase(toProviderDatabaseId);
        if(database == null)
            throw new InternalException("Invaid database provider Id");
        String serverName = Arrays.asList(database.getProviderDatabaseId().split(":")).get(0);
        HttpUriRequest listRulesRequest = new AzureSQLDatabaseSupportRequests().listFirewallRules(serverName).build();
        ServerServiceResourcesModel rulesModel = new AzureRequester(listRulesRequest).withXmlProcessor(ServerServiceResourcesModel.class).execute();
        if(rulesModel == null || rulesModel.getServerServiceResourcesModels() == null)
            return rules;
        CollectionUtils.forAllDo(rulesModel.getServerServiceResourcesModels(), new Closure() {
            @Override
            public void execute(Object input) {
                ServerServiceResourceModel firewallRule = (ServerServiceResourceModelinput;
                String endIpAddress = firewallRule.getEndIpAddress();
                if(endIpAddress == null)
                    endIpAddress = firewallRule.getStartIpAddress();
                rules.add(String.format("%s::%s::%s"firewallRule.getName(), firewallRule.getStartIpAddress(), endIpAddress));
            }
        });
        return rules;
    }
    @Override
        return null;
    }
    @Nonnull
    @Override
        return null;
    }
    @Override
        ArrayList<Databasedatabases = new ArrayList<Database>();
        HttpUriRequest httpUriRequest = new AzureSQLDatabaseSupportRequests(this.).listServersNonGen().build();
        ServersModel serversModel = new AzureRequester(httpUriRequest).withXmlProcessor(ServersModel.class).execute();
        if(serversModel == null || serversModel.getServers() == null)
            return databases;
        List<ServerModelservers = serversModel.getServers();
        CollectionUtils.filter(serversnew Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return .getContext().getRegionId().equalsIgnoreCase(((ServerModel)object).getLocation());
            }
        });
        for (ServerModel serverModel : servers){
            HttpUriRequest serverHttpUriRequest = new AzureSQLDatabaseSupportRequests(this.).listDatabases(serverModel.getName()).build();
            DatabaseServiceResourcesModel databaseServiceResourcesModel =
                    new AzureRequester(serverHttpUriRequest).withXmlProcessor(DatabaseServiceResourcesModel.class).execute();
            if (databaseServiceResourcesModel == null)
                continue;
            for (DatabaseServiceResourceModel databaseModel : databaseServiceResourcesModel.getDatabaseServiceResourceModels()){
                if(!databaseModel.getName().equalsIgnoreCase("master"))
                    databases.add(databaseFrom(databaseModelserverModel.getName()));
            }
        }
        return databases;
    }
    private Database databaseFrom(DatabaseServiceResourceModel databaseServiceResourceModelString serverName){
        if(databaseServiceResourceModel == null)
            return null;
        Database database = new Database();
        database.setName(databaseServiceResourceModel.getName());
        database.setProviderDatabaseId(String.format("%s:%s"serverNamedatabaseServiceResourceModel.getName()));
        database.setProviderRegionId(.getContext().getRegionId());
        database.setAllocatedStorageInGb(Integer.parseInt(databaseServiceResourceModel.getMaxSizeGB()));
        database.setEngine(.);
        database.setCreationTimestamp(new DateTime(databaseServiceResourceModel.getCreationDate()).getMillis());
        database.setCurrentState(databaseServiceResourceModel.getState().equalsIgnoreCase("normal") ? . : .);
        database.setProductSize(databaseServiceResourceModel.getEdition());
        database.setHostName(String.format("%s.database.windows.net"serverName));
        database.setHostPort(1433);
        return database;
    }
    @Override
    public Collection<ConfigurationParameterlistParameters(String forProviderConfigurationIdthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public Iterable<DatabaseSnapshotlistSnapshots(String forOptionalProviderDatabaseIdthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public void removeConfiguration(String providerConfigurationIdthrows CloudExceptionInternalException {
    }
    @Override
    public void removeDatabase(String providerDatabaseIdthrows CloudExceptionInternalException {
        if(providerDatabaseId == null)
            throw new InternalException("Provider database id cannot be null");
        List<StringproviderDatabaseIdParts = Arrays.asList(providerDatabaseId.split(":"));
        if(providerDatabaseIdParts.size() != 2)
            throw new InternalException("Invalid name for the provider database id");
        HttpUriRequest deleteDatabaseRequest = new AzureSQLDatabaseSupportRequests().deleteDatabase(providerDatabaseIdParts.get(0), providerDatabaseIdParts.get(1)).build();
        new AzureRequester(deleteDatabaseRequest).execute();
        HttpUriRequest serverHttpUriRequest = new AzureSQLDatabaseSupportRequests(this.).listDatabases(providerDatabaseIdParts.get(0)).build();
        DatabaseServiceResourcesModel databaseServiceResourcesModel =
                new AzureRequester(serverHttpUriRequest).withXmlProcessor(DatabaseServiceResourcesModel.class).execute();
        if(databaseServiceResourcesModel == null || databaseServiceResourcesModel.getDatabaseServiceResourceModels().size() > 1)
            return;
        if(databaseServiceResourcesModel.getDatabaseServiceResourceModels().size() == 1 && !databaseServiceResourcesModel.getDatabaseServiceResourceModels().get(0).getName().equalsIgnoreCase("master"))
            return;
        HttpUriRequest deleteServerRequest = new AzureSQLDatabaseSupportRequests().deleteServer(providerDatabaseIdParts.get(0)).build();
        new AzureRequester(deleteServerRequest).execute();
    }
    @Override
    public void removeSnapshot(String providerSnapshotIdthrows CloudExceptionInternalException {
    }
    @Override
    public void resetConfiguration(String providerConfigurationIdString... parametersthrows CloudExceptionInternalException {
    }
    @Override
    public void restart(String providerDatabaseIdboolean blockUntilDonethrows CloudExceptionInternalException {
    }
    @Override
    public void revokeAccess(String providerDatabaseIdString sourceCidethrows CloudExceptionInternalException {
        Database database = getDatabase(providerDatabaseId);
        if(database == null)
            throw new InternalException("Invaid database provider Id");
        List<StringruleParts = Arrays.asList(sourceCide.split("::"));
        if(ruleParts.size() != 3)
            throw new InternalError("Invalid parameter sourceCidr");
        String ruleName = ruleParts.get(0);
        String serverName = Arrays.asList(database.getProviderDatabaseId().split(":")).get(0);
        HttpUriRequest deleteRuleRequest = new AzureSQLDatabaseSupportRequests().deleteFirewallRule(serverNameruleName).build();
        new AzureRequester(deleteRuleRequest).execute();
    }
    @Override
    public void updateConfiguration(String providerConfigurationIdConfigurationParameter... parametersthrows CloudExceptionInternalException {
    }
    @Override
    public DatabaseSnapshot snapshot(String providerDatabaseIdString namethrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public DatabaseBackup getUsableBackup(String providerDbIdString beforeTimestampthrows CloudExceptionInternalException {
        return null;
    }
    @Override
    public Iterable<DatabaseBackuplistBackups(final String forOptionalProviderDatabaseIdthrows CloudExceptionInternalException {
        final ArrayList<DatabaseBackupbackups = new ArrayList<DatabaseBackup>();
        if(forOptionalProviderDatabaseId == null) {
            HttpUriRequest httpUriRequest = new AzureSQLDatabaseSupportRequests(this.).listServers().build();
            ServerServiceResourcesModel serversModel = new AzureRequester(httpUriRequest).withXmlProcessor(ServerServiceResourcesModel.class).execute();
            if (serversModel == null)
                return backups;
            CollectionUtils.forAllDo(serversModel.getServerServiceResourcesModels(), new Closure() {
                @Override
                public void execute(Object input) {
                    final ServerServiceResourceModel serverModel = (ServerServiceResourceModelinput;
                    backups.addAll(getBackupsForServer(serverModel.getName()));
                }
            });
        } else {
            List<StringproviderDBIdParts = Arrays.asList(forOptionalProviderDatabaseId.split(":"));
            if(providerDBIdParts.size() != 2)
                throw new InternalException("Invalid provider database id");
            final String serverName = providerDBIdParts.get(0);
            final String databaseName = providerDBIdParts.get(1);
            backups.addAll(getBackupsForServer(serverName));
            CollectionUtils.filter(backupsnew Predicate() {
                @Override
                public boolean evaluate(Object object) {
                    DatabaseBackup backup = (DatabaseBackupobject;
                    return backup.getProviderDatabaseId().equalsIgnoreCase(String.format("%s:%s"serverNamedatabaseName));
                }
            });
        }
        return backups;
    }
    private ArrayList<DatabaseBackupgetBackupsForServer(final String serverName){
        final ArrayList<DatabaseBackupbackups = new ArrayList<DatabaseBackup>();
        try {
            HttpUriRequest serverListBackupsRequest = new AzureSQLDatabaseSupportRequests().getRecoverableDatabases(serverName).build();
            RecoverableDatabasesModel recoverableDatabasesModel = new AzureRequester(serverListBackupsRequest).withXmlProcessor(RecoverableDatabasesModel.class).execute();
            CollectionUtils.forAllDo(recoverableDatabasesModel.getRecoverableDatabaseModels(), new Closure() {
                @Override
                public void execute(Object input) {
                    RecoverableDatabaseModel recoverableDatabaseModel = (RecoverableDatabaseModelinput;
                    DatabaseBackup databaseBackup = new DatabaseBackup();
                    databaseBackup.setProviderDatabaseId(String.format("%s:%s"serverNamegetDatabaseName(recoverableDatabaseModel)));
                    databaseBackup.setProviderOwnerId(.getContext().getAccountNumber());
                    databaseBackup.setProviderRegionId(.getContext().getRegionId());
                    databaseBackup.setCurrentState(.);
                    databaseBackup.setProviderBackupId(recoverableDatabaseModel.getName());
                    backups.add(databaseBackup);
                }
            });
        } catch (CloudException e) {
            e.printStackTrace();
        }
        return backups;
    }
    private String getDatabaseName(RecoverableDatabaseModel recoverableDatabaseModel) {
        if(recoverableDatabaseModel.getName() == null || recoverableDatabaseModel.getName().isEmpty())
            return null;
        //assume is an auto-generated name in the following format: AutomatedSqlExport_databaseName_20150114T100004Z
        if(recoverableDatabaseModel.getName().contains("_")){
            List<StringnameParts = Arrays.asList(recoverableDatabaseModel.getName().split("_"));
            return nameParts.get(1);
        }
        //assume is a backup from a deleted database
        return recoverableDatabaseModel.getName();
    }
    @Override
    public void createFromBackup(DatabaseBackup backupString databaseCloneToNamethrows CloudExceptionInternalException {
        if(backup == null)
            throw new InternalException("DatabaseBackup parameter cannot be null");
        if(backup.getProviderDatabaseId() == null || !backup.getProviderDatabaseId().contains(":"))
            throw new InternalException("Invalid provider database id for the specified database backup");
        List<StringproviderDBIdParts = Arrays.asList(backup.getProviderDatabaseId().split(":"));
        String serverName = providerDBIdParts.get(0);
        String databaseName = providerDBIdParts.get(1);
        CreateDatabaseRestoreModel createDatabaseRestoreModel = new CreateDatabaseRestoreModel();
        createDatabaseRestoreModel.setSourceDatabaseName(databaseName);
        createDatabaseRestoreModel.setTargetDatabaseName(databaseCloneToName);
        HttpUriRequest createFromBackupRequest =
                new AzureSQLDatabaseSupportRequests().createDatabaseFromBackup(serverNamecreateDatabaseRestoreModel).build();
        new AzureRequester(createFromBackupRequest).execute();
    }
    @Override
    public void removeBackup(DatabaseBackup backupthrows CloudExceptionInternalException {
    }
    @Override
    public void restoreBackup(DatabaseBackup backupthrows CloudExceptionInternalException {
    }

    
Maps the specified Dasein Cloud service action to an identifier specific to an underlying cloud. If there is no mapping that makes any sense, the method will return an empty array.

Parameters:
action the Dasein Cloud service action
Returns:
a list of cloud-specific IDs (e.g. iam:ListGroups) representing an action with this cloud provider
    @Nonnull
    @Override
    public String[] mapServiceAction(@Nonnull ServiceAction action) {
        return new String[0];
    }
        HttpUriRequest subscriptionMetaRequest = new AzureSQLDatabaseSupportRequests().subscriptionMetaRequest().build();
        ServerServiceResourceModel serverServiceResourceModel = new AzureRequester(this.subscriptionMetaRequest).withXmlProcessor(ServerServiceResourceModel.class).execute();
        return (ServerServiceResourceModel.Version) CollectionUtils.find(serverServiceResourceModel.getVersions(), new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return ((ServerServiceResourceModel.Versionobject).getName().equalsIgnoreCase("2.0");
            }
        });
    }
    private String getProductGUID(final DatabaseProduct productthrows CloudException {
        ServerServiceResourceModel.Edition edition = (ServerServiceResourceModel.Edition) CollectionUtils.find(versionResult.getEditions(), new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                return ((ServerServiceResourceModel.Editionobject).getName().equalsIgnoreCase(product.getName());
            }
        });
            @Override
            public boolean evaluate(Object object) {
                return ((ServerServiceResourceModel.ServiceLevelObjectiveobject).getName().equalsIgnoreCase(product.getProductSize());
            }
        });
        return serviceLevelObjective.getId();
    }
    @Override
    public void removeTags(@Nonnull String providerDatabaseId, @Nonnull Tag... tagsthrows CloudExceptionInternalException{}
    @Override
    public void removeTags(@Nonnull String[] providerDatabaseIds, @Nonnull Tag ... tagsthrows CloudExceptionInternalException{}
    @Override
    public void updateTags(@Nonnull String providerDatabaseId, @Nonnull Tag... tagsthrows CloudExceptionInternalException{}
    @Override
    public void updateTags(@Nonnull String[] providerDatabaseIds, @Nonnull Tag... tagsthrows CloudExceptionInternalException{}
    @Override
    public void setTags( @Nonnull String providerDatabaseId, @Nonnull Tag... tags ) throws CloudExceptionInternalException{}
    @Override
    public void setTags( @Nonnull String[] providerDatabaseIds, @Nonnull Tag... tags ) throws CloudExceptionInternalException{}
New to GrepCode? Check out our FAQ X