com.microsoft.azure.AzureEnvironment Java Examples

The following examples show how to use com.microsoft.azure.AzureEnvironment. 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: ManageSqlImportExportDatabase.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {

        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #2
Source File: AzureClientCredentialsTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRefreshTokenWhenBothRefreshTokenAndAuthenticationResultIsObtainableThenExpectedRefreshTokenReturns() {
    when(credentialView.getRefreshToken()).thenReturn(REFRESH_TOKEN);
    when(cbRefreshTokenClient.refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean())).thenReturn(authenticationResult);

    Optional<String> result = new AzureClientCredentials(credentialView, LOG_LEVEL, cbRefreshTokenClientProvider, authenticationContextProvider)
            .getRefreshToken();

    assertTrue(result.isPresent());
    assertEquals(REFRESH_TOKEN, result.get());

    verify(credentialView, times(1)).getTenantId();
    verify(credentialView, times(1)).getAccessKey();
    verify(credentialView, times(1)).getSecretKey();
    verify(credentialView, times(2)).codeGrantFlow();
    verify(credentialView, times(1)).getSubscriptionId();
    verify(cbRefreshTokenClientProvider, times(2)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClient, times(1)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(cbRefreshTokenClientProvider, times(2)).getCBRefreshTokenClient(eq(AzureEnvironment.AZURE.activeDirectoryEndpoint()));
}
 
Example #3
Source File: ManageSqlFailoverGroups.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #4
Source File: ManageSqlDatabasesAcrossDifferentDataCenters.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {

        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
                .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withReadTimeout(150, TimeUnit.SECONDS)
                .withLogLevel(LogLevel.BODY)
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
   } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #5
Source File: AzureCredentialConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> initCodeGrantFlow(CloudContext cloudContext, CloudCredential cloudCredential) {
    Map<String, String> parameters = new HashMap<>();
    AzureCredentialView azureCredential = new AzureCredentialView(cloudCredential);

    ApplicationTokenCredentials applicationCredentials = new ApplicationTokenCredentials(
            azureCredential.getAccessKey(),
            azureCredential.getTenantId(),
            azureCredential.getSecretKey(),
            AzureEnvironment.AZURE);

    String replyUrl = appCreationCommand.getRedirectURL(String.valueOf(cloudContext.getAccountId()), azureCredential.getDeploymentAddress());
    CbDelegatedTokenCredentials creds = new CbDelegatedTokenCredentials(applicationCredentials, replyUrl, authenticationContextProvider,
            cbRefreshTokenClientProvider);

    String state = UUID.randomUUID().toString();
    parameters.put("appLoginUrl", creds.generateAuthenticationUrl(state));
    parameters.put("appReplyUrl", replyUrl);
    parameters.put("codeGrantFlowState", state);
    return parameters;
}
 
Example #6
Source File: AzureClientCredentialsTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAzureAgainstSubscriptionId() {
    when(credentialView.getRefreshToken()).thenReturn(REFRESH_TOKEN);
    when(cbRefreshTokenClient.refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean())).thenReturn(authenticationResult);

    Azure result = new AzureClientCredentials(credentialView, LOG_LEVEL, cbRefreshTokenClientProvider, authenticationContextProvider).getAzure();

    assertNotNull(result);
    assertEquals(SUBSCRIPTION_ID, result.subscriptionId());

    verify(credentialView, times(1)).getTenantId();
    verify(credentialView, times(1)).getAccessKey();
    verify(credentialView, times(1)).getSecretKey();
    verify(credentialView, times(0)).getAppReplyUrl();
    verify(credentialView, times(1)).getRefreshToken();
    verify(credentialView, times(1)).codeGrantFlow();
    verify(credentialView, times(2)).getSubscriptionId();
    verify(credentialView, times(0)).getAuthorizationCode();
    verify(cbRefreshTokenClientProvider, times(2)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClient, times(1)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(cbRefreshTokenClientProvider, times(2)).getCBRefreshTokenClient(eq(AzureEnvironment.AZURE.activeDirectoryEndpoint()));
}
 
Example #7
Source File: ManageSqlFirewallRules.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
                .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withReadTimeout(150, TimeUnit.SECONDS)
                .withLogLevel(LogLevel.BODY)
                .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #8
Source File: CertificateCredentialImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
void exportAuthFile(ServicePrincipalImpl servicePrincipal) {
    if (authFile == null) {
        return;
    }
    RestClient restClient = servicePrincipal.manager().roleInner().restClient();
    AzureEnvironment environment = Utils.extractAzureEnvironment(restClient);

    StringBuilder builder = new StringBuilder("{\n");
    builder.append("  ").append(String.format("\"clientId\": \"%s\",", servicePrincipal.applicationId())).append("\n");
    builder.append("  ").append(String.format("\"clientCertificate\": \"%s\",", privateKeyPath.replace("\\", "\\\\"))).append("\n");
    builder.append("  ").append(String.format("\"clientCertificatePassword\": \"%s\",", privateKeyPassword)).append("\n");
    builder.append("  ").append(String.format("\"tenantId\": \"%s\",", servicePrincipal.manager().tenantId())).append("\n");
    builder.append("  ").append(String.format("\"subscriptionId\": \"%s\",", servicePrincipal.assignedSubscription)).append("\n");
    builder.append("  ").append(String.format("\"activeDirectoryEndpointUrl\": \"%s\",", environment.activeDirectoryEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"resourceManagerEndpointUrl\": \"%s\",", environment.resourceManagerEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"activeDirectoryGraphResourceId\": \"%s\",", environment.graphEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"managementEndpointUrl\": \"%s\"", environment.managementEndpoint())).append("\n");
    builder.append("}");
    try {
        authFile.write(builder.toString().getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: Utils.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Get the Azure storage account connection string.
 * @param accountName storage account name
 * @param accountKey storage account key
 * @param restClient rest client
 * @return the storage account connection string.
 */
public static String getStorageConnectionString(String accountName, String accountKey,
                                                RestClient restClient) {
    AzureEnvironment environment = AzureEnvironment.AZURE;
    if (restClient != null) {
        try {
            AzureEnvironment environment1 = extractAzureEnvironment(restClient);
            if (environment1 != null && environment1.storageEndpointSuffix() != null) {
                environment = environment1;
            }
        } catch (IllegalArgumentException e) {
            // ignored
        }
    }
    String suffix = environment.storageEndpointSuffix().replaceAll("^\\.*", "");
    return String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=%s",
            accountName, accountKey, suffix);
}
 
Example #10
Source File: PasswordCredentialImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
void exportAuthFile(ServicePrincipalImpl servicePrincipal) {
    if (authFile == null) {
        return;
    }
    RestClient restClient = servicePrincipal.manager().roleInner().restClient();
    AzureEnvironment environment = Utils.extractAzureEnvironment(restClient);

    StringBuilder builder = new StringBuilder("{\n");
    builder.append("  ").append(String.format("\"clientId\": \"%s\",", servicePrincipal.applicationId())).append("\n");
    builder.append("  ").append(String.format("\"clientSecret\": \"%s\",", value())).append("\n");
    builder.append("  ").append(String.format("\"tenantId\": \"%s\",", servicePrincipal.manager().tenantId())).append("\n");
    builder.append("  ").append(String.format("\"subscriptionId\": \"%s\",", servicePrincipal.assignedSubscription)).append("\n");
    builder.append("  ").append(String.format("\"activeDirectoryEndpointUrl\": \"%s\",", environment.activeDirectoryEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"resourceManagerEndpointUrl\": \"%s\",", environment.resourceManagerEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"activeDirectoryGraphResourceId\": \"%s\",", environment.graphEndpoint())).append("\n");
    builder.append("  ").append(String.format("\"managementEndpointUrl\": \"%s\"", environment.managementEndpoint())).append("\n");
    builder.append("}");
    try {
        authFile.write(builder.toString().getBytes());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: ManageSqlWithRecoveredOrRestoredDatabase.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {

        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #12
Source File: CbDelegatedTokenCredentialsTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTokenWhenAuthCodeGivenButNoTokenProvidedAndHttpUsedAsActiveDirectoryEndpointProtocolInsteadOfHttpsThenExceptionComes()
                throws IOException {
    String authorityUrl = format("%s/%s", format(TEST_AD_ENDPOINT, HTTP), TEST_DOMAIN);
    when(applicationTokenCredentials.environment()).thenReturn(new AzureEnvironment(Map.of("activeDirectoryEndpointUrl", format(TEST_AD_ENDPOINT, HTTP))));
    doThrow(new IllegalArgumentException("'authority' should use the 'https' scheme")).when(authenticationContextProvider)
            .getAuthenticationContext(eq(authorityUrl), eq(false), any(ExecutorService.class));

    var underTest = new CbDelegatedTokenCredentials(applicationTokenCredentials, REDIRECT_URL, authenticationContextProvider, cbRefreshTokenClientProvider);
    underTest.setAuthorizationCode(AUTHORIZATION_CODE);

    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("'authority' should use the 'https' scheme");

    underTest.getToken(RESOURCE);

    verify(applicationTokenCredentials, times(0)).clientId();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(format("%s/", DEFAULT_TEST_AD_ENDPOINT)));
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(anyString(), anyBoolean(), any(ExecutorService.class));
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(authenticationContextProvider, times(1)).getAuthenticationContext(eq(authorityUrl), eq(false), any(ExecutorService.class));
}
 
Example #13
Source File: ManageSqlServerSecurityAlertPolicy.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #14
Source File: GettingSqlServerMetrics.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #15
Source File: ManageSqlServerDnsAliases.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #16
Source File: AzureAuthHelper.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
protected AzureEnvironment getAzureEnvironment(String environment) {
    if (StringUtils.isEmpty(environment)) {
        return AzureEnvironment.AZURE;
    }

    switch (environment.toUpperCase(Locale.ENGLISH)) {
        case "AZURE_CHINA":
            return AzureEnvironment.AZURE_CHINA;
        case "AZURE_GERMANY":
            return AzureEnvironment.AZURE_GERMANY;
        case "AZURE_US_GOVERNMENT":
            return AzureEnvironment.AZURE_US_GOVERNMENT;
        default:
            return AzureEnvironment.AZURE;
    }
}
 
Example #17
Source File: ManageSqlServerKeysWithAzureKeyVaultKey.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure, credentials.clientId());
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #18
Source File: AzureAuthHelper.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
private AzureEnvironment getAzureEnvironment(String environment) {
    if (StringUtils.isEmpty(environment)) {
        return AzureEnvironment.AZURE;
    }

    switch (environment.toUpperCase(Locale.ENGLISH)) {
        case "AZURE_CHINA":
            return AzureEnvironment.AZURE_CHINA;
        case "AZURE_GERMANY":
            return AzureEnvironment.AZURE_GERMANY;
        case "AZURE_US_GOVERNMENT":
            return AzureEnvironment.AZURE_US_GOVERNMENT;
        default:
            return AzureEnvironment.AZURE;
    }
}
 
Example #19
Source File: ManageSqlDatabaseInElasticPool.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
                .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withReadTimeout(150, TimeUnit.SECONDS)
                .withLogLevel(LogLevel.BODY)
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
   } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #20
Source File: ManageSqlDatabase.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {

        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
                .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withSerializerAdapter(new AzureJacksonAdapter())
                .withReadTimeout(150, TimeUnit.SECONDS)
                .withLogLevel(LogLevel.BODY)
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #21
Source File: AzureClientCredentialsTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRefreshTokenWhenThereIsNoRefreshTokenInCredentialViewThenNoRefreshTokenReturns() {
    when(credentialView.getRefreshToken()).thenReturn(null);
    when(credentialView.getAppReplyUrl()).thenReturn("replyUrl");
    when(credentialView.getAuthorizationCode()).thenReturn("someAuthCode");

    Optional<String> result = new AzureClientCredentials(credentialView, LOG_LEVEL, cbRefreshTokenClientProvider, authenticationContextProvider)
            .getRefreshToken();

    assertFalse(result.isPresent());

    verify(credentialView, times(1)).getTenantId();
    verify(credentialView, times(1)).getAccessKey();
    verify(credentialView, times(1)).getSecretKey();
    verify(credentialView, times(1)).getAppReplyUrl();
    verify(credentialView, times(1)).getRefreshToken();
    verify(credentialView, times(2)).codeGrantFlow();
    verify(credentialView, times(1)).getSubscriptionId();
    verify(credentialView, times(1)).getAuthorizationCode();
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(anyString());
    verify(cbRefreshTokenClient, times(0)).refreshToken(anyString(), anyString(), anyString(), anyString(), anyString(), anyBoolean());
    verify(cbRefreshTokenClientProvider, times(1)).getCBRefreshTokenClient(eq(AzureEnvironment.AZURE.activeDirectoryEndpoint()));
}
 
Example #22
Source File: ManageSqlVirtualNetworkRules.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Main entry point.
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));


        ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
        RestClient restClient = new RestClient.Builder()
            .withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
            .withSerializerAdapter(new AzureJacksonAdapter())
            .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
            .withReadTimeout(150, TimeUnit.SECONDS)
            .withLogLevel(LogLevel.BODY)
            .withCredentials(credentials).build();
        Azure azure = Azure.authenticate(restClient, credentials.domain(), credentials.defaultSubscriptionId()).withDefaultSubscription();

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        runSample(azure);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example #23
Source File: BatchAIManager.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
* Creates an instance of BatchAIManager that exposes BatchAI resource management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the BatchAIManager
*/
public static BatchAIManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
    return new BatchAIManager(new RestClient.Builder()
        .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
        .withCredentials(credentials)
        .withSerializerAdapter(new AzureJacksonAdapter())
        .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
        .withInterceptor(new ProviderRegistrationInterceptor(credentials))
        .build(), subscriptionId);
}
 
Example #24
Source File: AzureSetup.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void validateAdlsFileSystem(CloudCredential credential, SpiFileSystem fileSystem) {
    Map<String, Object> credentialAttributes = credential.getParameters();
    CloudAdlsView cloudFileSystem = (CloudAdlsView) fileSystem.getCloudFileSystems().get(0);
    String clientSecret = String.valueOf(credentialAttributes.get(CloudAdlsView.CREDENTIAL_SECRET_KEY));
    String subscriptionId = String.valueOf(credentialAttributes.get(CloudAdlsView.SUBSCRIPTION_ID));
    String clientId = String.valueOf(credentialAttributes.get(CloudAdlsView.ACCESS_KEY));
    String tenantId = StringUtils.isEmpty(cloudFileSystem.getTenantId()) ? credential.getStringParameter(TENANT_ID) : cloudFileSystem.getTenantId();
    String accountName = cloudFileSystem.getAccountName();

    ApplicationTokenCredentials creds = new ApplicationTokenCredentials(clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
    DataLakeStoreAccountManagementClient adlsClient = new DataLakeStoreAccountManagementClientImpl(creds);
    adlsClient.withSubscriptionId(subscriptionId);
    PagedList<DataLakeStoreAccountBasic> dataLakeStoreAccountPagedList = adlsClient.accounts().list();
    boolean validAccountname = false;

    List<DataLakeStoreAccountBasic> dataLakeStoreAccountList = new ArrayList<>();
    while (dataLakeStoreAccountPagedList.hasNextPage()) {
        dataLakeStoreAccountList.addAll(dataLakeStoreAccountPagedList);
        dataLakeStoreAccountPagedList.loadNextPage();
    }

    for (DataLakeStoreAccountBasic account : dataLakeStoreAccountList) {
        if (account.name().equalsIgnoreCase(accountName)) {
            validAccountname = true;
            break;
        }
    }
    if (!validAccountname) {
        throw new CloudConnectorException("The provided file system account name does not belong to a valid ADLS account");
    }
}
 
Example #25
Source File: AuthFile.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
/**
 * Parses an auth file and read into an AuthFile object.
 * @param file the auth file to read
 * @return the AuthFile object created
 * @throws IOException thrown when the auth file or the certificate file cannot be read or parsed
 */
static AuthFile parse(File file) throws IOException {
    String content = Files.toString(file, Charsets.UTF_8).trim();

    AuthFile authFile;
    if (isJsonBased(content)) {
        authFile = ADAPTER.deserialize(content, AuthFile.class);
        Map<String, String> endpoints = ADAPTER.deserialize(content, new TypeToken<Map<String, String>>() { }.getType());
        authFile.environment.endpoints().putAll(endpoints);
    } else {
        // Set defaults
        Properties authSettings = new Properties();
        authSettings.put(CredentialSettings.AUTH_URL.toString(), AzureEnvironment.AZURE.activeDirectoryEndpoint());
        authSettings.put(CredentialSettings.BASE_URL.toString(), AzureEnvironment.AZURE.resourceManagerEndpoint());
        authSettings.put(CredentialSettings.MANAGEMENT_URI.toString(), AzureEnvironment.AZURE.managementEndpoint());
        authSettings.put(CredentialSettings.GRAPH_URL.toString(), AzureEnvironment.AZURE.graphEndpoint());
        authSettings.put(CredentialSettings.VAULT_SUFFIX.toString(), AzureEnvironment.AZURE.keyVaultDnsSuffix());

        // Load the credentials from the file
        StringReader credentialsReader = new StringReader(content);
        authSettings.load(credentialsReader);
        credentialsReader.close();

        authFile = new AuthFile();
        authFile.clientId = authSettings.getProperty(CredentialSettings.CLIENT_ID.toString());
        authFile.tenantId = authSettings.getProperty(CredentialSettings.TENANT_ID.toString());
        authFile.clientSecret = authSettings.getProperty(CredentialSettings.CLIENT_KEY.toString());
        authFile.clientCertificate = authSettings.getProperty(CredentialSettings.CLIENT_CERT.toString());
        authFile.clientCertificatePassword = authSettings.getProperty(CredentialSettings.CLIENT_CERT_PASS.toString());
        authFile.subscriptionId = authSettings.getProperty(CredentialSettings.SUBSCRIPTION_ID.toString());
        authFile.environment.endpoints().put(Endpoint.MANAGEMENT.identifier(), authSettings.getProperty(CredentialSettings.MANAGEMENT_URI.toString()));
        authFile.environment.endpoints().put(Endpoint.ACTIVE_DIRECTORY.identifier(), authSettings.getProperty(CredentialSettings.AUTH_URL.toString()));
        authFile.environment.endpoints().put(Endpoint.RESOURCE_MANAGER.identifier(), authSettings.getProperty(CredentialSettings.BASE_URL.toString()));
        authFile.environment.endpoints().put(Endpoint.GRAPH.identifier(), authSettings.getProperty(CredentialSettings.GRAPH_URL.toString()));
        authFile.environment.endpoints().put(Endpoint.KEYVAULT.identifier(), authSettings.getProperty(CredentialSettings.VAULT_SUFFIX.toString()));
    }
    authFile.authFilePath = file.getParent();

    return authFile;
}
 
Example #26
Source File: AzureConfigurableCoreImpl.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
protected RestClient buildRestClient(AzureTokenCredentials credentials, AzureEnvironment.Endpoint endpoint) {
    RestClient client =  restClientBuilder
            .withBaseUrl(credentials.environment(), endpoint)
            .withCredentials(credentials)
            .withInterceptor(new ResourceManagerThrottlingInterceptor())
            .build();
    if (client.httpClient().proxy() != null) {
        credentials.withProxy(client.httpClient().proxy());
    }
    return client;
}
 
Example #27
Source File: AzureTestCredentials.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
public AzureTestCredentials(final String mockUrl, String mockTenant, boolean isPlaybackMode) {
    super("", mockTenant, "", new AzureEnvironment(new HashMap<String, String>() {{
        put("managementEndpointUrl", mockUrl);
        put("resourceManagerEndpointUrl", mockUrl);
        put("sqlManagementEndpointUrl", mockUrl);
        put("galleryEndpointUrl", mockUrl);
        put("activeDirectoryEndpointUrl", mockUrl);
        put("activeDirectoryResourceId", mockUrl);
        put("activeDirectoryGraphResourceId", mockUrl);

    }}));
    this.isPlaybackMode = isPlaybackMode;
}
 
Example #28
Source File: TestBase.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
protected String baseUri() {
    if (this.baseUri != null) {
        return this.baseUri;
    } else {
        return AzureEnvironment.AZURE.url(AzureEnvironment.Endpoint.RESOURCE_MANAGER);
    }
}
 
Example #29
Source File: AzureCliSubscription.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
AzureEnvironment environment() {
    if (environmentName == null) {
        return null;
    } else if (environmentName.equalsIgnoreCase("AzureCloud")) {
        return AzureEnvironment.AZURE;
    } else if (environmentName.equalsIgnoreCase("AzureChinaCloud")) {
        return AzureEnvironment.AZURE_CHINA;
    } else if (environmentName.equalsIgnoreCase("AzureGermanCloud")) {
        return AzureEnvironment.AZURE_GERMANY;
    } else if (environmentName.equalsIgnoreCase("AzureUSGovernment")) {
        return AzureEnvironment.AZURE_US_GOVERNMENT;
    } else {
        return null;
    }
}
 
Example #30
Source File: AzureAccount.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public AzureTokenCredentials resolveCredentials() throws IOException {
  if (this.isAutoDiscovered()) {
    return AzureAccount.defaultCredentialProviderChain();
  } else {
    return new ApplicationTokenCredentials(
        clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
  }
}