com.microsoft.windowsazure.exception.ServiceException Java Examples

The following examples show how to use com.microsoft.windowsazure.exception.ServiceException. 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: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException {
    boolean done = false;
    JobState jobState = null;
    while (!done) {
        // Sleep for 5 seconds
        Thread.sleep(5000);

        // Query the updated Job state
        jobState = mediaService.get(Job.get(jobId)).getState();
        System.out.println("Job state: " + jobState);

        if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
            done = true;
        }
    }
}
 
Example #2
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
public static void createAssetDeliveryPolicy(AssetInfo asset, ContentKeyInfo key) throws ServiceException {
    String acquisitionUrl = mediaService
            .create(ContentKey.getKeyDeliveryUrl(key.getId(), ContentKeyDeliveryType.PlayReadyLicense));

    Map<AssetDeliveryPolicyConfigurationKey, String> assetDeliveryPolicyConfiguration
        = new HashMap<AssetDeliveryPolicyConfigurationKey, String>();

    assetDeliveryPolicyConfiguration.put(AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl,
            acquisitionUrl);

    AssetDeliveryPolicyInfo assetDeliveryPolicy = mediaService.create(AssetDeliveryPolicy.create()
            .setName("PlayReady Smooth + Dash + HLS Asset Delivery Policy")
            .setAssetDeliveryConfiguration(assetDeliveryPolicyConfiguration)
            .setAssetDeliveryPolicyType(AssetDeliveryPolicyType.DynamicCommonEncryption)
            .setAssetDeliveryProtocol(EnumSet.of(AssetDeliveryProtocol.SmoothStreaming, AssetDeliveryProtocol.Dash, AssetDeliveryProtocol.HLS)));

    // Link the AssetDeliveryPolicy to the Asset
    mediaService.action(Asset.linkDeliveryPolicy(asset.getId(), assetDeliveryPolicy.getId()));

    System.out.println("Added Asset Delivery Policy: " + assetDeliveryPolicy.getName());
}
 
Example #3
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException {
    // Get the .ISM AssetFile
    ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
    AssetFileInfo streamingAssetFile = null;
    for (AssetFileInfo file : assetFiles) {
        if (file.getName().toLowerCase().endsWith(".ism")) {
            streamingAssetFile = file;
            break;
        }
    }

    AccessPolicyInfo originAccessPolicy;
    LocatorInfo originLocator = null;

    // Create a 30-day readonly AccessPolicy
    double durationInMinutes = 60 * 24 * 30;
    originAccessPolicy = mediaService.create(
            AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));

    // Create a Locator using the AccessPolicy and Asset
    originLocator = mediaService
            .create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));

    // Create a Smooth Streaming base URL
    return originLocator.getPath() + streamingAssetFile.getName() + "/manifest";
}
 
Example #4
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException {
    boolean done = false;
    JobState jobState = null;
    while (!done) {
        // Sleep for 5 seconds
        Thread.sleep(5000);

        // Query the updated Job state
        jobState = mediaService.get(Job.get(jobId)).getState();
        System.out.println("Job state: " + jobState);

        if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
            done = true;
        }
    }
}
 
Example #5
Source File: AzureConnector.java    From cloudml with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createHostedService(String hostedServiceName, String loc, String certPath) throws SAXException, InterruptedException, ExecutionException, TransformerException, ServiceException, URISyntaxException, ParserConfigurationException, IOException {
    //hosted service required for vm deployment
    HostedServiceCreateParameters createParameters = new HostedServiceCreateParameters();
    //required
    createParameters.setLabel(hostedServiceName);
    //required
    createParameters.setServiceName(hostedServiceName);
    createParameters.setDescription(hostedServiceName);

    //required
    String location="North Europe";
    if(!loc.equals(""))
        location=loc;

    createParameters.setLocation(location);
    OperationResponse hostedServiceOperationResponse = hostedServicesOperations.create(createParameters);

    uploadCerts(computeManagementClient,hostedServiceName,getCertData(certPath));
}
 
Example #6
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException {
    boolean done = false;
    JobState jobState = null;
    while (!done) {
        // Sleep for 5 seconds
        Thread.sleep(5000);

        // Query the updated Job state
        jobState = mediaService.get(Job.get(jobId)).getState();
        System.out.println("Job state: " + jobState);

        if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
            done = true;
        }
    }
}
 
Example #7
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException {
    // Get the .ISM AssetFile
    ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
    AssetFileInfo streamingAssetFile = null;
    for (AssetFileInfo file : assetFiles) {
        if (file.getName().toLowerCase().endsWith(".ism")) {
            streamingAssetFile = file;
            break;
        }
    }

    AccessPolicyInfo originAccessPolicy;
    LocatorInfo originLocator = null;

    // Create a 30-day readonly AccessPolicy
    double durationInMinutes = 60 * 24 * 30;
    originAccessPolicy = mediaService.create(
            AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));

    // Create a Locator using the AccessPolicy and Asset
    originLocator = mediaService
            .create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));

    // Create a Smooth Streaming base URL
    return originLocator.getPath() + streamingAssetFile.getName() + "/manifest";
}
 
Example #8
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
private static JobState checkJobStatus(String jobId) throws InterruptedException, ServiceException {
    boolean done = false;
    JobState jobState = null;
    while (!done) {
        // Sleep for 5 seconds
        Thread.sleep(5000);

        // Query the updated Job state
        jobState = mediaService.get(Job.get(jobId)).getState();
        System.out.println("Job state: " + jobState);

        if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
            done = true;
        }
    }

    return jobState;
}
 
