davidvera
davidvera

Reputation: 1489

Microsoft graph search feature Java

I'm trying to use Microsoft Graph to make a file search. I use this entry point : https://graph.microsoft.com/beta/search/query My application do not use a user account but a daemon with an application key (see auth method). And i send a built object.

My java code is rather simple :

public static void main(String[] args) throws Exception{

    try {
        // Authentication result containing token
        IAuthenticationResult result = getAccessTokenByClientCredentialGrant();
        String token = result.accessToken();

        SearchDocumentResponseModel documentQuery = fileGraphs.searchDocument(token, QUERYSTRING, 0, 25);
        System.out.println("Find a document" + documentQuery.toString());

    } catch(Exception ex){
        throw ex;
    }
}

private static IAuthenticationResult getAccessTokenByClientCredentialGrant() throws Exception {
    ConfidentialClientApplication app = ConfidentialClientApplication.builder(
            CONFIDENTIAL_CLIENT_ID,
            ClientCredentialFactory.createFromSecret(CONFIDENTIAL_CLIENT_SECRET))
            .authority(TENANT_SPECIFIC_AUTHORITY)
            .build();

    ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
            Collections.singleton(GRAPH_DEFAULT_SCOPE))
            .build();

    CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
    return future.get();
}

The SearchDocumentResponseModel is just a set of POJO that build for me the object that i must send as a request body.

{
  "requests":
     [{
        "entityTypes":["microsoft.graph.driveItem"],
        "query":{"query_string":{"query":"any query"}},
        "from":0,"size":25
      }]
 }

The method searchDocument is just here to build the object before i send it to the API

 public SearchDocumentResponseModel searchDocument(String accessToken, String stringSearch, int from, int size) throws IOException {
        SearchDocumentRequestModel searchRequest = new SearchDocumentRequestModel();
        // set values here
        ...
        URL url = new URL("https://graph.microsoft.com/beta/search/query");
        return requestsBuilder.buildPostRequest(accessToken, searchRequest, url)
  }

Now i want to send to server the Json and expect an answer :

public SearchDocumentResponseModel buildPostRequest(String accessToken, SearchDocumentRequestModel searchRequest, URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestProperty("Authorization", "Bearer " + accessToken);
    conn.setRequestProperty("Accept","application/json");
    conn.setRequestProperty("Content-Type","application/json; utf-8");
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    // write the input json in a string
    String jsonInputString = new Gson().toJson(searchRequest);
    try(OutputStream os = conn.getOutputStream()) {
        byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);
    }

    int httpResponseCode = conn.getResponseCode();
    String httpResponseMessage = conn.getResponseMessage();
    // reading the response
    try(BufferedReader br = new BufferedReader(
            new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
        StringBuilder response = new StringBuilder();
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }
        String outputResponse = response.toString();
        return new Gson().fromJson(outputResponse, SearchDocumentResponseModel.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

I think i set the properties correctly. Is it coming from my code or from Microsoft Graph ? Thanks !

Upvotes: 1

Views: 710

Answers (1)

Tony Ju
Tony Ju

Reputation: 15609

First of all, you should check if the access token is valid, you can send a request using postman.

enter image description here

enter image description here

If the token is valid, I think it should be the problem of your jsonInputString. The following code works fine.

URL url = new URL("https://graph.microsoft.com/beta/search/query");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization", "access_token" );
            conn.setRequestProperty("Accept","application/json");
            conn.setRequestProperty("Content-Type","application/json; utf-8");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            String str = "";
            str += "{";
            str += "  \"requests\": [";
            str += "    {";
            str += "      \"entityTypes\": [";
            str += "        \"microsoft.graph.driveItem\"";
            str += "      ],";
            str += "      \"query\": {";
            str += "        \"query_string\": {";
            str += "          \"query\": \"contoso\"";
            str += "        }";
            str += "      },";
            str += "      \"from\": 0,";
            str += "      \"size\": 25";
            str += "    }";
            str += "  ]";
            str += "}";
            OutputStream os = conn.getOutputStream();
            byte[] input = str.getBytes("UTF-8");
            os.write(input, 0, input.length);
            System.out.println(conn.getResponseCode()); 

Update:

Query api doesn't support client credential flow.

enter image description here

Upvotes: 1

Related Questions