Search code examples
javaazurepowerbiadalazure-active-directory

Push data into power bi using java azure ad library


I am knew to java, azure ad and power bi and I want to test pushing data into power bi using the azure ad java library (ADAL) here : http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java

I've created a netbeans project and used this code : http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java and tested it so that I know I have all rights to access my azure ad application.

In the Power BI documentation, we tell you to register your app and get the authentication token which will help you use the API to send GET/POST.. requests

I used a sample code I found on Github. However, following the examples in the power bi apiary docs I get a "403" or "404" http reponse status.

 public class ApplicationAuthExample {

    private final static String AUTHORIZATION_ENDPOINT = "https://login.microsoftonline.com/";
    private final static String ARM_ENDPOINT = "https://management.azure.com/";
    private static final boolean DEV_MODE = true;

    public static void main(String[] args) throws Exception {
        String username = null;
        String credential = null;
        String tenantId = null;
        String clientId = null;
        String subscriptionId = null;

        if (DEV_MODE) {
            username = "[email protected]";
            credential = "******";
            clientId = "50xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            tenantId = "bbexxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            subscriptionId = "16bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        } else {
            if ((!args[0].equals("service-principal") && !args[0].equals("user"))
                    || (args[0].equals("user") && args.length != 6)
                    || (args[0].equals("service-principal") && args.length != 5)) {
                System.out.println("Usage:");
                System.out.println(" user <username> <password> <client id> <tenant id> <subscription id>");
                System.out.println(" service-principal <password> <client id> <tenant id> <subscription id>");
                System.exit(1);
            }
            int idx = 1;
            if (args[0].equals("user")) {
                username = args[idx++];
            }
            credential = args[idx++];
            clientId = args[idx++];
            tenantId = args[idx++];
            subscriptionId = args[idx++];
        }

        // use adal to Authenticate
        AuthenticationContext context = null;
        AuthenticationResult result = null;
        ExecutorService service = null;

        try {
            service = Executors.newFixedThreadPool(1);
            String url = AUTHORIZATION_ENDPOINT + tenantId + "/oauth2/authorize";
            context = new AuthenticationContext(url,
                    false,
                    service);
            Future<AuthenticationResult> future = null;
            if (username == null) {
                System.out.println("username = null");
                ClientCredential cred = new ClientCredential(clientId, credential);
                future = context.acquireToken(ARM_ENDPOINT, cred, null);
            } else {
                future = context.acquireToken(ARM_ENDPOINT, clientId,
                        username, credential, null);
            }
            result = future.get();
        } catch (Exception ex) {
            System.out.println("Exception occurred:");
            ex.printStackTrace();
            System.exit(1);
        } finally {
            service.shutdown();
        }

        // make a request to list available providers
        String url = ARM_ENDPOINT
                + "subscriptions/" + subscriptionId
                + "/providers"
                + "?api-version=2014-04-01-preview";
//        String url = "https://api.powerbi.com/v1.0/myorg/datasets";
        String body = null;
        try {
            //final HttpClient httpClient = new DefaultHttpClient();
            final HttpClient httpClient = HttpClientBuilder.create().build();
            //HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 10000);
             RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);
            System.out.println("url : "+url);
            httpGet.addHeader("Authorization", "Bearer " + result.getAccessToken());
           // httpGet.setHeader("Authorization", "Bearer " + result.getAccessToken());
//            System.out.println("token : "+result.getAccessToken());
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("status : "+statusCode);
            if(statusCode == 403){
                System.out.println(statusCode+": acces denied");
            }
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();

            StringBuilder sb = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(instream), 1000);
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sb.append(line);
            }
            instream.close();
            body = sb.toString();
        } catch (Exception ex) {
            System.out.println(ex.toString());
            System.exit(1);
        }

        System.out.println("body : "+body);
    }
}

Thank you for your help.


Solution

  • As I known, the endpoints in your code are only for service on Azure, not for PowerBI. Please follow the PowerBI offical document to set the endpoints for authenticating, and see the document Push data into a Power BI Dashboard to know how to get started.

    For authenticating to PowerBI service, please according to your needs to register a client app or a web app that needs different authentication.

    There is a sample which I searched in GitHub, that includes the code for getting access token for PowerBI authentication using Java, please see https://github.com/satalyst/powerbi-rest-java/blob/master/src/main/java/com/satalyst/powerbi/impl/Office365Authenticator.java.

    Hope it helps.

    Any concern, please feel free to let me know.