Example #9
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException {
    // Get the .ISM AssetFile
    ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
    AssetFileInfo streamingAssetFile = null;
    for (AssetFileInfo file : assetFiles) {
        if (file.getName().toLowerCase().endsWith(".ism")) {
            streamingAssetFile = file;
            break;
        }
    }

    AccessPolicyInfo originAccessPolicy;
    LocatorInfo originLocator = null;

    // Create a 30-day readonly AccessPolicy
    double durationInMinutes = 60 * 24 * 30;
    originAccessPolicy = mediaService.create(
            AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));

    // Create a Locator using the AccessPolicy and Asset
    originLocator = mediaService
            .create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));

    // Create a Smooth Streaming base URL
    return originLocator.getPath() + streamingAssetFile.getName() + "/manifest(format=m3u8-aapl)";
}
 
Example #10
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException {
    boolean done = false;
    JobState jobState = null;
    while (!done) {
        // Sleep for 5 seconds
        Thread.sleep(5000);

        // Query the updated Job state
        jobState = mediaService.get(Job.get(jobId)).getState();
        System.out.println("Job state: " + jobState);

        if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
            done = true;
        }
    }
}
 
Example #11
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 6 votes vote down vote up
public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException {
    // Get the .ISM AssetFile
    ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
    AssetFileInfo streamingAssetFile = null;
    for (AssetFileInfo file : assetFiles) {
        if (file.getName().toLowerCase().endsWith(".ism")) {
            streamingAssetFile = file;
            break;
        }
    }

    AccessPolicyInfo originAccessPolicy;
    LocatorInfo originLocator = null;

    // Create a 30-day readonly AccessPolicy
    double durationInMinutes = 60 * 24 * 30;
    originAccessPolicy = mediaService.create(
            AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));

    // Create a Locator using the AccessPolicy and Asset
    originLocator = mediaService
            .create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));

    // Create a Smooth Streaming base URL
    return originLocator.getPath() + streamingAssetFile.getName() + "/manifest";
}
 
Example #12
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
    WritableBlobContainerContract uploader;
    AssetInfo resultAsset;
    AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an Asset
    resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
    System.out.println("Created Asset " + fileName);

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a Locator using the AccessPolicy and Asset
    uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    InputStream input = new FileInputStream(
            new File(Program.class.getClassLoader().getResource("").getPath() + fileName));

    System.out.println("Uploading " + fileName);

    // Upload the local file to the asset
    uploader.createBlockBlob(fileName, input);

    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return resultAsset;
}
 
Example #13
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
    WritableBlobContainerContract uploader;
    AssetInfo resultAsset;
    AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an Asset
    resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
    System.out.println("Created Asset " + fileName);

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a Locator using the AccessPolicy and Asset
    uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    InputStream input = new FileInputStream(
            new File(Program.class.getClassLoader().getResource("").getPath() + fileName));

    System.out.println("Uploading " + fileName);

    // Upload the local file to the asset
    uploader.createBlockBlob(fileName, input);

    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return resultAsset;
}
 
Example #14
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
public static void createAssetDeliveryPolicy(AssetInfo asset, ContentKeyInfo key) throws ServiceException {
    String acquisitionUrl = mediaService
            .create(ContentKey.getKeyDeliveryUrl(key.getId(), ContentKeyDeliveryType.PlayReadyLicense));
    String widevineUrl = mediaService
            .create(ContentKey.getKeyDeliveryUrl(key.getId(), ContentKeyDeliveryType.Widevine));

    Map<AssetDeliveryPolicyConfigurationKey, String> assetDeliveryPolicyConfiguration
        = new HashMap<AssetDeliveryPolicyConfigurationKey, String>();

    if (widevineUrl.contains("?")) {
        widevineUrl = widevineUrl.substring(0, widevineUrl.indexOf("?"));
    }

    assetDeliveryPolicyConfiguration.put(AssetDeliveryPolicyConfigurationKey.PlayReadyLicenseAcquisitionUrl,
            acquisitionUrl);
    assetDeliveryPolicyConfiguration.put(AssetDeliveryPolicyConfigurationKey.WidevineBaseLicenseAcquisitionUrl,
            widevineUrl);

    AssetDeliveryPolicyInfo assetDeliveryPolicy = mediaService.create(AssetDeliveryPolicy.create()
            .setName("PlayReady & Widevine Dash Asset Delivery Policy")
            .setAssetDeliveryConfiguration(assetDeliveryPolicyConfiguration)
            .setAssetDeliveryPolicyType(AssetDeliveryPolicyType.DynamicCommonEncryption)
            .setAssetDeliveryProtocol(EnumSet.of(AssetDeliveryProtocol.Dash)));

    // Link the AssetDeliveryPolicy to the Asset
    mediaService.action(Asset.linkDeliveryPolicy(asset.getId(), assetDeliveryPolicy.getId()));

    System.out.println("Added Asset Delivery Policy: " + assetDeliveryPolicy.getName());
}
 
Example #15
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
    WritableBlobContainerContract uploader;
    AssetInfo resultAsset;
    AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an Asset
    resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
    System.out.println("Created Asset " + fileName);

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a Locator using the AccessPolicy and Asset
    uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    InputStream input = new FileInputStream(
            new File(Program.class.getClassLoader().getResource("").getPath() + fileName));

    System.out.println("Uploading " + fileName);

    // Upload the local file to the asset
    uploader.createBlockBlob(fileName, input);

    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return resultAsset;
}
 
