Skip to content

Commit 56e774c

Browse files
authored
Merge pull request #6191 from PatrickFarley/consaf-qss
add java blocklist qs
2 parents f8b905c + 33ee824 commit 56e774c

File tree

3 files changed

+200
-0
lines changed

3 files changed

+200
-0
lines changed
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
---
2+
title: "Quickstart: Use a blocklist with Java"
3+
description: In this quickstart, get started using the Azure AI Content Safety Java SDK to create and use blocklists for text analysis.
4+
author: PatrickFarley
5+
manager: nitinme
6+
ms.service: azure-ai-content-safety
7+
ms.custom:
8+
ms.topic: include
9+
ms.date: 07/23/2025
10+
ms.author: pafarley
11+
---
12+
13+
[Reference documentation](/java/api/overview/azure/ai-contentsafety-readme) | [Library source code](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/contentsafety/azure-ai-contentsafety/src) | [Artifact (Maven)](https://central.sonatype.com/artifact/com.azure/azure-ai-contentsafety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/java/1.0.0)
14+
15+
## Prerequisites
16+
17+
* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/)
18+
* The current version of the [Java Development Kit (JDK)](https://www.microsoft.com/openjdk)
19+
* The [Gradle build tool](https://gradle.org/install/), or another dependency manager.
20+
* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**.
21+
* The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs.
22+
23+
## Set up application
24+
25+
Create a new Gradle project.
26+
27+
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
28+
29+
```console
30+
mkdir myapp && cd myapp
31+
```
32+
33+
Run the `gradle init` command from your working directory. This command will create essential build files for Gradle, including *build.gradle.kts*, which is used at runtime to create and configure your application.
34+
35+
```console
36+
gradle init --type basic
37+
```
38+
39+
When prompted to choose a **DSL**, select **Kotlin**.
40+
41+
42+
### Install the client SDK
43+
44+
This quickstart uses the Gradle dependency manager. You can find the client library and information for other dependency managers on the [Maven Central Repository](https://central.sonatype.com/artifact/com.azure/azure-ai-contentsafety).
45+
46+
Locate *build.gradle.kts* and open it with your preferred IDE or text editor. Then copy in the following build configuration. This configuration defines the project as a Java application whose entry point is the class **ContentSafetyBlocklistQuickstart**. It imports the Azure AI Content Safety library.
47+
48+
```kotlin
49+
plugins {
50+
java
51+
application
52+
}
53+
application {
54+
mainClass.set("ContentSafetyBlocklistQuickstart")
55+
}
56+
repositories {
57+
mavenCentral()
58+
}
59+
dependencies {
60+
implementation(group = "com.azure", name = "azure-ai-contentsafety", version = "1.0.0")
61+
}
62+
```
63+
64+
[!INCLUDE [Create environment variables](../env-vars.md)]
65+
66+
## Create and use a blocklist
67+
68+
From your working directory, run the following command to create a project source folder:
69+
70+
```console
71+
mkdir -p src/main/java
72+
```
73+
74+
Navigate to the new folder and create a file called *ContentSafetyBlocklistQuickstart.java*.
75+
76+
Open *ContentSafetyBlocklistQuickstart.java* in your preferred editor or IDE and paste in the following code. This code creates a new blocklist, adds items to it, and then analyzes a text string against the blocklist.
77+
78+
```java
79+
import com.azure.ai.contentsafety.*;
80+
81+
82+
import com.azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsOptions;
83+
import com.azure.ai.contentsafety.models.AddOrUpdateTextBlocklistItemsResult;
84+
import com.azure.ai.contentsafety.models.AnalyzeTextOptions;
85+
import com.azure.ai.contentsafety.models.AnalyzeTextResult;
86+
import com.azure.ai.contentsafety.models.RemoveTextBlocklistItemsOptions;
87+
import com.azure.ai.contentsafety.models.TextBlocklist;
88+
import com.azure.ai.contentsafety.models.TextBlocklistItem;
89+
import com.azure.ai.contentsafety.models.TextBlocklistMatch;
90+
import com.azure.core.credential.KeyCredential;
91+
import com.azure.core.exception.HttpResponseException;
92+
import com.azure.core.http.rest.PagedIterable;
93+
import com.azure.core.http.rest.RequestOptions;
94+
import com.azure.core.http.rest.Response;
95+
import com.azure.core.util.BinaryData;
96+
import com.azure.core.util.Configuration;
97+
98+
import java.util.HashMap;
99+
import java.util.Map;
100+
import java.util.List;
101+
import java.util.Arrays;
102+
import java.util.ArrayList;
103+
104+
public class ContentSafetyBlocklistQuickstart {
105+
public static void main(String[] args) {
106+
String endpoint = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_ENDPOINT");
107+
String key = Configuration.getGlobalConfiguration().get("CONTENT_SAFETY_KEY");
108+
109+
BlocklistClient blocklistClient = new BlocklistClientBuilder()
110+
.credential(new KeyCredential(key))
111+
.endpoint(endpoint).buildClient();
112+
113+
String blocklistName = "ProductSaleBlocklist";
114+
Map<String, String> description = new HashMap<>();
115+
description.put("description", "Contains terms related to the sale of a product.");
116+
BinaryData resource = BinaryData.fromObject(description);
117+
RequestOptions requestOptions = new RequestOptions();
118+
Response<BinaryData> response =
119+
blocklistClient.createOrUpdateTextBlocklistWithResponse(blocklistName, resource, requestOptions);
120+
if (response.getStatusCode() == 201) {
121+
System.out.println("\nBlocklist " + blocklistName + " created.");
122+
} else if (response.getStatusCode() == 200) {
123+
System.out.println("\nBlocklist " + blocklistName + " updated.");
124+
}
125+
126+
String blockItemText1 = "price";
127+
String blockItemText2 = "offer";
128+
List<TextBlocklistItem> blockItems = Arrays.asList(
129+
new TextBlocklistItem(blockItemText1).setDescription("Price word"),
130+
new TextBlocklistItem(blockItemText2).setDescription("Offer word")
131+
);
132+
AddOrUpdateTextBlocklistItemsResult addedBlockItems = blocklistClient.addOrUpdateBlocklistItems(blocklistName,
133+
new AddOrUpdateTextBlocklistItemsOptions(blockItems));
134+
if (addedBlockItems != null && addedBlockItems.getBlocklistItems() != null) {
135+
System.out.println("\nBlockItems added:");
136+
for (TextBlocklistItem addedBlockItem : addedBlockItems.getBlocklistItems()) {
137+
System.out.println("BlockItemId: " + addedBlockItem.getBlocklistItemId() + ", Text: " + addedBlockItem.getText() + ", Description: " + addedBlockItem.getDescription());
138+
}
139+
}
140+
141+
ContentSafetyClient contentSafetyClient = new ContentSafetyClientBuilder()
142+
.credential(new KeyCredential(key))
143+
.endpoint(endpoint).buildClient();
144+
AnalyzeTextOptions request = new AnalyzeTextOptions("You can order a copy now for the low price of $19.99.");
145+
request.setBlocklistNames(Arrays.asList(blocklistName));
146+
request.setHaltOnBlocklistHit(true);
147+
148+
AnalyzeTextResult analyzeTextResult;
149+
try {
150+
analyzeTextResult = contentSafetyClient.analyzeText(request);
151+
} catch (HttpResponseException ex) {
152+
System.out.println("Analyze text failed.\nStatus code: " + ex.getResponse().getStatusCode() + ", Error message: " + ex.getMessage());
153+
throw ex;
154+
}
155+
156+
if (analyzeTextResult.getBlocklistsMatch() != null) {
157+
System.out.println("\nBlocklist match result:");
158+
for (TextBlocklistMatch matchResult : analyzeTextResult.getBlocklistsMatch()) {
159+
System.out.println("BlocklistName: " + matchResult.getBlocklistName() + ", BlockItemId: " + matchResult.getBlocklistItemId() + ", BlockItemText: " + matchResult.getBlocklistItemText());
160+
}
161+
}
162+
}
163+
}
164+
165+
```
166+
167+
Optionally replace the blocklist name and items with your own.
168+
169+
Navigate back to the project root folder, and build the app with:
170+
171+
```console
172+
gradle build
173+
```
174+
175+
Then, run it with the `gradle run` command:
176+
177+
```console
178+
gradle run
179+
```
180+
181+
## Output
182+
183+
```console
184+
Blocklist ProductSaleBlocklist updated.
185+
186+
BlockItems added:
187+
BlockItemId: 6155969c-1589-4c27-8cb0-61758985b2d9, Text: price, Description: Price word
188+
BlockItemId: 0ca9ff49-d89b-4ecd-a451-28bd303342e1, Text: offer, Description: Offer word
189+
190+
Blocklist match result:
191+
BlocklistName: ProductSaleBlocklist, BlockItemId: 6155969c-1589-4c27-8cb0-61758985b2d9, BlockItemText: price
192+
```

articles/ai-services/content-safety/quickstart-blocklist.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ Get started using Azure AI Content Safety to create a custom text blocklist and
3737

3838
::: zone-end
3939

40+
::: zone pivot="programming-language-java"
41+
42+
[!INCLUDE [Java SDK quickstart](./includes/quickstarts/java-quickstart-blocklist.md)]
43+
44+
::: zone-end
45+
4046
::: zone pivot="programming-language-python"
4147

4248
[!INCLUDE [Python SDK quickstart](./includes/quickstarts/python-quickstart-blocklist.md)]

zone-pivots/zone-pivot-groups.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ groups:
110110
title: Foundry portal
111111
- id: programming-language-csharp
112112
title: C#
113+
- id: programming-language-java
114+
title: Java
113115
- id: programming-language-javascript
114116
title: JavaScript
115117
- id: programming-language-python

0 commit comments

Comments
 (0)