使用 java azure 广告库将数据推送到 power bi

Push data into power bi using java azure ad library

我知道 java、azure ad 和 power bi,我想在这里使用 azure ad java 库 (ADAL) 测试将数据推送到 power bi 中:http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java

我创建了一个 netbeans 项目并使用了这段代码:http://innerdot.com/azure/authenticating-to-azure-resource-manager-using-java 并对其进行了测试,这样我就知道我拥有访问我的 azure 广告应用程序的所有权利。

在 Power BI 文档中,我们告诉您注册您的应用程序并获取身份验证令牌,这将帮助您使用 API 发送 GET/POST.. 请求

我使用了在 Github 上找到的示例代码。但是,按照 power bi apiary 文档中的示例,我得到了“403”或“404”http 响应状态。

 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 = "name.name@entity.com";
            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);
    }
}

感谢您的帮助。

据我所知,您代码中的端点仅用于 Azure 上的服务,不适用于 PowerBI。请关注 PowerBI 官方 document to set the endpoints for authenticating, and see the document Push data into a Power BI Dashboard 了解如何入门。

对于authenticating to PowerBI service,请根据您的需要注册需要不同身份验证的客户端应用或Web应用。

有个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.

希望对您有所帮助。

如有任何疑问,请随时告诉我。

在 C# 中测试并返回 java 后,我终于成功建立了连接并获得了有效令牌:

public class ApplicationAuth {


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

    username = "xxxx.xxxxx@company.com";
    credential = "************";
    clientId = "50xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

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

    try {
        service = Executors.newFixedThreadPool(1);           
        String url = "https://login.windows.net/common/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("https://analysis.windows.net/powerbi/api", cred, null);
        } else {
            future = context.acquireToken("https://analysis.windows.net/powerbi/api", clientId,
                    username, credential, null);

        }
        result = future.get();
    } catch (Exception ex) {
        System.out.println("Exception occurred:");
        ex.printStackTrace();
        System.exit(1);
    } finally {
        service.shutdown();
    }

    String body = null;
    String token = result.getAccessToken();
    try {

        DatasetsHandler datasetH = new DatasetsHandler();
        String data = "{\"name\": \"JavaDatasetTest\", \"tables\": " +
         "[{\"name\": \"Product\", \"columns\": " +
         "[{ \"name\": \"ProductID\", \"dataType\": \"Int64\"}, " +
         "{ \"name\": \"Name\", \"dataType\": \"string\"}, " +
         "{ \"name\": \"Category\", \"dataType\": \"string\"}," +
         "{ \"name\": \"IsCompete\", \"dataType\": \"bool\"}," +
         "{ \"name\": \"ManufacturedOn\", \"dataType\": \"DateTime\"}" +
         "]}]}";

        //datasetH.CreateDataset(data, token);   
        System.out.println("after creating dataset");
        body = datasetH.GetDatasets(token);
        String datasetID = datasetH.GetDatasetID(token);
        System.out.println("dataset ID: "+datasetID);    

        String rows = "{\"rows\":" +
        "[{\"ProductID\":1,\"Name\":\"Adjustable Race\",\"Category\":\"Components\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}," +
        "{\"ProductID\":2,\"Name\":\"LL Crankarm\",\"Category\":\"Components\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}," +
        "{\"ProductID\":3,\"Name\":\"HL Mountain Frame - Silver\",\"Category\":\"Bikes\",\"IsCompete\":true,\"ManufacturedOn\":\"07/30/2014\"}]}";

        String resu = datasetH.AddRows( datasetID, token, "Product", rows);

    }catch (Exception ex) {
        System.out.println(ex.toString());
        System.exit(1);
    }
   // System.out.println("body : "+body); //{"value":[]}
  }  

}

以下是我使用的方法:

public class DatasetsHandler {

public String powerBIDatasetsApiUrl = "https://api.powerbi.com/v1.0/myorg/datasets";

public String GetDatasets(String token) throws IOException{

    HttpRequests httpRequest = new HttpRequests();       
    HttpResponse response = httpRequest.HttpHeaderParams(token, powerBIDatasetsApiUrl, "GET", "");

    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();
    String body = sb.toString();

    return body;
}

public void CreateDataset(String data, String token) throws IOException{           

    HttpRequests httpRequest = new HttpRequests(); 
    HttpResponse response = httpRequest.HttpHeaderParams(token, powerBIDatasetsApiUrl, "POST", data);

    System.out.println("createDataset response: "+response.getStatusLine().getStatusCode());

    HttpEntity entity = response.getEntity();
    System.out.println("entity: "+entity);
    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();
    String body = sb.toString();

    System.out.println("created dataset");

}

public String GetDatasetID(String token) throws IOException{

    int id_count = 0;
    DatasetsHandler DatasetH = new DatasetsHandler();
    String result  = DatasetH.GetDatasets(token);

    JSONObject jObject = new JSONObject(result);
    JSONArray geodata = jObject.getJSONArray("value");

    for (int i = 0; i<geodata.length(); i++){
        try{
            JSONObject cdataset = geodata.getJSONObject(i);
            id_count = id_count +1;
        }catch (JSONException e) {
            // If id doesn't exist, this exception is thrown
        }
    }

    JSONObject cdataset = geodata.getJSONObject(id_count -1);
    String Id = cdataset.getString("id");
    System.out.println("get dataset name : "+cdataset.getString("name"));
    System.out.println("get dataset id : "+cdataset.getString("id"));
    return Id;
}

public String AddRows(String DatasetID, String token, String TableName, String rows) throws IOException{

    String url = "https://api.powerbi.com/v1.0/myorg/datasets/"+DatasetID+"/tables/"+TableName+"/rows";
    HttpRequests httpRequest = new HttpRequests(); 
    HttpResponse response = httpRequest.HttpHeaderParams(token, url, "POST", rows);

    System.out.println("Rows Added");
    return response.getEntity().toString();
}

}

还有 HttpHandelr:

public class HttpRequests {

public HttpRequestBase httpRequest;
public static Gson gson = new Gson();
public HttpResponse HttpHeaderParams (String token, String powerBIApiUrl, String method, String body) throws IOException {      

    final HttpClient httpClient = HttpClientBuilder.create().build();
    //JSONObject jsonObj = new JSONObject(body);
    StringEntity  dataset = new StringEntity(body);

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(5000)
            .setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000)
            .build();

    if("GET".equals(method)){
        httpRequest = new HttpGet(powerBIApiUrl);
    }else if("POST".equals(method)){
        System.out.println("===POST METHOD");
        httpRequest = new HttpPost(powerBIApiUrl);
        ((HttpPost)httpRequest).setEntity(dataset);
        System.out.println("get entity: "+((HttpPost)httpRequest).getEntity());
    }
    System.out.println("TOKEN: "+token);
    httpRequest.setConfig(requestConfig);
    httpRequest.addHeader("Authorization", "Bearer " + token);
    httpRequest.setHeader("Content-Type", "application/json"); 
    httpRequest.setHeader("ContentLength", "\""+body.length()+"\"");

    HttpResponse response = httpClient.execute(httpRequest);
    System.out.println("response: "+Arrays.toString(response.getAllHeaders()));
    System.out.println("response: "+response.getStatusLine().getStatusCode());
    return response;
   } 
}

希望对您有所帮助:)