Example #16
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
public static void createAssetDeliveryPolicy(AssetInfo asset, ContentKeyInfo key) throws ServiceException {
    String acquisitionUrl = mediaService
            .create(ContentKey.getKeyDeliveryUrl(key.getId(), ContentKeyDeliveryType.BaselineHttp));

    byte[] randomKey = new byte[16];
    EncryptionUtils.eraseKey(randomKey);
    String envelopeEncryptionIV = Base64.encode(randomKey);

    Map<AssetDeliveryPolicyConfigurationKey, String> assetDeliveryPolicyConfiguration
            = new HashMap<AssetDeliveryPolicyConfigurationKey, String>();

    assetDeliveryPolicyConfiguration.put(
            AssetDeliveryPolicyConfigurationKey.EnvelopeKeyAcquisitionUrl, acquisitionUrl);
    assetDeliveryPolicyConfiguration.put(
            AssetDeliveryPolicyConfigurationKey.EnvelopeEncryptionIVAsBase64, envelopeEncryptionIV);

    AssetDeliveryPolicyInfo assetDeliveryPolicy = mediaService.create(AssetDeliveryPolicy.create()
            .setName("AES Smooth + Dash + HLS Asset Delivery Policy")
            .setAssetDeliveryConfiguration(assetDeliveryPolicyConfiguration)
            .setAssetDeliveryPolicyType(AssetDeliveryPolicyType.DynamicEnvelopeEncryption)
            .setAssetDeliveryProtocol(EnumSet.of(AssetDeliveryProtocol.SmoothStreaming, AssetDeliveryProtocol.Dash, AssetDeliveryProtocol.HLS)));

    // Link the AssetDeliveryPolicy to the Asset
    mediaService.action(Asset.linkDeliveryPolicy(asset.getId(), assetDeliveryPolicy.getId()));

    System.out.println("Added Asset Delivery Policy: " + assetDeliveryPolicy.getName());
}
 
Example #17
Source File: AzureSeedHostsProviderTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException, ServiceException {
    logger = LogManager.getLogger(this.getClass());

    ResourceId resourceId = new ResourceId();
    resourceId.setId("/subscriptions/xx/resourceGroups/my_resourcegroup/providers/Microsoft.Network/networkInterfaces/nic_dummy/ipConfigurations/Nic-IP-config");

    Subnet subnet = new Subnet();
    subnet.setIpConfigurations(CollectionUtils.asArrayList(resourceId));
    subnet.setName("mySubnet");

    VirtualNetworkOperations virtualNetworkOperations = mock(VirtualNetworkOperationsImpl.class);
    VirtualNetworkGetResponse virtualNetworkGetResponse = mock(VirtualNetworkGetResponse.class);
    final NetworkInterfaceOperations networkInterfaceOperations = mock(NetworkInterfaceOperationsImpl.class);
    NetworkInterfaceGetResponse networkInterfaceGetResponse = mock(NetworkInterfaceGetResponse.class);

    NetworkInterfaceIpConfiguration ipConfiguration = new NetworkInterfaceIpConfiguration();
    ipConfiguration.setPrivateIpAddress("10.0.0.4");

    NetworkInterface nic = new NetworkInterface();
    nic.setName("nic_dummy");
    nic.setIpConfigurations(CollectionUtils.asArrayList(ipConfiguration));

    VirtualNetwork virtualNetwork = new VirtualNetwork();
    virtualNetwork.setSubnets(CollectionUtils.asArrayList(subnet));

    when(virtualNetworkGetResponse.getVirtualNetwork()).thenReturn(virtualNetwork);
    when(providerClient.getVirtualNetworksOperations()).thenReturn(virtualNetworkOperations);
    when(virtualNetworkOperations.get(rgName, vnetName)).thenReturn(virtualNetworkGetResponse);

    when(providerClient.getNetworkInterfacesOperations()).thenReturn(networkInterfaceOperations);
    when(networkInterfaceOperations.get(rgName, "nic_dummy")).thenReturn(networkInterfaceGetResponse);
    when(networkInterfaceGetResponse.getNetworkInterface()).thenReturn(nic);
}
 
Example #18
Source File: AzureSeedHostsProviderTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleSubnet() throws IOException, ServiceException {
    List<String> networkAddresses = AzureSeedHostsProvider.listIPAddresses(providerClient, rgName, vnetName, "", "vnet",
                                                                           AzureSeedHostsProvider.HostType.PRIVATE_IP, logger);
    assertEquals(networkAddresses.size(), 1);
    assertEquals(networkAddresses.get(0), "10.0.0.4");

    List<String> networkAddresses2 = AzureSeedHostsProvider.listIPAddresses(providerClient, rgName, vnetName, "", "vnet",
                                                                            AzureSeedHostsProvider.HostType.PUBLIC_IP, logger);
    assertEquals(networkAddresses2.size(), 0);
}
 
