Skip to content

Commit 8a95647

Browse files
[Samples][Java] Fix disparities of 15.handling-attachments sample (microsoft#3228)
* Changes for sample 15 * Remove unnecessary files * Fix error / improve message sending * Move methods around * Add corrections * Change header in line * Fix nit changes in README document Co-authored-by: matiasroldan6 <[email protected]>
1 parent 9aa5103 commit 8a95647

File tree

9 files changed

+82
-82
lines changed

9 files changed

+82
-82
lines changed

samples/java_springboot/15.handling-attachments/README.md

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,37 @@
11
# Handling Attachments
22

3-
Bot Framework v4 handling attachments bot sample
3+
Bot Framework v4 handling attachments bot sample.
44

55
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to send outgoing attachments and how to save attachments to disk.
66

77
> **NOTE: A specific example for Microsoft Teams, demonstrating how to
88
upload files to Teams from a bot and how to receive a file sent to a bot as an attachment, can be found [here](../56.teams-file-upload)**
99

10+
This sample is a Spring Boot app and uses the Azure CLI and azure-webapp Maven plugin to deploy to Azure.
11+
1012
## Prerequisites
1113

1214
- Java 1.8+
1315
- Install [Maven](https://maven.apache.org/)
1416
- An account on [Azure](https://azure.microsoft.com) if you want to deploy to Azure.
1517

16-
## To try this sample locally
18+
## To try this sample
1719
- From the root of this project folder:
1820
- Build the sample using `mvn package`
1921
- Run it by using `java -jar .\target\bot-attachments-sample.jar`
2022

21-
- Test the bot using Bot Framework Emulator
23+
## Testing the bot using Bot Framework Emulator
2224

23-
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
25+
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
2426

25-
- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
27+
- Install the latest Bot Framework Emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
2628

27-
- Connect to the bot using Bot Framework Emulator
29+
### Connect to the bot using Bot Framework Emulator
30+
- Launch Bot Framework Emulator
31+
- File -> Open Bot
32+
- Enter a Bot URL of `http://localhost:3978/api/messages`
2833

29-
- Launch Bot Framework Emulator
30-
- File -> Open Bot
31-
- Enter a Bot URL of `http://localhost:3978/api/messages`
34+
With the Bot Framework Emulator connected to your running bot, the sample will show you different types of attachments.
3235

3336
## Interacting with the bot
3437

@@ -42,7 +45,7 @@ As described on [Deploy your bot](https://docs.microsoft.com/en-us/azure/bot-ser
4245
### 1. Login to Azure
4346
From a command (or PowerShell) prompt in the root of the bot folder, execute:
4447
`az login`
45-
48+
4649
### 2. Set the subscription
4750
`az account set --subscription "<azure-subscription>"`
4851

@@ -62,10 +65,14 @@ Record the `appid` from the returned JSON
6265
Replace the values for `<appid>`, `<appsecret>`, `<botname>`, and `<groupname>` in the following commands:
6366

6467
#### To a new Resource Group
65-
`az deployment sub create --name "echoBotDeploy" --location "westus" --template-file ".\deploymentTemplates\template-with-new-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" botSku=S1 newAppServicePlanName="echoBotPlan" newWebAppName="echoBot" groupLocation="westus" newAppServicePlanLocation="westus"`
68+
```
69+
az deployment sub create --name "attachmentsBotDeploy" --location "westus" --template-file ".\deploymentTemplates\template-with-new-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" botSku=S1 newAppServicePlanName="attachmentsBotPlan" newWebAppName="attachmentsBot" groupLocation="westus" newAppServicePlanLocation="westus"
70+
```
6671

6772
#### To an existing Resource Group
68-
`az deployment group create --resource-group "<groupname>" --template-file ".\deploymentTemplates\template-with-preexisting-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" newWebAppName="echoBot" newAppServicePlanName="echoBotPlan" appServicePlanLocation="westus" --name "echoBot"`
73+
```
74+
az deployment group create --resource-group "<groupname>" --template-file ".\deploymentTemplates\template-with-preexisting-rg.json" --parameters appId="<appid>" appSecret="<appsecret>" botId="<botname>" newWebAppName="attachmentsBot" newAppServicePlanName="attachmentsBotPlan" appServicePlanLocation="westus" --name "attachmentsBot"
75+
```
6976

7077
### 5. Update app id and password
7178
In src/main/resources/application.properties update
@@ -74,7 +81,7 @@ In src/main/resources/application.properties update
7481

7582
### 6. Deploy the code
7683
- Execute `mvn clean package`
77-
- Execute `mvn azure-webapp:deploy -Dgroupname="<groupname>" -Dbotname="<botname>"`
84+
- Execute `mvn azure-webapp:deploy -Dgroupname="<groupname>" -Dbotname="<bot-app-service-name>"`
7885

7986
If the deployment is successful, you will be able to test it via "Test in Web Chat" from the Azure Portal using the "Bot Channel Registration" for the bot.
8087

@@ -83,9 +90,8 @@ After the bot is deployed, you only need to execute #6 if you make changes to th
8390

8491
## Further reading
8592

86-
- [Maven Plugin for Azure App Service](https://docs.microsoft.com/en-us/java/api/overview/azure/maven/azure-webapp-maven-plugin/readme?view=azure-java-stable)
93+
- [Maven Plugin for Azure App Service](https://github.com/microsoft/azure-maven-plugins/tree/develop/azure-webapp-maven-plugin)
8794
- [Spring Boot](https://spring.io/projects/spring-boot)
88-
- [Azure for Java cloud developers](https://docs.microsoft.com/en-us/azure/java/?view=azure-java-stable)
8995
- [Bot Framework Documentation](https://docs.botframework.com)
9096
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
9197
- [Attachments](https://docs.microsoft.com/en-us/azure/bot-service/nodejs/bot-builder-nodejs-send-receive-attachments?view=azure-bot-service-4.0)
@@ -94,4 +100,5 @@ After the bot is deployed, you only need to execute #6 if you make changes to th
94100
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
95101
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
96102
- [Azure Portal](https://portal.azure.com)
97-
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
103+
- [Azure for Java cloud developers](https://docs.microsoft.com/en-us/azure/java/?view=azure-java-stable)
104+
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)

samples/java_springboot/15.handling-attachments/src/main/java/com/microsoft/bot/sample/attachments/AttachmentsBot.java

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,13 @@
3232

3333
/**
3434
* This class implements the functionality of the Bot.
35+
*
36+
* Represents a bot that processes incoming activities.
37+
* For each user interaction, an instance of this class is created and the onTurn method is called.
38+
* This is a Transient lifetime service. Transient lifetime services are created
39+
* each time they're requested. For each Activity received, a new instance of this
40+
* class is created. Objects that are expensive to construct, or have a lifetime
41+
* beyond the single turn, should be carefully managed.
3542
*
3643
* <p>
3744
* This is where application specific logic for interacting with the users would be added. For this
@@ -41,20 +48,39 @@
4148
*/
4249
public class AttachmentsBot extends ActivityHandler {
4350

44-
@Override
45-
protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
46-
return processInput(turnContext)
47-
.thenCompose(turnContext::sendActivity)
48-
.thenCompose(resourceResponse -> displayOptions(turnContext));
49-
}
50-
5151
@Override
5252
protected CompletableFuture<Void> onMembersAdded(
5353
List<ChannelAccount> membersAdded,
5454
TurnContext turnContext
5555
) {
5656
return sendWelcomeMessage(turnContext);
5757
}
58+
59+
@Override
60+
protected CompletableFuture<Void> onMessageActivity(TurnContext turnContext) {
61+
return processInput(turnContext)
62+
// Respond to the user.
63+
.thenCompose(reply -> turnContext.sendActivities(MessageFactory.text("HI"), reply))
64+
.thenCompose(resourceResponse -> displayOptions(turnContext));
65+
}
66+
67+
private static CompletableFuture<Void> displayOptions(TurnContext turnContext) {
68+
// Create a HeroCard with options for the user to interact with the bot.
69+
HeroCard card = new HeroCard();
70+
card.setText("You can upload an image or select one of the following choices");
71+
72+
// Note that some channels require different values to be used in order to get buttons to display text.
73+
// In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
74+
// need to provide a value for other parameters like 'text' or 'displayText'.
75+
card.setButtons(
76+
new CardAction(ActionTypes.IM_BACK, "1. Inline Attachment", "1"),
77+
new CardAction(ActionTypes.IM_BACK, "2. Internet Attachment", "2"),
78+
new CardAction(ActionTypes.IM_BACK, "3. Uploaded Attachment", "3")
79+
);
80+
81+
Activity reply = MessageFactory.attachment(card.toAttachment());
82+
return turnContext.sendActivity(reply).thenApply(resourceResponse -> null);
83+
}
5884

5985
// Greet the user and give them instructions on how to interact with the bot.
6086
private CompletableFuture<Void> sendWelcomeMessage(TurnContext turnContext) {
@@ -74,23 +100,6 @@ private CompletableFuture<Void> sendWelcomeMessage(TurnContext turnContext) {
74100
.collect(CompletableFutures.toFutureList()).thenApply(resourceResponses -> null);
75101
}
76102

77-
private CompletableFuture<Void> displayOptions(TurnContext turnContext) {
78-
// Create a HeroCard with options for the user to interact with the bot.
79-
HeroCard card = new HeroCard();
80-
card.setText("You can upload an image or select one of the following choices");
81-
82-
// Note that some channels require different values to be used in order to get buttons to display text.
83-
// In this code the emulator is accounted for with the 'title' parameter, but in other channels you may
84-
// need to provide a value for other parameters like 'text' or 'displayText'.
85-
card.setButtons(
86-
new CardAction(ActionTypes.IM_BACK, "1. Inline Attachment", "1"),
87-
new CardAction(ActionTypes.IM_BACK, "2. Internet Attachment", "2"),
88-
new CardAction(ActionTypes.IM_BACK, "3. Uploaded Attachment", "3")
89-
);
90-
91-
Activity reply = MessageFactory.attachment(card.toAttachment());
92-
return turnContext.sendActivity(reply).thenApply(resourceResponse -> null);
93-
}
94103

95104
// Given the input from the message, create the response.
96105
private CompletableFuture<Activity> processInput(TurnContext turnContext) {
@@ -105,9 +114,10 @@ private CompletableFuture<Activity> processInput(TurnContext turnContext) {
105114
return handleOutgoingAttachment(turnContext, activity);
106115
}
107116

117+
// Returns a reply with the requested Attachment
108118
private CompletableFuture<Activity> handleOutgoingAttachment(TurnContext turnContext, Activity activity) {
119+
// Look at the user input, and figure out what kind of attachment to send.
109120
CompletableFuture<Activity> result;
110-
111121
if (activity.getText().startsWith("1")) {
112122
result = getInlineAttachment()
113123
.thenApply(attachment -> {
@@ -116,12 +126,9 @@ private CompletableFuture<Activity> handleOutgoingAttachment(TurnContext turnCon
116126
return reply;
117127
});
118128
} else if (activity.getText().startsWith("2")) {
119-
result = getInternetAttachment()
120-
.thenApply(attachment -> {
121-
Activity reply = MessageFactory.text("This is an attachment from a HTTP URL.");
122-
reply.setAttachment(attachment);
123-
return reply;
124-
});
129+
Activity reply = MessageFactory.text("This is an attachment from a HTTP URL.");
130+
reply.setAttachment(getInternetAttachment());
131+
result = CompletableFuture.completedFuture(reply);
125132
} else if (activity.getText().startsWith("3")) {
126133
// Get the uploaded attachment.
127134
result = getUploadedAttachment(
@@ -132,6 +139,7 @@ private CompletableFuture<Activity> handleOutgoingAttachment(TurnContext turnCon
132139
return reply;
133140
});
134141
} else {
142+
// The user did not enter input that this bot was built to handle.
135143
result = CompletableFuture.completedFuture(
136144
MessageFactory.text("Your input was not recognized please try again.")
137145
);
@@ -197,15 +205,7 @@ private CompletableFuture<Attachment> getInlineAttachment() {
197205
});
198206
}
199207

200-
// Creates an Attachment to be sent from the bot to the user from a HTTP URL.
201-
private CompletableFuture<Attachment> getInternetAttachment() {
202-
Attachment attachment = new Attachment();
203-
attachment.setName("architecture-resize.png");
204-
attachment.setContentType("image/png");
205-
attachment.setContentUrl("https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png");
206-
return CompletableFuture.completedFuture(attachment);
207-
}
208-
208+
// Creates an "Attachment" to be sent from the bot to the user from an uploaded file.
209209
private CompletableFuture<Attachment> getUploadedAttachment(TurnContext turnContext, String serviceUrl, String conversationId) {
210210
if (StringUtils.isEmpty(serviceUrl)) {
211211
return Async.completeExceptionally(new IllegalArgumentException("serviceUrl"));
@@ -238,6 +238,16 @@ private CompletableFuture<Attachment> getUploadedAttachment(TurnContext turnCont
238238
});
239239
});
240240
}
241+
242+
// Creates an Attachment to be sent from the bot to the user from a HTTP URL.
243+
private static Attachment getInternetAttachment() {
244+
// ContentUrl must be HTTPS.
245+
Attachment attachment = new Attachment();
246+
attachment.setName("architecture-resize.png");
247+
attachment.setContentType("image/png");
248+
attachment.setContentUrl("https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png");
249+
return attachment;
250+
}
241251

242252
private CompletableFuture<String> getEncodedFileData(String filename) {
243253
return getFileData(filename)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License. See License.txt in the project root for
3+
// license information.
4+
5+
/**
6+
* This package contains the classes for the handling attachments sample.
7+
*/
8+
package com.microsoft.bot.sample.attachments;

samples/java_springboot/15.handling-attachments/src/main/webapp/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<head>
55
<meta charset="utf-8">
66
<meta name="viewport" content="width=device-width, initial-scale=1">
7-
<title>EchoBot</title>
7+
<title>Handling Attachments Sample</title>
88
<style>
99
body {
1010
margin: 0px;

samples/java_springboot/15.handling-attachments/target/classes/application.properties

Lines changed: 0 additions & 3 deletions
This file was deleted.

samples/java_springboot/15.handling-attachments/target/classes/log4j2.json

Lines changed: 0 additions & 18 deletions
This file was deleted.

samples/java_springboot/15.handling-attachments/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst

Lines changed: 0 additions & 2 deletions
This file was deleted.

samples/java_springboot/15.handling-attachments/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

Lines changed: 0 additions & 2 deletions
This file was deleted.

0 commit comments

Comments
 (0)