Integrate Azure Cognitive Services Text Analytics API in Java
Setup Authentication
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();
}
}