Example #19
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
public static void createAssetDeliveryPolicy(AssetInfo asset, ContentKeyInfo key) throws ServiceException {
    String acquisitionUrl = mediaService
            .create(ContentKey.getKeyDeliveryUrl(key.getId(), ContentKeyDeliveryType.FairPlay));

    // The reason the below code replaces "https://" with "skd://" is because
    // in the IOS player sample code which you obtained in Apple developer account,
    // the player only recognizes a Key URL that starts with skd://.
    // However, if you are using a customized player,
    // you can choose whatever protocol you want.
    // For example, "https".
    acquisitionUrl = acquisitionUrl.replace("https://", "skd://");
    acquisitionUrl = acquisitionUrl.substring(0, acquisitionUrl.indexOf('?'));

    Map<AssetDeliveryPolicyConfigurationKey, String> assetDeliveryPolicyConfiguration
        = new HashMap<AssetDeliveryPolicyConfigurationKey, String>();

    assetDeliveryPolicyConfiguration.put(AssetDeliveryPolicyConfigurationKey.FairPlayBaseLicenseAcquisitionUrl,
            acquisitionUrl);
    assetDeliveryPolicyConfiguration.put(AssetDeliveryPolicyConfigurationKey.CommonEncryptionIVForCbcs, fairPlayIV);

    AssetDeliveryPolicyInfo assetDeliveryPolicy = mediaService.create(AssetDeliveryPolicy.create()
            .setName("FairPlay Asset Delivery Policy")
            .setAssetDeliveryConfiguration(assetDeliveryPolicyConfiguration)
            .setAssetDeliveryPolicyType(AssetDeliveryPolicyType.DynamicCommonEncryptionCbcs)
            .setAssetDeliveryProtocol(EnumSet.of(AssetDeliveryProtocol.HLS)));

    // Link the AssetDeliveryPolicy to the Asset
    mediaService.action(Asset.linkDeliveryPolicy(asset.getId(), assetDeliveryPolicy.getId()));

    System.out.println("Added Asset Delivery Policy: " + assetDeliveryPolicy.getName());
}
 
Example #20
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
    WritableBlobContainerContract uploader;
    AssetInfo resultAsset;
    AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an Asset
    resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
    System.out.println("Created Asset " + fileName);

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a Locator using the AccessPolicy and Asset
    uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    InputStream input = new FileInputStream(
            new File(Program.class.getClassLoader().getResource("").getPath() + fileName));

    System.out.println("Uploading " + fileName);

    // Upload the local file to the asset
    uploader.createBlockBlob(fileName, input);

    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return resultAsset;
}
 
Example #21
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 5 votes vote down vote up
private static void downloadAssetFiles(AssetInfo asset, String destinationPath) throws ServiceException, IOException {
    // Create destination directory if does not exist
    new File(destinationPath).mkdir();

    // Create an AccessPolicy that provides Read access for 15 minutes
    AccessPolicyInfo accessPolicy = mediaService
            .create(AccessPolicy.create("downloadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.READ)));

    // Create a SAS Locator using the AccessPolicy and Asset
    LocatorInfo sasLocator = mediaService
            .create(Locator.create(accessPolicy.getId(), asset.getId(), LocatorType.SAS));

    // List all the Asset Files
    ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));

    for (AssetFileInfo file : assetFiles) {
        System.out.print("Downloading " + file.getName() + " output file...");

        URL downloadUrl = new URL(sasLocator.getBaseUri() + "/" + file.getName() + sasLocator.getContentAccessToken());
        HttpURLConnection httpConn = (HttpURLConnection) downloadUrl.openConnection();
        InputStream inputStream = httpConn.getInputStream();
        Files.copy(inputStream, Paths.get(destinationPath, file.getName()), StandardCopyOption.REPLACE_EXISTING);
        inputStream.close();

        System.out.println("Done!");
    }

    // Clean up Locator and Access Policy
    mediaService.delete(Locator.delete(sasLocator.getId()));
    mediaService.delete(AccessPolicy.delete(accessPolicy.getId()));
}
 
Example #22
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    try {
        // Connect to Media Services API with service principal and client symmetric key
        AzureAdTokenCredentials credentials = new AzureAdTokenCredentials(
                tenant,
                new AzureAdClientSymmetricKey(clientId, clientKey),
                AzureEnvironments.AZURE_CLOUD_ENVIRONMENT);

        TokenProvider provider = new AzureAdTokenProvider(credentials, executorService);

        // create a new configuration with the new credentials
        Configuration configuration = MediaConfiguration.configureWithAzureAdTokenProvider(
                new URI(restApiEndpoint),
                provider);

        // create the media service provisioned with the new configuration
        mediaService = MediaService.create(configuration);

        System.out.println("Azure SDK for Java - FairPlay Dynamic Encryption Sample");

        // Upload a local file to a media asset.
        AssetInfo uploadAsset = uploadFileAndCreateAsset("Azure-Video.wmv");
        System.out.println("Uploaded Asset Id: " + uploadAsset.getId());

        // Transform the asset.
        AssetInfo encodedAsset = encode(uploadAsset);
        System.out.println("Encoded Asset Id: " + encodedAsset.getId());

        // Create the ContentKey
        ContentKeyInfo contentKeyInfo = createCommonCBCTypeContentKey(encodedAsset);
        System.out.println("Common Encryption Content Key: " + contentKeyInfo.getId());

        // Create the ContentKeyAuthorizationPolicy
        String tokenTemplateString = null;
        if (tokenRestriction) {
            tokenTemplateString = addTokenRestrictedAuthorizationPolicy(contentKeyInfo, tokenType);
        } else {
            addOpenAuthorizationPolicy(contentKeyInfo);
        }

        // Create the AssetDeliveryPolicy
        createAssetDeliveryPolicy(encodedAsset, contentKeyInfo);

        if (tokenTemplateString != null) {
            // Deserializes a string containing the XML representation of the TokenRestrictionTemplate
            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer
                    .deserialize(tokenTemplateString);

            // Generate a test token based on the the data in the given
            // TokenRestrictionTemplate.
            // Note: You need to pass the key id Guid because we specified
            // TokenClaim.ContentKeyIdentifierClaim in during the creation
            // of TokenRestrictionTemplate.
            UUID rawKey = UUID.fromString(contentKeyInfo.getId().substring("nb:kid:UUID:".length()));

            // Token expiration: 1-year
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            date.add(Calendar.YEAR, 1);

            // Generate token
            String testToken = TokenRestrictionTemplateSerializer.generateTestToken(tokenTemplate, null, rawKey,
                    date.getTime(), null);

            System.out.println(tokenTemplate.getTokenType().toString() + " Test Token: Bearer " + testToken);
        }

        // Create the Streaming Origin Locator
        String url = getStreamingOriginLocator(encodedAsset);

        System.out.println("Origin Locator Url: " + url);
        System.out.println("Sample completed!");

    } catch (ServiceException se) {
        System.out.println("ServiceException encountered.");
        System.out.println(se.toString());
    } catch (Exception e) {
        System.out.println("Exception encountered.");
        System.out.println(e.toString());
    } finally {
        executorService.shutdown();
    }
}
 
