|

|  How to Implement Azure Cognitive Services Text Analytics API in Java

How to Implement Azure Cognitive Services Text Analytics API in Java

October 31, 2024

Explore a step-by-step Java guide to integrating Azure Cognitive Services Text Analytics API, enhancing app capabilities with language processing features.

How to Implement Azure Cognitive Services Text Analytics API in Java

 

Integrate Azure Cognitive Services Text Analytics API in Java

 

  • First, ensure you have included the necessary dependencies in your project. The Azure Cognitive Services Text Analytics library should be added using Maven or Gradle.
  •  

  • For Maven projects, add the dependency to your `pom.xml`:
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-ai-textanalytics</artifactId>
        <version>5.2.0</version>
    </dependency>
    
  •  

  • For Gradle projects, add this to your `build.gradle`:
    implementation 'com.azure:azure-ai-textanalytics:5.2.0'
    

 

Setup Authentication

 

  • You'll need to authenticate with the Azure Text Analytics service using an API key. Here's how to set it up:
  •  

  • Set up your `TextAnalyticsClient` using the `TextAnalyticsClientBuilder` and your API key:
    import com.azure.ai.textanalytics.*;
    import com.azure.core.credential.AzureKeyCredential;
    
    public class TextAnalyticsExample {
        public static void main(String[] args) {
            String endpoint = "https://<your-text-analytics-resource>.cognitiveservices.azure.com/";
            String apiKey = "<your-api-key>";
    
            TextAnalyticsClient client = new TextAnalyticsClientBuilder()
                .credential(new AzureKeyCredential(apiKey))
                .endpoint(endpoint)
                .buildClient();
        }
    }
    

 

Perform Text Analysis

 

  • Now that the client is set up, you can perform various text analysis operations such as sentiment analysis, named entity recognition, and more.
  •  

  • Here’s an example to determine the sentiment of a given text:
    import com.azure.ai.textanalytics.models.DocumentSentiment;
    
    public class SentimentAnalysisExample {
        public static void main(String[] args) {
            // Assume client is initialized as shown earlier
            
            String text = "The hotel was clean and the staff was friendly.";
    
            DocumentSentiment documentSentiment = client.analyzeSentiment(text);
            System.out.printf("Document sentiment: %s%n", documentSentiment.getSentiment());
            documentSentiment.getSentences().forEach(sentenceSentiment ->
                System.out.printf("Sentence sentiment: %s%n", sentenceSentiment.getSentiment()));
        }
    }
    

 

Handle Exceptions and Errors

 

  • Implement error handling to manage potential issues like network errors or invalid input data.
  •  

  • Use try-catch blocks to capture and respond to `TextAnalyticsException` or any other runtime exceptions:
    import com.azure.ai.textanalytics.models.TextAnalyticsException;
    
    public class SafeTextAnalyticsExample {
        public static void main(String[] args) {
            try {
                // Assume client and text are already initialized
                
                client.analyzeSentiment(text);
            } catch (TextAnalyticsException e) {
                System.out.printf("Error Message: %s%n", e.getMessage());
                System.out.printf("Error Code: %s%n", e.getErrorCode());
            } catch (Exception e) {
                System.out.println("Unexpected error occurred: " + e);
            }
        }
    }
    

 

Optimize for Production

 

  • In a production environment, you should use Azure identity management for better security instead of just relying on API keys.
  •  

  • Monitor the performance and handle batch requests for large-scale applications to maintain efficiency and adhere to API rate limits.

 

import com.azure.identity.DefaultAzureCredentialBuilder;

// Example of setting up client with managed identity
public class ManagedIdentityClientExample {
    public static void main(String[] args) {
        TextAnalyticsClient client = new TextAnalyticsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint("https://<your-text-analytics-resource>.cognitiveservices.azure.com/")
            .buildClient();
    }
}