Example #23
Source File: AzureSeedHostsProviderTest.java    From crate with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultipleSubnet() throws IOException, ServiceException {
    ResourceId resourceId2 = new ResourceId();
    resourceId2.setId("/subscriptions/xx/resourceGroups/my_resourcegroup/providers/Microsoft.Network/networkInterfaces/nic_dummy2/ipConfigurations/Nic-IP-config");

    ResourceId resourceId3 = new ResourceId();
    resourceId3.setId("/subscriptions/xx/resourceGroups/my_resourcegroup/providers/Microsoft.Network/publicIPAddresses/ip_public1");

    Subnet subnet2 = new Subnet();
    subnet2.setIpConfigurations(CollectionUtils.asArrayList(resourceId2));
    subnet2.setName("mySubnet2");

    NetworkInterfaceGetResponse networkInterfaceGetResponse2 = mock(NetworkInterfaceGetResponse.class);
    PublicIpAddressOperations publicIpAddressOperations = mock(PublicIpAddressOperationsImpl.class);
    PublicIpAddressGetResponse publicIpAddressGetResponse = mock(PublicIpAddressGetResponse.class);

    NetworkInterfaceIpConfiguration ipConfiguration2 = new NetworkInterfaceIpConfiguration();
    ipConfiguration2.setPrivateIpAddress("10.0.0.5");

    ipConfiguration2.setPublicIpAddress(resourceId3);

    PublicIpAddress publicIpAddress = new PublicIpAddress();
    publicIpAddress.setIpAddress("33.33.33.33");

    NetworkInterface nic2 = new NetworkInterface();
    nic2.setName("nic_dummy2");
    nic2.setIpConfigurations(CollectionUtils.asArrayList(ipConfiguration2));

    providerClient.getVirtualNetworksOperations().get(rgName, vnetName).getVirtualNetwork().getSubnets().add(subnet2);

    when(providerClient.getNetworkInterfacesOperations().get(rgName, "nic_dummy2")).thenReturn(networkInterfaceGetResponse2);
    when(networkInterfaceGetResponse2.getNetworkInterface()).thenReturn(nic2);

    when(providerClient.getPublicIpAddressesOperations()).thenReturn(publicIpAddressOperations);
    when(publicIpAddressOperations.get(rgName, "ip_public1")).thenReturn(publicIpAddressGetResponse);
    when(publicIpAddressGetResponse.getPublicIpAddress()).thenReturn(publicIpAddress);

    List<String> networkAddresses = AzureSeedHostsProvider.listIPAddresses(providerClient, rgName, vnetName, subnetName, "subnet",
                                                                           AzureSeedHostsProvider.HostType.PRIVATE_IP, logger);
    assertEquals(networkAddresses.size(), 1);
    assertEquals(networkAddresses.get(0), "10.0.0.5");

    List<String> networkAddresses2 = AzureSeedHostsProvider.listIPAddresses(providerClient, rgName, vnetName, subnetName, "vnet",
                                                                            AzureSeedHostsProvider.HostType.PRIVATE_IP, logger);
    assertEquals(networkAddresses2.size(), 2);
    assertEquals(networkAddresses2.contains("10.0.0.5"), true);
    assertEquals(networkAddresses2.contains("10.0.0.4"), true);

    List<String> networkAddresses3 = AzureSeedHostsProvider.listIPAddresses(providerClient, rgName, vnetName, subnetName, "vnet",
                                                                            AzureSeedHostsProvider.HostType.PUBLIC_IP, logger);
    assertEquals(networkAddresses3.size(), 1);
    assertEquals(networkAddresses3.contains("33.33.33.33"), true);
    assertEquals(networkAddresses3.contains("10.0.0.5"), false);
    assertEquals(networkAddresses3.contains("10.0.0.4"), false);

}
 
Example #24
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    try {
        // Connect to Media Services API with service principal and client symmetric key
        AzureAdTokenCredentials credentials = new AzureAdTokenCredentials(
                tenant,
                new AzureAdClientSymmetricKey(clientId, clientKey),
                AzureEnvironments.AZURE_CLOUD_ENVIRONMENT);

        TokenProvider provider = new AzureAdTokenProvider(credentials, executorService);

        // create a new configuration with the new credentials
        Configuration configuration = MediaConfiguration.configureWithAzureAdTokenProvider(
                new URI(restApiEndpoint),
                provider);

        // create the media service provisioned with the new configuration
        mediaService = MediaService.create(configuration);

        System.out.println("Azure SDK for Java - PlayReady Dynamic Encryption Sample");

        // Upload a local file to a media asset.
        AssetInfo uploadAsset = uploadFileAndCreateAsset("Azure-Video.wmv");
        System.out.println("Uploaded Asset Id: " + uploadAsset.getId());

        // Transform the asset.
        AssetInfo encodedAsset = encode(uploadAsset);
        System.out.println("Encoded Asset Id: " + encodedAsset.getId());

        // Create the ContentKey
        ContentKeyInfo contentKeyInfo = createCommonTypeContentKey(encodedAsset);
        System.out.println("Common Encryption Content Key: " + contentKeyInfo.getId());

        // Create the ContentKeyAuthorizationPolicy
        String tokenTemplateString = null;
        if (tokenRestriction) {
            tokenTemplateString = addTokenRestrictedAuthorizationPolicy(contentKeyInfo, tokenType);
        } else {
            addOpenAuthorizationPolicy(contentKeyInfo);
        }

        // Create the AssetDeliveryPolicy
        createAssetDeliveryPolicy(encodedAsset, contentKeyInfo);

        if (tokenTemplateString != null) {
            // Deserializes a string containing the XML representation of the TokenRestrictionTemplate
            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer
                    .deserialize(tokenTemplateString);

            // Generate a test token based on the the data in the given
            // TokenRestrictionTemplate.
            // Note: You need to pass the key id Guid because we specified
            // TokenClaim.ContentKeyIdentifierClaim in during the creation
            // of TokenRestrictionTemplate.
            UUID rawKey = UUID.fromString(contentKeyInfo.getId().substring("nb:kid:UUID:".length()));

            // Token expiration: 1-year
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            date.add(Calendar.YEAR, 1);

            // Generate token
            String testToken = TokenRestrictionTemplateSerializer.generateTestToken(tokenTemplate, null, rawKey,
                    date.getTime(), null);

            System.out.println(tokenTemplate.getTokenType().toString() + " Test Token: Bearer " + testToken);
        }

        // Create the Streaming Origin Locator
        String url = getStreamingOriginLocator(encodedAsset);

        System.out.println("Origin Locator Url: " + url);
        System.out.println("Sample completed!");

    } catch (ServiceException se) {
        System.out.println("ServiceException encountered.");
        System.out.println(se.toString());
    } catch (Exception e) {
        System.out.println("Exception encountered.");
        System.out.println(e.toString());
    } finally {
        executorService.shutdown();
    }
}
 
Example #25
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
private static AssetInfo encode(AssetInfo assetToEncode)
        throws ServiceException, InterruptedException {
    // Retrieve the list of Media Processors that match the name
    ListResult<MediaProcessorInfo> mediaProcessors = mediaService
            .list(MediaProcessor.list().set("$filter", String.format("Name eq '%s'", preferedEncoder)));

    // Use the latest version of the Media Processor
    MediaProcessorInfo mediaProcessor = null;
    for (MediaProcessorInfo info : mediaProcessors) {
        if (null == mediaProcessor || info.getVersion().compareTo(mediaProcessor.getVersion()) > 0) {
            mediaProcessor = info;
        }
    }

    System.out.println("Using Media Processor: " + mediaProcessor.getName() + " " + mediaProcessor.getVersion());

    // Create a task with the specified Media Processor
    String outputAssetName = String.format("%s as %s", assetToEncode.getName(), encodingPreset);
    String taskXml = "<taskBody><inputAsset>JobInputAsset(0)</inputAsset>"
            + "<outputAsset assetCreationOptions=\"0\"" // AssetCreationOptions.None
            + " assetName=\"" + outputAssetName + "\">JobOutputAsset(0)</outputAsset></taskBody>";

    Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml)
            .setConfiguration(encodingPreset).setName("Encoding");

    /// Create the Job; this automatically schedules and runs it.
    Job.Creator jobCreator = Job.create()
            .setName(String.format("Encoding %s to %s", assetToEncode.getName(), encodingPreset))
            .addInputMediaAsset(assetToEncode.getId()).setPriority(2).addTaskCreator(task);
    JobInfo job = mediaService.create(jobCreator);

    String jobId = job.getId();
    System.out.println("Created Job with Id: " + jobId);

    // Check to see if the Job has completed
    checkJobStatus(jobId);
    // Done with the Job

    // Retrieve the output Asset
    ListResult<AssetInfo> outputAssets = mediaService.list(Asset.list(job.getOutputAssetsLink()));
    return outputAssets.get(0);
}
 
Example #26
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    try {
        // Connect to Media Services API with service principal and client symmetric key
        AzureAdTokenCredentials credentials = new AzureAdTokenCredentials(
                tenant,
                new AzureAdClientSymmetricKey(clientId, clientKey),
                AzureEnvironments.AZURE_CLOUD_ENVIRONMENT);

        TokenProvider provider = new AzureAdTokenProvider(credentials, executorService);

        // create a new configuration with the new credentials
        Configuration configuration = MediaConfiguration.configureWithAzureAdTokenProvider(
                new URI(restApiEndpoint),
                provider);

        // create the media service provisioned with the new configuration
        mediaService = MediaService.create(configuration);

        System.out.println("Azure SDK for Java - Media Analytics Sample (Indexer)");

        // Upload a local file to an Asset
        AssetInfo sourceAsset = uploadFileAndCreateAsset(mediaFileName);
        System.out.println("Uploaded Asset Id: " + sourceAsset.getId());

        // Create indexing task configuration based on parameters
        String indexerTaskPresetTemplate = new String(Files.readAllBytes(
                Paths.get(new URL(Program.class.getClassLoader().getResource(""), indexerTaskPresetTemplateFileName).toURI())));
        String taskConfiguration = String.format(indexerTaskPresetTemplate, title, description, language, captionFormats, generateAIB, generateKeywords);

        // Run indexing job to generate output asset
        AssetInfo outputAsset = runIndexingJob(sourceAsset, taskConfiguration);
        System.out.println("Output Asset Id: " + outputAsset.getId());

        // Download output asset files
        downloadAssetFiles(outputAsset, destinationPath);

        // Done
        System.out.println("Sample completed!");

    } catch (ServiceException se) {
        System.out.println("ServiceException encountered.");
        System.out.println(se.toString());
    } catch (Exception e) {
        System.out.println("Exception encountered.");
        System.out.println(e.toString());
    } finally {
        executorService.shutdown();
    }
}
 
Example #27
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
private static AssetInfo uploadFileAndCreateAsset(String fileName)
        throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
    WritableBlobContainerContract uploader;
    AssetInfo asset;
    AccessPolicyInfo uploadAccessPolicy;
    LocatorInfo uploadLocator = null;

    // Create an empty Asset
    asset = mediaService.create(Asset.create().setName(String.format("Media File %s", fileName)));
    System.out.println("Asset created " + asset.getName());

    // Create an AccessPolicy that provides Write access for 15 minutes
    uploadAccessPolicy = mediaService
            .create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));

    // Create a SAS Locator using the AccessPolicy and Asset
    uploadLocator = mediaService
            .create(Locator.create(uploadAccessPolicy.getId(), asset.getId(), LocatorType.SAS));

    // Create the Blob Writer using the Locator
    uploader = mediaService.createBlobWriter(uploadLocator);

    // The local file that will be uploaded to your Media Services account
    InputStream input = new FileInputStream(
            new File(Program.class.getClassLoader().getResource("").getPath() + fileName));

    System.out.println("Uploading " + fileName);

    // Upload the local file to the asset
    uploader.createBlockBlob(fileName, input);

    // Inform Media Services about the uploaded files
    mediaService.action(AssetFile.createFileInfos(asset.getId()));
    System.out.println("Uploaded Asset File " + fileName);

    // Delete the SAS Locator (and Access Policy) for the Asset since we are done uploading files
    mediaService.delete(Locator.delete(uploadLocator.getId()));
    mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));

    return asset;
}
 
Example #28
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
private static AssetInfo runIndexingJob(AssetInfo asset, String taskConfiguration)
        throws ServiceException, InterruptedException {
    // Retrieve the list of Media Processors that match the name
    ListResult<MediaProcessorInfo> mediaProcessors = mediaService
            .list(MediaProcessor.list().set("$filter", String.format("Name eq '%s'", indexerProcessorName)));

    // Use the latest version of the Media Processor
    MediaProcessorInfo mediaProcessor = null;
    for (MediaProcessorInfo info : mediaProcessors) {
        if (null == mediaProcessor || info.getVersion().compareTo(mediaProcessor.getVersion()) > 0) {
            mediaProcessor = info;
        }
    }

    System.out.println("Using Media Processor: " + mediaProcessor.getName() + " " + mediaProcessor.getVersion());

    // Create a task with the specified Media Processor
    String outputAssetName = String.format("Indexer Results %s", asset.getName());
    String taskXml = "<taskBody><inputAsset>JobInputAsset(0)</inputAsset>"
            + "<outputAsset assetCreationOptions=\"0\"" // AssetCreationOptions.None
            + " assetName=\"" + outputAssetName + "\">JobOutputAsset(0)</outputAsset></taskBody>";

    Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml)
            .setConfiguration(taskConfiguration).setName("Indexing Task");

    // Create the Job; this automatically schedules and runs it.
    Job.Creator jobCreator = Job.create()
            .setName("Indexing Job")
            .addInputMediaAsset(asset.getId()).setPriority(0).addTaskCreator(task);
    JobInfo job = mediaService.create(jobCreator);

    String jobId = job.getId();
    System.out.println("Created Job with Id: " + jobId);

    // Check to see if the Job has completed
    JobState result = checkJobStatus(jobId);

    // Done with the Job
    if (result != JobState.Finished) {
        System.out.println("The job has finished with a wrong status: " + result.toString());
        throw new RuntimeException();
    }

    System.out.println("Job Finished!");

    // Get the output Asset
    ListResult<AssetInfo> outputAssets = mediaService.list(Asset.list(job.getOutputAssetsLink()));
    AssetInfo outputAsset = outputAssets.get(0);

    System.out.println("Output asset: " + outputAsset.getName());

    return outputAsset;
}
 
Example #29
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
private static AssetInfo encode(AssetInfo assetToEncode)
        throws ServiceException, InterruptedException {
    // Retrieve the list of Media Processors that match the name
    ListResult<MediaProcessorInfo> mediaProcessors = mediaService
            .list(MediaProcessor.list().set("$filter", String.format("Name eq '%s'", preferedEncoder)));

    // Use the latest version of the Media Processor
    MediaProcessorInfo mediaProcessor = null;
    for (MediaProcessorInfo info : mediaProcessors) {
        if (null == mediaProcessor || info.getVersion().compareTo(mediaProcessor.getVersion()) > 0) {
            mediaProcessor = info;
        }
    }

    System.out.println("Using Media Processor: " + mediaProcessor.getName() + " " + mediaProcessor.getVersion());

    // Create a task with the specified Media Processor
    String outputAssetName = String.format("%s as %s", assetToEncode.getName(), encodingPreset);
    String taskXml = "<taskBody><inputAsset>JobInputAsset(0)</inputAsset>"
            + "<outputAsset assetCreationOptions=\"0\"" // AssetCreationOptions.None
            + " assetName=\"" + outputAssetName + "\">JobOutputAsset(0)</outputAsset></taskBody>";

    Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml)
            .setConfiguration(encodingPreset).setName("Encoding");

    // Create the Job; this automatically schedules and runs it.
    Job.Creator jobCreator = Job.create()
            .setName(String.format("Encoding %s to %s", assetToEncode.getName(), encodingPreset))
            .addInputMediaAsset(assetToEncode.getId()).setPriority(2).addTaskCreator(task);
    JobInfo job = mediaService.create(jobCreator);

    String jobId = job.getId();
    System.out.println("Created Job with Id: " + jobId);

    // Check to see if the Job has completed
    checkJobStatus(jobId);
    // Done with the Job

    // Retrieve the output Asset
    ListResult<AssetInfo> outputAssets = mediaService.list(Asset.list(job.getOutputAssetsLink()));
    return outputAssets.get(0);
}
 
Example #30
Source File: Program.java    From azure-sdk-for-media-services-java-samples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    try {
        // Setup Azure AD Service Principal Symmetric Key Credentials
        AzureAdTokenCredentials credentials = new AzureAdTokenCredentials(
                tenant,
                new AzureAdClientSymmetricKey(clientId, clientKey),
                AzureEnvironments.AZURE_CLOUD_ENVIRONMENT);

        TokenProvider provider = new AzureAdTokenProvider(credentials, executorService);

        // create a new configuration with the new credentials
        Configuration configuration = MediaConfiguration.configureWithAzureAdTokenProvider(
                new URI(restApiEndpoint),
                provider);

        // create the media service provisioned with the new configuration
        mediaService = MediaService.create(configuration);

        System.out.println("Azure SDK for Java - PlayReady & Widevine Dynamic Encryption Sample");

        // Upload a local file to a media asset.
        AssetInfo uploadAsset = uploadFileAndCreateAsset("Azure-Video.wmv");
        System.out.println("Uploaded Asset Id: " + uploadAsset.getId());

        // Transform the asset.
        AssetInfo encodedAsset = encode(uploadAsset);
        System.out.println("Encoded Asset Id: " + encodedAsset.getId());

        // Create the ContentKey
        ContentKeyInfo contentKeyInfo = createCommonTypeContentKey(encodedAsset);
        System.out.println("Common Encryption Content Key: " + contentKeyInfo.getId());

        // Create the ContentKeyAuthorizationPolicy
        String tokenTemplateString = null;
        if (tokenRestriction) {
            tokenTemplateString = addTokenRestrictedAuthorizationPolicy(contentKeyInfo, tokenType);
        } else {
            addOpenAuthorizationPolicy(contentKeyInfo);
        }

        // Create the AssetDeliveryPolicy
        createAssetDeliveryPolicy(encodedAsset, contentKeyInfo);

        if (tokenTemplateString != null) {
            // Deserializes a string containing the XML representation of the TokenRestrictionTemplate
            TokenRestrictionTemplate tokenTemplate = TokenRestrictionTemplateSerializer
                    .deserialize(tokenTemplateString);

            // Generate a test token based on the the data in the given
            // TokenRestrictionTemplate.
            // Note: You need to pass the key id Guid because we specified
            // TokenClaim.ContentKeyIdentifierClaim in during the creation
            // of TokenRestrictionTemplate.
            UUID rawKey = UUID.fromString(contentKeyInfo.getId().substring("nb:kid:UUID:".length()));

            // Token expiration: 1-year
            Calendar date = Calendar.getInstance();
            date.setTime(new Date());
            date.add(Calendar.YEAR, 1);

            // Generate token
            String testToken = TokenRestrictionTemplateSerializer.generateTestToken(tokenTemplate, null, rawKey,
                    date.getTime(), null);

            System.out.println(tokenTemplate.getTokenType().toString() + " Test Token: Bearer " + testToken);
        }

        // Create the Streaming Origin Locator
        String url = getStreamingOriginLocator(encodedAsset);

        System.out.println("Origin Locator Url: " + url);
        System.out.println("Sample completed!");

    } catch (ServiceException se) {
        System.out.println("ServiceException encountered.");
        System.out.println(se.toString());
    } catch (Exception e) {
        System.out.println("Exception encountered.");
        System.out.println(e.toString());
    } finally {
        executorService.shutdown();
    }
}