From c2d689c80a29d377a7ee9ffd7201f1b170790667 Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 10:44:23 -0500
Subject: [PATCH 001/354] Initial 56.teams-file-upload
---
pom.xml | 1 +
samples/56.teams-file-upload/LICENSE | 21 +
samples/56.teams-file-upload/README.md | 76 ++++
.../new-rg-parameters.json | 42 ++
.../preexisting-rg-parameters.json | 39 ++
.../template-with-new-rg.json | 191 ++++++++
.../template-with-preexisting-rg.json | 158 +++++++
.../56.teams-file-upload/files/teams-logo.png | Bin 0 -> 6412 bytes
samples/56.teams-file-upload/pom.xml | 315 +++++++++++++
.../sample/teamsfileupload/Application.java | 46 ++
.../teamsfileupload/TeamsFileUploadBot.java | 233 ++++++++++
.../src/main/resources/application.properties | 2 +
.../src/main/resources/log4j2.json | 18 +
.../src/main/webapp/META-INF/MANIFEST.MF | 3 +
.../src/main/webapp/WEB-INF/web.xml | 12 +
.../src/main/webapp/index.html | 418 ++++++++++++++++++
.../teamsfileupload/ApplicationTests.java | 19 +
.../teamsAppManifest/icon-color.png | Bin 0 -> 1229 bytes
.../teamsAppManifest/icon-outline.png | Bin 0 -> 383 bytes
.../teamsAppManifest/manifest.json | 38 ++
20 files changed, 1632 insertions(+)
create mode 100644 samples/56.teams-file-upload/LICENSE
create mode 100644 samples/56.teams-file-upload/README.md
create mode 100644 samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json
create mode 100644 samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json
create mode 100644 samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json
create mode 100644 samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json
create mode 100644 samples/56.teams-file-upload/files/teams-logo.png
create mode 100644 samples/56.teams-file-upload/pom.xml
create mode 100644 samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
create mode 100644 samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
create mode 100644 samples/56.teams-file-upload/src/main/resources/application.properties
create mode 100644 samples/56.teams-file-upload/src/main/resources/log4j2.json
create mode 100644 samples/56.teams-file-upload/src/main/webapp/META-INF/MANIFEST.MF
create mode 100644 samples/56.teams-file-upload/src/main/webapp/WEB-INF/web.xml
create mode 100644 samples/56.teams-file-upload/src/main/webapp/index.html
create mode 100644 samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
create mode 100644 samples/56.teams-file-upload/teamsAppManifest/icon-color.png
create mode 100644 samples/56.teams-file-upload/teamsAppManifest/icon-outline.png
create mode 100644 samples/56.teams-file-upload/teamsAppManifest/manifest.json
diff --git a/pom.xml b/pom.xml
index 488cdd1a5..b984ba6ea 100644
--- a/pom.xml
+++ b/pom.xml
@@ -379,6 +379,7 @@
samples/51.teams-messaging-extensions-actionsamples/52.teams-messaging-extensions-search-auth-configsamples/53.teams-messaging-extensions-action-preview
+ samples/56.teams-file-uploadsamples/57.teams-conversation-bot
diff --git a/samples/56.teams-file-upload/LICENSE b/samples/56.teams-file-upload/LICENSE
new file mode 100644
index 000000000..21071075c
--- /dev/null
+++ b/samples/56.teams-file-upload/LICENSE
@@ -0,0 +1,21 @@
+ MIT License
+
+ Copyright (c) Microsoft Corporation. All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/samples/56.teams-file-upload/README.md b/samples/56.teams-file-upload/README.md
new file mode 100644
index 000000000..c353aeb2b
--- /dev/null
+++ b/samples/56.teams-file-upload/README.md
@@ -0,0 +1,76 @@
+
+# Teams File Upload Bot
+
+Bot Framework v4 File Upload Bot sample for Teams.
+
+This bot has been created using [Bot Framework](https://dev.botframework.com). This sample shows
+how to incorporate basic conversational flow into a Teams application. It also illustrates a few of the Teams specific calls you can make from your bot.
+
+## Prerequisites
+
+- Microsoft Teams is installed and you have an account
+- [ngrok](https://ngrok.com/) or equivalent tunnelling solution
+
+## To try this sample
+
+> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
+the Teams service needs to call into the bot.
+
+1) Clone the repository
+
+ ```bash
+ git clone https://github.com/Microsoft/botbuilder-java.git
+ ```
+
+1) Run ngrok - point to port 8080
+
+ ```bash
+ ngrok http -host-header=rewrite 8080
+ ```
+
+1) Create [Bot Framework registration resource](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration) in Azure
+ - Use the current `https` URL you were given by running ngrok. Append with the path `/api/messages` used by this sample
+ - Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/en-us/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
+ - __*If you don't have an Azure account*__ you can use this [Bot Framework registration](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/create-a-bot-for-teams#register-your-web-service-with-the-bot-framework)
+
+1) Update the `resources/application.properties` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.)
+
+1) __*This step is specific to Teams.*__
+ - **Edit** the `manifest.json` contained in the `teamsAppManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `<>` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`)
+ - **Zip** up the contents of the `teamsAppManifest` folder to create a `manifest.zip`
+ - **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")
+
+1) From the root of this project folder:
+ - Build the sample using `mvn package`
+ - Unless done previously, install the packages in the local cache by using `mvn install`
+ - Run it by using `java -jar .\target\bot-teams-file-upload-sample.jar`
+
+
+## Interacting with the bot
+
+You can interact with this bot by sending it a message, or selecting a command from the command list. The bot will respond to the following strings.
+
+1. **Show Welcome**
+ - **Result:** The bot will send the welcome card for you to interact with
+ - **Valid Scopes:** personal, group chat, team chat
+2. **MentionMe**
+ - **Result:** The bot will respond to the message and mention the user
+ - **Valid Scopes:** personal, group chat, team chat
+3. **MessageAllMembers**
+ - **Result:** The bot will send a 1-on-1 message to each member in the current conversation (aka on the conversation's roster).
+ - **Valid Scopes:** personal, group chat, team chat
+
+You can select an option from the command list by typing ```@TeamsConversationBot``` into the compose message area and ```What can I do?``` text above the compose area.
+
+### Avoiding Permission-Related Errors
+
+You may encounter permission-related errors when sending a proactive message. This can often be mitigated by using `MicrosoftAppCredentials.TrustServiceUrl()`. See [the documentation](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0&tabs=csharp#avoiding-401-unauthorized-errors) for more information.
+
+## Deploy the bot to Azure
+
+To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
+
+## Further reading
+
+- [How Microsoft Teams bots work](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-basics-teams?view=azure-bot-service-4.0&tabs=javascript)
+
diff --git a/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json b/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json
new file mode 100644
index 000000000..ead339093
--- /dev/null
+++ b/samples/56.teams-file-upload/deploymentTemplates/new-rg-parameters.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupLocation": {
+ "value": ""
+ },
+ "groupName": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ },
+ "botId": {
+ "value": ""
+ },
+ "botSku": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "newAppServicePlanLocation": {
+ "value": ""
+ },
+ "newWebAppName": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json b/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json
new file mode 100644
index 000000000..b6f5114fc
--- /dev/null
+++ b/samples/56.teams-file-upload/deploymentTemplates/preexisting-rg-parameters.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ },
+ "botId": {
+ "value": ""
+ },
+ "botSku": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appServicePlanLocation": {
+ "value": ""
+ },
+ "existingAppServicePlan": {
+ "value": ""
+ },
+ "newWebAppName": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json b/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json
new file mode 100644
index 000000000..dcd6260a5
--- /dev/null
+++ b/samples/56.teams-file-upload/deploymentTemplates/template-with-new-rg.json
@@ -0,0 +1,191 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupLocation": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
+ }
+ },
+ "botId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
+ }
+ },
+ "botSku": {
+ "defaultValue": "F0",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "newAppServicePlanName": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "The name of the App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "P1v2",
+ "tier": "PremiumV2",
+ "size": "P1v2",
+ "family": "Pv2",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "newAppServicePlanLocation": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan. Defaults to \"westus\"."
+ }
+ },
+ "newWebAppName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
+ }
+ }
+ },
+ "variables": {
+ "resourcesLocation": "[deployment().location]",
+ "effectiveGroupLocation": "[if(empty(parameters('groupLocation')), variables('resourcesLocation'), parameters('groupLocation'))]",
+ "effectivePlanLocation": "[if(empty(parameters('newAppServicePlanLocation')), variables('resourcesLocation'), parameters('newAppServicePlanLocation'))]",
+ "appServicePlanName": "[if(empty(parameters('newAppServicePlanName')), concat(parameters('botId'), 'ServicePlan'), parameters('newAppServicePlanName'))]",
+ "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
+ "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
+ "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[variables('effectiveGroupLocation')]",
+ "properties": {
+ }
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan",
+ "type": "Microsoft.Web/serverfarms",
+ "name": "[variables('appServicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('effectivePlanLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('appServicePlanName')]",
+ "reserved":true
+ }
+ },
+ {
+ "comments": "Create a Web App using the new App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
+ ],
+ "name": "[variables('webAppName')]",
+ "properties": {
+ "name": "[variables('webAppName')]",
+ "serverFarmId": "[variables('appServicePlanName')]",
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "JAVA_OPTS",
+ "value": "-Dserver.port=80"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "apiVersion": "2017-12-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('botId')]",
+ "location": "global",
+ "kind": "bot",
+ "sku": {
+ "name": "[parameters('botSku')]"
+ },
+ "properties": {
+ "name": "[parameters('botId')]",
+ "displayName": "[parameters('botId')]",
+ "endpoint": "[variables('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "developerAppInsightsApplicationId": null,
+ "developerAppInsightKey": null,
+ "publishingCredentials": null,
+ "storageResourceId": null
+ },
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
+ ]
+ }
+ ],
+ "outputs": {}
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json b/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json
new file mode 100644
index 000000000..b790d2bdc
--- /dev/null
+++ b/samples/56.teams-file-upload/deploymentTemplates/template-with-preexisting-rg.json
@@ -0,0 +1,158 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Defaults to \"\"."
+ }
+ },
+ "botId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
+ }
+ },
+ "botSku": {
+ "defaultValue": "S1",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "newAppServicePlanName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The name of the new App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "P1v2",
+ "tier": "PremiumV2",
+ "size": "P1v2",
+ "family": "Pv2",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appServicePlanLocation": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "existingAppServicePlan": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Name of the existing App Service Plan used to create the Web App for the bot."
+ }
+ },
+ "newWebAppName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
+ }
+ }
+ },
+ "variables": {
+ "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",
+ "useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
+ "servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), if(empty(parameters('newAppServicePlanName')),concat(parameters('botId'), 'ServicePlan'),parameters('newAppServicePlanName')))]",
+ "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), resourceGroup().location, parameters('appServicePlanLocation'))]",
+ "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
+ "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
+ "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
+ },
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
+ "type": "Microsoft.Web/serverfarms",
+ "condition": "[not(variables('useExistingAppServicePlan'))]",
+ "name": "[variables('servicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('resourcesLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('servicePlanName')]",
+ "reserved":true
+ }
+ },
+ {
+ "comments": "Create a Web App using an App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2016-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms/', variables('servicePlanName'))]"
+ ],
+ "name": "[variables('webAppName')]",
+ "properties": {
+ "name": "[variables('webAppName')]",
+ "serverFarmId": "[variables('servicePlanName')]",
+ "siteConfig": {
+ "linuxFxVersion": "JAVA|8-jre8",
+ "appSettings": [
+ {
+ "name": "JAVA_OPTS",
+ "value": "-Dserver.port=80"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "apiVersion": "2017-12-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('botId')]",
+ "location": "global",
+ "kind": "bot",
+ "sku": {
+ "name": "[parameters('botSku')]"
+ },
+ "properties": {
+ "name": "[parameters('botId')]",
+ "displayName": "[parameters('botId')]",
+ "endpoint": "[variables('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "developerAppInsightsApplicationId": null,
+ "developerAppInsightKey": null,
+ "publishingCredentials": null,
+ "storageResourceId": null
+ },
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/samples/56.teams-file-upload/files/teams-logo.png b/samples/56.teams-file-upload/files/teams-logo.png
new file mode 100644
index 0000000000000000000000000000000000000000..78b0a0c308939206aee5f15e2c052def7a18a74e
GIT binary patch
literal 6412
zcmdT}XEa=GyC!uch!Q2b(PctHM2qr{(R&v)qD3&H4+ayjL5T9{83sWFqxVkKV3apn
zgc*!BM2p@z^R4sqth3hnb=EmQ_I}pdd+ldm`+n|y-S>4p(FS_zH22u<|?CF(CwP_XuBLjE!dz-$o$Juxo!-*-uYbH{{Z
zf-z!a>YX2V{c;bA|CRc6xdD`a0)CAoj>Pjf8GhSznB2E45PJ`>V9S20f@h0M9E
zbMDN7DU>+`gD5CgXz6bNA_0`QR8SOu^MWZl>3HA2{y?Yv6awI31>T~g{=a@3M^Eah
zZglnjag!2EXMZY;D%>y=^x=MOSMUtJ&FDU8L^uI|gq&8R3S
zB-W?B7G7p!{d77}m~#~Hhl7s#nqp({Vne69a<6&CTa;Zo67d4{<{45YyaPKHLgfCM
z;u+7E8}OmB)=N)@l%`5OK1h0kjF_2TgT@A0S%EpXh|O}`4!%EjY;a*+i*)vy)gUM<
z{%O-!tX$<>P@|YvK@o_$v
zYG*Y5@Bw{!-6z5#xk6VNw32$e~osPr)$zs2LDJ<
zn&xqZ6;|cC*>uik&c9~{b1Ti#|u-E!7J?cL_(IUx2aQxsHr*Pg-47(
zJOXGBm)SHk)g+^|PBBE0(y^@g=K&7+@TEutxOq`|eO_*7g=-OQkHskch~0ILrO_1FJF+#%qM5r+X-XirQRFQDx1bWRz5|$TH>EKmRrRD>*~yE>rHx=!j6tK
zsI^T$Po$`!YKZ8UIStQs;~|(y(~-1Q0~ePf5iUAx
zA6Xu#;uMl4&gy$N+yZ-J0~Nwo3*w?KYG~zS{&+iMG0dP}BnU#GYCjLqO_r8EpFr%ZBoPy#b&cr2L#YtDb3rqA>^`Y$Qy~6+XD74lEyvXNR?I~w
z8y6cdn81-0{JS`Jpt#gH+3Asp7&{R4^SkVT^RTDI`TnsK!CSlL`_@UDQl6Pvv%Gwl
zbbH-yI5K2%n`QLnML+Q}Bw0*IQR;Od9d9cwZV{8L6bxVDY=GYmPoK9yJqse#)nx`f
z&OzEQ%yAzI7&n6)MqtHsydXzb=7PHeE)qq)w~!Rk95@6aNKPEYZmlPd@2rwBMKN46?5_-6>#-)p9Z07wH8
zK62(;-PmBo!(@2-kLN7e^HI0yc%5Uy@CZI>Q(r>%i2(xxZN+~doUoiyDN)KJUT
zrys3;KSkc|J)E0usfV&J1h3r3-^=kU#3s!?K`7AX=$o3R4QCjSH<@VZ7f{m2l!xP!nk}SN4!(VrUZ4i&N`<@nAQ9vH&@!;H&?fFE|LdW3-xr{{NHZw
zmKC1gWq>w-Gz-#!KvW)LpXN}1i`8xq}S4?i|0=EEG(gs`iEeRDaH}c?-L*S7_)aORDW$oUF3XnN(o4Lt<=^AvXH@
zEA{hS*Xtn_hFV&0*Es~8Kd)UdVSko@yzZ&~e4=WfbAH@Fh8?_qo4JuN=z+xV{u*r+
zNtMuEn*ab&b^jRb)Rf}Pb2rRDtCw@vb2C$Hmb)Q`?xn5AcX#$qIU)_&IDz0@>h3|u
zIEVxiDk}dXn~O`2mSz|u^9+qE%W<+(%vq|Yv1Ep~q_!yf5mGCdi(;F1&X((F?^o8NHlBI@xXm*$T3!@Z^$vuy-&v_
z)_P>fdANq}R}@zOTqPu8tz+=_zXbe$8UG7idWuH2w>J;Ah#pV>pubv+LUf!=rnhpn
zC=F~WDq0aS56=e3GpUU_9=iASuO3*BXcQbk!1{vw(O;^O49Ij3vj
z?zdgkr;N~QZ!=z2WCqO*l4xwC{Rm@z<4=dIM|Al2$H$whtdppt5yV
zo_w@oMqi_Sps!FqP%ki5Zfs>!`Ksi85bl89_O&CwU-Y^bZZYirnG4*v?CkPt#m+tW
zG*zg=vG^OCaDHL`!opCRI<1RDkeG{OjkB1`>YkaH+v=XPB5Z|xBC~|cK^I2YAtL-?
zZcQeeAsA2qNfNHxS1KK*PWZCEsGe^<*Sw`r^>(7|_wg+2e#dEK2IpugdG-vEe1MRU
zq*cQqPNKm5XoZ`XWJjqL+iX2n0HZWpT`pdCAF+0S^@xOec2u9asM>rCC(Ili#PiB?
zQ*WKmcVqKoX82jt1nn>uABS7ZYx>KyD%%h)SE=@*PlJ%(C%=;_9F-7#W*
z-i`I~eA%C0q%)HRFTg9dJOM#XE48Htyq^2Od%ib4
zf7Q)s#U)#NKofktDSKY554+wCsbES|2JN;uqPb*)$^&L^2^j|=kzFH*(FF|)h);S_
zPRG~QKfMa$X-q2SYa2-xMZ_{ue4HB_^Y(TOYVcq&8zO6)BKY!iweZZ
z;?>+-F&FIXGm?@j@u45TQK*+C?_$R!&r`(%SW(xEWls&P
zXfc*wbIh7GiTpR9<^2be@-%3pdRQ-~u3JwA+p7f1Vaph81`k(SW|-mLOy>D@k?^(8
zQ#BWc(;NcwPjXHp)DL#5uB51(b`5rpOEpC8s$B~y)+ZqyMxsIEPHlfJVWtDC@@R^&
z2g}Ccuy*@D&2AfJ8!wPGhtqTE-(S|x&vi{jxn>IMq$yX)W{pX=H<5g=e`Ct08;~b=
zl{S4^v=`V6Apn1Jh*yTiL!3w_kh6O*Eb{ePi5=ocb%5q(=zBn?+CwxsM-?v;%g&Ez
zDo)h=x7jYfMb$e?L}rcB*aGPPZtItDh`pFaw*FajP&X>RsBVY9lS9mp(gv?TZn+t%
zPUR5}J3cNoh`h%hA53aFN1o4)H_T5RO*Qn1oj<`OZ*|D;ehZIMQuz#2PSs&{Zk${
zlS$QL>C4t#akDf))GG{Q-&zOW&*SB`_*gtBsmC_N?_hTRmk>_dW_IgPR5BW`zb(&?
zBiGyKrrs?~QKC+gYI0>RK4yXrpP1poLsx}BW@GG9hfE($7+EQWbG53<2~9%_FL9i>A_Tx9ay0cmt(S`Ecxv9v;%_TfCXLWW{WAQo
z0<$Kc$JV|h;murlS)nOCFQ890QNXO{mIyEA(`p{~eE|;Otxji#vj-h;H(d{Ua{$L0
zd)r2i|Fpj*%^c(3uQ4nk*Hl5oc=%B`!2YrZhD6bkr7QWN|4r#?ab5kYdxU%PBN>9W
zfZw|%m*%*rJC#~$-;Ef$6X}#O#)XCaRAecgq_KSWZZfqxn8J{j`;k(pL>M3M`=?f1
zig|LIRy=>9D%-c_6nqyJP@vhfKf0AUj)B^
zO$TayrJxs!cJdluPV0R#BFmz{)`&qvw%zRJPiKfC=iGOwc&pbaQzB<9=leBYq)Qu#
z@TE!^xe}^n98!$HB2Fm}+dromXvqjA_56bsURqj5UT((MxQu6rMswkkc)D;7v7rl>
zZQKFZUGt;PalSMC&T%?sqmHre^?y`GooU8v@nWjqEO43j79D{XYlLHt6elcJz>^xJ
zjCx$?TK$zsSsM{N_tNwAa{IZRLg*Vc)8edjw`;|hQLnekoO#!4uO`L|vjhD-=dY-A
zleN|;WFF9WWk~4aB%b71A3)=t_{idV9Q{2#u^q@DQaOZ!q{U#y7M_QMr*Fbf+wkqT
z9gA)v%WWV^N=h+1mnEmsr)7CG#4FvkbO6hXb|
z=DXqM7{Gt}PnrYPA#3PsDG&m1>#RO`utQL%5-BbKx!t1gvJ6-@kAiQrdCB|<89ck7E)DzMz;(U@>sa*11@JbrLIAxEZ5QjjljYQb(-EQ^s5oqj}pdC|$|5@if+
z*qrbLFYb{AMIMSyYrDO0=Z78l#&(P~!b4Z3ZFJqY(RxsT)(IV(IPkmJq`d-0u6B_L
zTv=>6L$Vx08@+uuv?Bn-R
z{TNK;VDcu#XwiQuy4E{j^R?mrUol+$a#8z*|E*Kyya9M*b_IS^2}7m)C|<|+K-3PD
zDPnN#kDVQ(xn$)oi3y6^-UDQpA_&p7+o;5`cPl(&Etj%X@LWv;U?1zPC-G=0BFn}9
zrKIrVQtX)NBfq|-D;mO&Rp$<4<3B`4gWsE1)Y+H9)@n=$uW%q
zO7*stJz**<%O%Tf<7B&o*OX>m+w`_?6*XQ7W{7&}-MN!os3#O!Q)egL=(-n2=o~gz
zpPdaiO>Li%<9-nonPi|vFZQ&f4;ji{aTV6H%Q%jr%lSzUkYQsBw#g#WumcryR`;=u
zY!sWtD87pja%-sxL@n?2p=SF+7mC>am|}*)?wa3!-Kh&a6KAoWlzsP%
z3vAb5@Y#fgoUenbtRJj{NQ>Ud)w0T@7#YG9|YKkh;9H_J|Tr(eS+43eCDsJ6cFmN
zLTSArir>G^^?#kya2Vo_3%WrG!iPgWKnu@M4I?_TM8ky#1;;90!t3}+=ddP~SFW^c*MobKCkc*(6;gg2Dc0l6O3)}t~q
zZ|14r6SzY!HjD4#1mcpgT9{<=+6)*=MtWIF%jDO(I21Jq;qe?rB_%~=yD?ni)11Io
zqx;O;o_g_InL%6s@aIk}rM1}#%vpGu!fMN&tnJI*q!g;znRMW}1GIKZVR-em8blBF
zC1iZ+kB@iG4%w!5swJnM9SIt9K0DLJxy9Qs8@A7_OlNOs6F>#vUB)+UoUk0&lFJA{`b%rJ1)=xF8m9gbQLMT0C8X1j(8kxz;~%^8uGv%W~hR
zhN>Uz33ugYyW`?QBexW^ZUI52EMoW{CS9_!f$vty7ECwCKl^E4H3>GIG=$vMRb`d7
zj^-J@pw>!ZNTVLcu2BWxMP6BzD4}y&Jp(P%)Fx|hb*n$WOGKBvkUR_2Q8p+#%`UX2
zl`?9Bu>g|xipW4WqA5|l6XbP*CXEV9d{o2K)s?5M@;JDMCV=Pw^ySF=N6@U7>6|(J
zn}LBChCJ-Fo%&0Ng{>IAg~|O!g&M{GTg&}FHw!M6L>f~9&lv2f$lDtfnyPw`a`5ZF
F{{vnI6G{L8
literal 0
HcmV?d00001
diff --git a/samples/56.teams-file-upload/pom.xml b/samples/56.teams-file-upload/pom.xml
new file mode 100644
index 000000000..cd8e24ee2
--- /dev/null
+++ b/samples/56.teams-file-upload/pom.xml
@@ -0,0 +1,315 @@
+
+
+
+ 4.0.0
+
+ com.microsoft.bot.sample
+ bot-teams-file-upload
+ sample
+ jar
+
+ ${project.groupId}:${project.artifactId}
+ This package contains a Java Teams File Upload sample using Spring Boot.
+ http://maven.apache.org
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.1.7.RELEASE
+
+
+
+
+
+ MIT License
+ http://www.opensource.org/licenses/mit-license.php
+
+
+
+
+
+ Bot Framework Development
+
+ Microsoft
+ https://dev.botframework.com/
+
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+ 1.8
+ 1.8
+ com.microsoft.bot.sample.teamsfileupload.Application
+ https://botbuilder.myget.org/F/botbuilder-v4-java-daily/maven/
+
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ 2.1.8.RELEASE
+ test
+
+
+
+ org.slf4j
+ slf4j-api
+
+
+ org.apache.logging.log4j
+ log4j-api
+ 2.11.0
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.11.0
+
+
+
+ com.microsoft.bot
+ bot-integration-spring
+ 4.0.0-SNAPSHOT
+ compile
+
+
+
+
+
+ MyGet
+ ${repo.url}
+
+
+
+
+
+ ossrh
+
+ https://oss.sonatype.org/
+
+
+
+
+
+
+ build
+
+ true
+
+
+
+
+ maven-compiler-plugin
+ 3.8.1
+
+ 1.8
+ 1.8
+
+
+
+ maven-war-plugin
+ 3.2.3
+
+ src/main/webapp
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ com.microsoft.bot.sample.teamsfileupload.Application
+
+
+
+
+
+ com.microsoft.azure
+ azure-webapp-maven-plugin
+ 1.7.0
+
+ V2
+ {groupname}
+ {botname}
+
+
+ JAVA_OPTS
+ -Dserver.port=80
+
+
+
+ linux
+ jre8
+ jre8
+
+
+
+
+ ${project.basedir}/target
+
+ *.jar
+
+
+
+
+
+
+
+ org.eluder.coveralls
+ coveralls-maven-plugin
+ 4.3.0
+
+ yourcoverallsprojectrepositorytoken
+
+
+
+ org.codehaus.mojo
+ cobertura-maven-plugin
+ 2.7
+
+ ../../cobertura-report/spring-teamsfileupload-sample
+ xml
+ 256m
+
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.7.1
+
+
+ org.apache.maven.plugins
+ maven-project-info-reports-plugin
+ 3.0.0
+
+
+
+
+
+
+
+ publish
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ org.sonatype.plugins
+ nexus-staging-maven-plugin
+ 1.6.8
+ true
+
+ true
+ ossrh
+ https://oss.sonatype.org/
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+
+
+ attach-sources
+
+ jar
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+
+ 8
+ false
+
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ 3.12.0
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 3.1.0
+
+
+
+ checkstyle
+
+
+
+
+
+
+
+
diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
new file mode 100644
index 000000000..3223c89f3
--- /dev/null
+++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
@@ -0,0 +1,46 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.microsoft.bot.sample.teamsfileupload;
+
+import com.microsoft.bot.integration.AdapterWithErrorHandler;
+import com.microsoft.bot.integration.BotFrameworkHttpAdapter;
+import com.microsoft.bot.integration.Configuration;
+import com.microsoft.bot.integration.spring.BotController;
+import com.microsoft.bot.integration.spring.BotDependencyConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Import;
+
+/**
+ * This is the starting point of the Sprint Boot Bot application.
+ *
+ * This class also provides overrides for dependency injections. A class that extends the
+ * {@link com.microsoft.bot.builder.Bot} interface should be annotated with @Component.
+ *
+ * @see TeamsConversationBot
+ */
+@SpringBootApplication
+
+// Use the default BotController to receive incoming Channel messages. A custom controller
+// could be used by eliminating this import and creating a new RestController. The default
+// controller is created by the Spring Boot container using dependency injection. The
+// default route is /api/messages.
+@Import({BotController.class})
+
+public class Application extends BotDependencyConfiguration {
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+ /**
+ * Returns a custom Adapter that provides error handling.
+ *
+ * @param configuration The Configuration object to use.
+ * @return An error handling BotFrameworkHttpAdapter.
+ */
+ @Override
+ public BotFrameworkHttpAdapter getBotFrameworkHttpAdaptor(Configuration configuration) {
+ return new AdapterWithErrorHandler(configuration);
+ }
+}
diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
new file mode 100644
index 000000000..6e8259584
--- /dev/null
+++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
@@ -0,0 +1,233 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.microsoft.bot.sample.teamsfileupload;
+
+import com.microsoft.bot.builder.MessageFactory;
+import com.microsoft.bot.builder.TurnContext;
+import com.microsoft.bot.builder.teams.TeamsActivityHandler;
+import com.microsoft.bot.schema.Activity;
+import com.microsoft.bot.schema.Attachment;
+import com.microsoft.bot.schema.ResultPair;
+import com.microsoft.bot.schema.Serialization;
+import com.microsoft.bot.schema.TextFormatTypes;
+import com.microsoft.bot.schema.teams.FileConsentCard;
+import com.microsoft.bot.schema.teams.FileConsentCardResponse;
+import com.microsoft.bot.schema.teams.FileDownloadInfo;
+import com.microsoft.bot.schema.teams.FileInfoCard;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * This class implements the functionality of the Bot.
+ *
+ *
This is where application specific logic for interacting with the users would be
+ * added. For this sample, the {@link #onMessageActivity(TurnContext)} echos the text
+ * back to the user. The {@link #onMembersAdded(List, TurnContext)} will send a greeting
+ * to new conversation participants.
Visit Azure
+ Bot Service to register your bot and add it to
+ various channels. The bot's endpoint URL typically looks
+ like this:
+
https://your_bots_hostname/api/messages
+
+
+
+
+
+
+
+
+
diff --git a/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
new file mode 100644
index 000000000..9b98c3963
--- /dev/null
+++ b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
@@ -0,0 +1,19 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.microsoft.bot.sample.teamsconversation;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class ApplicationTests {
+
+ @Test
+ public void contextLoads() {
+ }
+
+}
diff --git a/samples/56.teams-file-upload/teamsAppManifest/icon-color.png b/samples/56.teams-file-upload/teamsAppManifest/icon-color.png
new file mode 100644
index 0000000000000000000000000000000000000000..48a2de13303e1e8a25f76391f4a34c7c4700fd3d
GIT binary patch
literal 1229
zcmeAS@N?(olHy`uVBq!ia0vp^2_VeD1|%QND7OGojKx9jP7LeL$-D$|SkfJR9T^xl
z_H+M9WCe1|JzX3_D&pSWuFnWfl{x;g|9jrEYf8Vqrkk2Ba|%ol3OT){=#|7ID~|e{
zODQ{kU&ME#@`*-tm%Tukt_gFr+`F?$dx9wg-jad`^gsMn2_%Kh%WH91&SjKq5
zgkdI|!exdOVgw@>>=!Tjnk6q)zV*T8$FdgRFYC{kQ7``NOcl@R(_%_8e5e0E;>v0G
zEM9kb)2itgOTSfH7M=b3-S61B?PiazMdwXZwrS)^5UUS#HQjaoua5h_{Gx*_Zz|XK
z$tf0mZ&=tpf2!!Q)!A_l&o_$g*|JM$VZa~F^0{x1T{=QFu*x$`=V%~jUW=G`iqqp=lquB-`P{Qjw`=zEu3cMc_x7m2f#9m}uoFBMMQ^+%cOL)F_)N@JZ}Axoxi1y=
zeebq`y==e!nl+?cK-PhOec!3%|IupShHrcjW8sSt)F1>NW*{
zW%ljk2)nk%-}+F&?gi=7^$L#VeX3@kp%f{n}fR
z`}uZPx$IY~r8R5%gMlrc`jP!L3IloKFoq~sFFH5|cdklX=R08T)}71BhaN8$`AsNf0_
zq>WNhAtCd|-nBlTU=y5zl_vXlXZ~bkuaYENMp>3QSQ_#zuYZ+eQh*OIHRxP~s(}ic
zN2J4$u=AQcPt)|>F3zZLsjtP;Tajkugx;NcYED2~JVBlVO>{`uAY?Q4O|AA
z=16}CJieK^5P_TKnou!zGR`$!PUC)DqtkO;?!`p!+9v3lP_mu=%Vt3BkoWsq%;FN1sp58w*zfr-z^7tIb*q>!yncCjrzLuOk3N+d&~^Cxd|
z
Date: Tue, 7 Apr 2020 10:46:55 -0500
Subject: [PATCH 002/354] Corrected Invoke Activity reply type and
Serialization class now ignores unknown fields.
---
.../microsoft/bot/builder/ActivityHandler.java | 2 +-
.../com/microsoft/bot/builder/TurnContext.java | 11 +++++++++++
.../java/com/microsoft/bot/schema/Activity.java | 16 ++++++++++++++++
.../com/microsoft/bot/schema/Serialization.java | 2 ++
4 files changed, 30 insertions(+), 1 deletion(-)
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
index 649007f7b..f6414ffa9 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
@@ -69,7 +69,7 @@ public CompletableFuture onTurn(TurnContext turnContext) {
if (invokeResponse != null
&& turnContext.getTurnState().get(BotFrameworkAdapter.INVOKE_RESPONSE_KEY) == null) {
- Activity activity = new Activity(ActivityTypes.INVOKE);
+ Activity activity = new Activity(ActivityTypes.INVOKE_RESPONSE);
activity.setValue(invokeResponse);
return turnContext.sendActivity(activity);
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/TurnContext.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/TurnContext.java
index ad927589d..cc7a7a2a1 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/TurnContext.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/TurnContext.java
@@ -142,6 +142,17 @@ static CompletableFuture traceActivity(
*/
CompletableFuture sendActivity(Activity activity);
+ /**
+ * Sends an Activity to the sender of the incoming Activity without
+ * returning a ResourceResponse.
+ *
+ * @param activity The activity to send.
+ * @return A task that represents the work queued to execute.
+ */
+ default CompletableFuture sendActivityBlind(Activity activity) {
+ return sendActivity(activity).thenApply(aVoid -> null);
+ }
+
/**
* Sends a list of activities to the sender of the incoming activity.
*
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Activity.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Activity.java
index c8d789e7c..6a3336c93 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Activity.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Activity.java
@@ -771,6 +771,14 @@ public void setAttachments(List withAttachments) {
this.attachments = withAttachments;
}
+ /**
+ * Sets a single attachment on the Activity.
+ * @param withAttachment The Attachment object.
+ */
+ public void setAttachment(Attachment withAttachment) {
+ setAttachments(Collections.singletonList(withAttachment));
+ }
+
/**
* Returns payload version of the Entities in an Activity.
*
@@ -1194,6 +1202,14 @@ public Activity createTrace(String withName, Object withValue, String withValueT
return reply;
}
+ /**
+ * Creates a new message activity as a response to this activity.
+ * @return The new message activity.
+ */
+ public Activity createReply() {
+ return createReply(null, null);
+ }
+
/**
* Creates a new message activity as a response to this activity.
*
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Serialization.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Serialization.java
index 24d2cc444..cef69b0a5 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Serialization.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/Serialization.java
@@ -4,6 +4,7 @@
package com.microsoft.bot.schema;
import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -22,6 +23,7 @@ private Serialization() {
static {
objectMapper = new ObjectMapper();
+ objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.findAndRegisterModules();
}
From 9f934cc29cabe230ac039503098d25b9d414d4f3 Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 12:22:41 -0500
Subject: [PATCH 003/354] Finished 56.teams-file-upload
---
samples/56.teams-file-upload/README.md | 26 +++++--------------
.../sample/teamsfileupload/Application.java | 2 +-
.../teamsfileupload/TeamsFileUploadBot.java | 17 ++++++++++--
.../src/main/resources/application.properties | 4 +--
.../teamsfileupload/ApplicationTests.java | 2 +-
.../teamsAppManifest/manifest.json | 4 +--
6 files changed, 28 insertions(+), 27 deletions(-)
diff --git a/samples/56.teams-file-upload/README.md b/samples/56.teams-file-upload/README.md
index c353aeb2b..04d4a14e1 100644
--- a/samples/56.teams-file-upload/README.md
+++ b/samples/56.teams-file-upload/README.md
@@ -1,10 +1,10 @@
# Teams File Upload Bot
-Bot Framework v4 File Upload Bot sample for Teams.
+Bot Framework v4 file upload bot sample for Teams.
-This bot has been created using [Bot Framework](https://dev.botframework.com). This sample shows
-how to incorporate basic conversational flow into a Teams application. It also illustrates a few of the Teams specific calls you can make from your bot.
+This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to
+upload files to Teams from a bot and how to receive a file sent to a bot as an attachment.
## Prerequisites
@@ -46,25 +46,13 @@ the Teams service needs to call into the bot.
- Run it by using `java -jar .\target\bot-teams-file-upload-sample.jar`
-## Interacting with the bot
+## Interacting with the bot in Teams
-You can interact with this bot by sending it a message, or selecting a command from the command list. The bot will respond to the following strings.
+> Note this `manifest.json` specified that the bot will be installed in "personal" scope which is why you immediately entered a one on one chat conversation with the bot. Please refer to Teams documentation for more details.
-1. **Show Welcome**
- - **Result:** The bot will send the welcome card for you to interact with
- - **Valid Scopes:** personal, group chat, team chat
-2. **MentionMe**
- - **Result:** The bot will respond to the message and mention the user
- - **Valid Scopes:** personal, group chat, team chat
-3. **MessageAllMembers**
- - **Result:** The bot will send a 1-on-1 message to each member in the current conversation (aka on the conversation's roster).
- - **Valid Scopes:** personal, group chat, team chat
+Sending a message to the bot will cause it to respond with a card that will prompt you to upload a file. The file that's being uploaded is the `teams-logo.png` in the `Files` directory in this sample. The `Accept` and `Decline` events illustrated in this sample are specific to Teams. You can message the bot again to receive another prompt.
-You can select an option from the command list by typing ```@TeamsConversationBot``` into the compose message area and ```What can I do?``` text above the compose area.
-
-### Avoiding Permission-Related Errors
-
-You may encounter permission-related errors when sending a proactive message. This can often be mitigated by using `MicrosoftAppCredentials.TrustServiceUrl()`. See [the documentation](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0&tabs=csharp#avoiding-401-unauthorized-errors) for more information.
+You can also send a file to the bot as an attachment in the message compose section in Teams. This will be delivered to the bot as a Message Activity and the code in this sample fetches and saves the file.
## Deploy the bot to Azure
diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
index 3223c89f3..34143c488 100644
--- a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
+++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/Application.java
@@ -18,7 +18,7 @@
* This class also provides overrides for dependency injections. A class that extends the
* {@link com.microsoft.bot.builder.Bot} interface should be annotated with @Component.
*
- * @see TeamsConversationBot
+ * @see TeamsFileUploadBot
*/
@SpringBootApplication
diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
index 6e8259584..d6046deaf 100644
--- a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
+++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
@@ -15,6 +15,7 @@
import com.microsoft.bot.schema.teams.FileConsentCardResponse;
import com.microsoft.bot.schema.teams.FileDownloadInfo;
import com.microsoft.bot.schema.teams.FileInfoCard;
+import com.sun.corba.se.spi.orbutil.fsm.ActionBase;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@@ -46,10 +47,12 @@ public class TeamsFileUploadBot extends TeamsActivityHandler {
@Override
protected CompletableFuture onMessageActivity(TurnContext turnContext) {
if (messageWithDownload(turnContext.getActivity())) {
- return downloadAttachment(turnContext.getActivity().getAttachments().get(0))
+ Attachment attachment = turnContext.getActivity().getAttachments().get(0);
+ return downloadAttachment(attachment)
.thenCompose(result -> !result.result()
? fileDownloadFailed(turnContext, result.value())
- : CompletableFuture.completedFuture(null));
+ : fileDownloadCompleted(turnContext, attachment)
+ );
} else {
File filePath = new File("files", "teams-logo.png");
return sendFileCard(turnContext, filePath.getName(), filePath.length());
@@ -139,6 +142,16 @@ private CompletableFuture fileUploadFailed(TurnContext turnContext, String
return turnContext.sendActivityBlind(reply);
}
+ private CompletableFuture fileDownloadCompleted(TurnContext turnContext, Attachment attachment) {
+ Activity reply = MessageFactory.text(String.format(
+ "%s received and saved.",
+ attachment.getName()
+ ));
+ reply.setTextFormat(TextFormatTypes.XML);
+
+ return turnContext.sendActivityBlind(reply);
+ }
+
private CompletableFuture fileDownloadFailed(TurnContext turnContext, String error) {
Activity reply = MessageFactory.text("File download failed. Error:
" + error + "
");
reply.setTextFormat(TextFormatTypes.XML);
diff --git a/samples/56.teams-file-upload/src/main/resources/application.properties b/samples/56.teams-file-upload/src/main/resources/application.properties
index 1f5bdd6e8..a695b3bf0 100644
--- a/samples/56.teams-file-upload/src/main/resources/application.properties
+++ b/samples/56.teams-file-upload/src/main/resources/application.properties
@@ -1,2 +1,2 @@
-MicrosoftAppId=22e1d947-3a22-43b7-b665-3590b0f01af7
-MicrosoftAppPassword=#+)aQv{eb)C0^b;gph&w)fkg
+MicrosoftAppId=
+MicrosoftAppPassword=
diff --git a/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
index 9b98c3963..cdd838d56 100644
--- a/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
+++ b/samples/56.teams-file-upload/src/test/java/com/microsoft/bot/sample/teamsfileupload/ApplicationTests.java
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
-package com.microsoft.bot.sample.teamsconversation;
+package com.microsoft.bot.sample.teamsfileupload;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/samples/56.teams-file-upload/teamsAppManifest/manifest.json b/samples/56.teams-file-upload/teamsAppManifest/manifest.json
index 280f6951a..cd1708561 100644
--- a/samples/56.teams-file-upload/teamsAppManifest/manifest.json
+++ b/samples/56.teams-file-upload/teamsAppManifest/manifest.json
@@ -2,7 +2,7 @@
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
"manifestVersion": "1.5",
"version": "1.0",
- "id": "22e1d947-3a22-43b7-b665-3590b0f01af7",
+ "id": "<>",
"packageName": "com.microsoft.teams.fileupload",
"developer": {
"name": "Microsoft Corp",
@@ -25,7 +25,7 @@
"accentColor": "#abcdef",
"bots": [
{
- "botId": "22e1d947-3a22-43b7-b665-3590b0f01af7",
+ "botId": "<>",
"scopes": [
"personal"
],
From 74f0fdd40d2810b14928c8c686fc464a76edbe3c Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 13:26:08 -0500
Subject: [PATCH 004/354] Removed unused import
---
.../microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java | 1 -
1 file changed, 1 deletion(-)
diff --git a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
index d6046deaf..96f86b2b7 100644
--- a/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
+++ b/samples/56.teams-file-upload/src/main/java/com/microsoft/bot/sample/teamsfileupload/TeamsFileUploadBot.java
@@ -15,7 +15,6 @@
import com.microsoft.bot.schema.teams.FileConsentCardResponse;
import com.microsoft.bot.schema.teams.FileDownloadInfo;
import com.microsoft.bot.schema.teams.FileInfoCard;
-import com.sun.corba.se.spi.orbutil.fsm.ActionBase;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
From 849a4335f4229704b6deaf3a1160ef1055ab83b4 Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 15:28:49 -0500
Subject: [PATCH 005/354] Now returning the InvokeResponse
---
.../bot/builder/teams/TeamsActivityHandler.java | 10 +++++++---
.../bot/integration/BotFrameworkHttpAdapter.java | 6 +++---
.../bot/integration/spring/BotController.java | 2 ++
.../java/com/microsoft/bot/schema/CardImage.java | 15 +++++++++++++++
.../schema/teams/MessagingExtensionResponse.java | 8 ++++++++
.../schema/teams/MessagingExtensionResult.java | 11 +++++++++++
6 files changed, 46 insertions(+), 6 deletions(-)
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/teams/TeamsActivityHandler.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/teams/TeamsActivityHandler.java
index 3f1a31866..0d9c407ec 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/teams/TeamsActivityHandler.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/teams/TeamsActivityHandler.java
@@ -504,13 +504,17 @@ protected CompletableFuture onTeamsTeamRenamed(
return CompletableFuture.completedFuture(null);
}
- private CompletableFuture notImplemented() {
+ protected CompletableFuture notImplemented() {
+ return notImplemented(null);
+ }
+
+ protected CompletableFuture notImplemented(String body) {
CompletableFuture result = new CompletableFuture<>();
- result.completeExceptionally(new InvokeResponseExcetion(HttpURLConnection.HTTP_NOT_IMPLEMENTED));
+ result.completeExceptionally(new InvokeResponseExcetion(HttpURLConnection.HTTP_NOT_IMPLEMENTED, body));
return result;
}
- private CompletableFuture withException(Throwable t) {
+ protected CompletableFuture withException(Throwable t) {
CompletableFuture result = new CompletableFuture<>();
result.completeExceptionally(new CompletionException(t));
return result;
diff --git a/libraries/bot-integration-core/src/main/java/com/microsoft/bot/integration/BotFrameworkHttpAdapter.java b/libraries/bot-integration-core/src/main/java/com/microsoft/bot/integration/BotFrameworkHttpAdapter.java
index 7bf542ba7..810ea0486 100644
--- a/libraries/bot-integration-core/src/main/java/com/microsoft/bot/integration/BotFrameworkHttpAdapter.java
+++ b/libraries/bot-integration-core/src/main/java/com/microsoft/bot/integration/BotFrameworkHttpAdapter.java
@@ -5,6 +5,7 @@
import com.microsoft.bot.builder.Bot;
import com.microsoft.bot.builder.BotFrameworkAdapter;
+import com.microsoft.bot.builder.InvokeResponse;
import com.microsoft.bot.connector.authentication.ChannelProvider;
import com.microsoft.bot.connector.authentication.ChannelValidation;
import com.microsoft.bot.connector.authentication.CredentialProvider;
@@ -66,8 +67,7 @@ public BotFrameworkHttpAdapter(CredentialProvider withCredentialProvider,
* @param bot A Bot.
* @return A CompletableFuture.
*/
- public CompletableFuture processIncomingActivity(String authHeader, Activity activity, Bot bot) {
- return processActivity(authHeader, activity, bot::onTurn)
- .thenApply(invokeResponse -> null);
+ public CompletableFuture processIncomingActivity(String authHeader, Activity activity, Bot bot) {
+ return processActivity(authHeader, activity, bot::onTurn);
}
}
diff --git a/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java b/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
index a19ad992e..cd450f0b8 100644
--- a/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
+++ b/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
@@ -79,6 +79,8 @@ public CompletableFuture> incoming(
.handle((result, exception) -> {
if (exception == null) {
+ if (result != null)
+ return new ResponseEntity<>(result.getBody(), HttpStatus.valueOf(result.getStatus()));
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/CardImage.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/CardImage.java
index 74a7b82c8..96940221e 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/CardImage.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/CardImage.java
@@ -31,6 +31,21 @@ public class CardImage {
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private CardAction tap;
+ /**
+ * Creates a new CardImage.
+ */
+ public CardImage() {
+
+ }
+
+ /**
+ * Creates a new CardImage with an initial URL.
+ * @param withUrl The URL for the image.
+ */
+ public CardImage(String withUrl) {
+ setUrl(withUrl);
+ }
+
/**
* Get the url value.
*
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResponse.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResponse.java
index 5f4d94661..93c800cbf 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResponse.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResponse.java
@@ -12,6 +12,14 @@ public class MessagingExtensionResponse {
@JsonProperty(value = "composeExtension")
private MessagingExtensionResult composeExtension;
+ /**
+ * Creates a new response with the specified result.
+ * @param withResult The result.
+ */
+ public MessagingExtensionResponse(MessagingExtensionResult withResult) {
+ composeExtension = withResult;
+ }
+
/**
* Gets the response result.
* @return The result.
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
index a0ac6a49f..7c8d200f3 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
@@ -7,6 +7,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.bot.schema.Activity;
+import java.util.Collections;
import java.util.List;
/**
@@ -78,12 +79,22 @@ public List getAttachments() {
/**
* Sets (Only when type is result) Attachments.
+ * This replaces all previous attachments on the object.
* @param withAttachments The result attachments.
*/
public void setAttachments(List withAttachments) {
attachments = withAttachments;
}
+ /**
+ * Sets (Only when type is result) Attachments to the specific attachment.
+ * This replaces all previous attachments on the object.
+ * @param withAttachment The attachment.
+ */
+ public void setAttachment(MessagingExtensionAttachment withAttachment) {
+ setAttachments(Collections.singletonList(withAttachment));
+ }
+
/**
* Gets (Only when type is auth or config) suggested actions.
* @return The suggested actions.
From cbb4f5bf22218a9380e9a472438d6c857aad99ac Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 15:35:09 -0500
Subject: [PATCH 006/354] Checkstyle correction in BotController
---
.../com/microsoft/bot/integration/spring/BotController.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java b/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
index cd450f0b8..79c44e70b 100644
--- a/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
+++ b/libraries/bot-integration-spring/src/main/java/com/microsoft/bot/integration/spring/BotController.java
@@ -79,8 +79,9 @@ public CompletableFuture> incoming(
.handle((result, exception) -> {
if (exception == null) {
- if (result != null)
+ if (result != null) {
return new ResponseEntity<>(result.getBody(), HttpStatus.valueOf(result.getStatus()));
+ }
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
From fd6c3b67a4bc737d5b73565a801b104123d3ab45 Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Tue, 7 Apr 2020 15:59:53 -0500
Subject: [PATCH 007/354] Added 55.teams-link-unfurling
---
pom.xml | 1 +
samples/55.teams-link-unfurling/LICENSE | 21 +
samples/55.teams-link-unfurling/README.md | 60 +++
.../new-rg-parameters.json | 42 ++
.../preexisting-rg-parameters.json | 39 ++
.../template-with-new-rg.json | 191 ++++++++
.../template-with-preexisting-rg.json | 158 +++++++
samples/55.teams-link-unfurling/pom.xml | 315 +++++++++++++
.../bot/sample/teamsunfurl/Application.java | 46 ++
.../sample/teamsunfurl/LinkUnfurlingBot.java | 89 ++++
.../src/main/resources/application.properties | 2 +
.../src/main/resources/log4j2.json | 18 +
.../src/main/webapp/META-INF/MANIFEST.MF | 3 +
.../src/main/webapp/WEB-INF/web.xml | 12 +
.../src/main/webapp/index.html | 418 ++++++++++++++++++
.../sample/teamsunfurl/ApplicationTests.java | 19 +
.../teamsAppManifest/icon-color.png | Bin 0 -> 1229 bytes
.../teamsAppManifest/icon-outline.png | Bin 0 -> 383 bytes
.../teamsAppManifest/manifest.json | 58 +++
19 files changed, 1492 insertions(+)
create mode 100644 samples/55.teams-link-unfurling/LICENSE
create mode 100644 samples/55.teams-link-unfurling/README.md
create mode 100644 samples/55.teams-link-unfurling/deploymentTemplates/new-rg-parameters.json
create mode 100644 samples/55.teams-link-unfurling/deploymentTemplates/preexisting-rg-parameters.json
create mode 100644 samples/55.teams-link-unfurling/deploymentTemplates/template-with-new-rg.json
create mode 100644 samples/55.teams-link-unfurling/deploymentTemplates/template-with-preexisting-rg.json
create mode 100644 samples/55.teams-link-unfurling/pom.xml
create mode 100644 samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/Application.java
create mode 100644 samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/LinkUnfurlingBot.java
create mode 100644 samples/55.teams-link-unfurling/src/main/resources/application.properties
create mode 100644 samples/55.teams-link-unfurling/src/main/resources/log4j2.json
create mode 100644 samples/55.teams-link-unfurling/src/main/webapp/META-INF/MANIFEST.MF
create mode 100644 samples/55.teams-link-unfurling/src/main/webapp/WEB-INF/web.xml
create mode 100644 samples/55.teams-link-unfurling/src/main/webapp/index.html
create mode 100644 samples/55.teams-link-unfurling/src/test/java/com/microsoft/bot/sample/teamsunfurl/ApplicationTests.java
create mode 100644 samples/55.teams-link-unfurling/teamsAppManifest/icon-color.png
create mode 100644 samples/55.teams-link-unfurling/teamsAppManifest/icon-outline.png
create mode 100644 samples/55.teams-link-unfurling/teamsAppManifest/manifest.json
diff --git a/pom.xml b/pom.xml
index 488cdd1a5..388d68327 100644
--- a/pom.xml
+++ b/pom.xml
@@ -379,6 +379,7 @@
samples/51.teams-messaging-extensions-actionsamples/52.teams-messaging-extensions-search-auth-configsamples/53.teams-messaging-extensions-action-preview
+ samples/55.teams-link-unfurlingsamples/57.teams-conversation-bot
diff --git a/samples/55.teams-link-unfurling/LICENSE b/samples/55.teams-link-unfurling/LICENSE
new file mode 100644
index 000000000..21071075c
--- /dev/null
+++ b/samples/55.teams-link-unfurling/LICENSE
@@ -0,0 +1,21 @@
+ MIT License
+
+ Copyright (c) Microsoft Corporation. All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all
+ copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE
diff --git a/samples/55.teams-link-unfurling/README.md b/samples/55.teams-link-unfurling/README.md
new file mode 100644
index 000000000..7a2446381
--- /dev/null
+++ b/samples/55.teams-link-unfurling/README.md
@@ -0,0 +1,60 @@
+
+# Teams Link Unfurl Bot
+
+Bot Framework v4 Teams [link unfurling](https://docs.microsoft.com/en-us/microsoftteams/platform/messaging-extensions/how-to/link-unfurling?tabs=json) bot sample for Teams.
+
+This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that performs link unfurling in Teams.
+
+## Prerequisites
+
+- Microsoft Teams is installed and you have an account
+- [ngrok](https://ngrok.com/) or equivalent tunnelling solution
+
+## To try this sample
+
+> Note these instructions are for running the sample on your local machine, the tunnelling solution is required because
+the Teams service needs to call into the bot.
+
+1) Clone the repository
+
+ ```bash
+ git clone https://github.com/Microsoft/botbuilder-java.git
+ ```
+
+1) Run ngrok - point to port 8080
+
+ ```bash
+ ngrok http -host-header=rewrite 8080
+ ```
+
+1) Create [Bot Framework registration resource](https://docs.microsoft.com/en-us/azure/bot-service/bot-service-quickstart-registration) in Azure
+ - Use the current `https` URL you were given by running ngrok. Append with the path `/api/messages` used by this sample
+ - Ensure that you've [enabled the Teams Channel](https://docs.microsoft.com/en-us/azure/bot-service/channel-connect-teams?view=azure-bot-service-4.0)
+ - __*If you don't have an Azure account*__ you can use this [Bot Framework registration](https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/create-a-bot-for-teams#register-your-web-service-with-the-bot-framework)
+
+1) Update the `resources/application.properties` configuration for the bot to use the Microsoft App Id and App Password from the Bot Framework registration. (Note the App Password is referred to as the "client secret" in the azure portal and you can always create a new client secret anytime.)
+
+1) __*This step is specific to Teams.*__
+ - **Edit** the `manifest.json` contained in the `teamsAppManifest` folder to replace your Microsoft App Id (that was created when you registered your bot earlier) *everywhere* you see the place holder string `<>` (depending on the scenario the Microsoft App Id may occur multiple times in the `manifest.json`)
+ - **Zip** up the contents of the `teamsAppManifest` folder to create a `manifest.zip`
+ - **Upload** the `manifest.zip` to Teams (in the Apps view click "Upload a custom app")
+
+1) From the root of this project folder:
+ - Build the sample using `mvn package`
+ - Unless done previously, install the packages in the local cache by using `mvn install`
+ - Run it by using `java -jar .\target\bot-teams-link-unfurl-sample.jar`
+
+## Interacting with the bot in Teams
+
+> Note the Teams `manifest.json` for this sample also includes a Search Query. This Messaging Extension is only introduced in order to enable installation, because there is no mechanism for installing a link unfurling feature in isolation.
+
+If you copy and paste a link from https://www.BotFramework.com into the compose message area the link will unfurl.
+
+## Deploy the bot to Azure
+
+To learn more about deploying a bot to Azure, see [Deploy your bot to Azure](https://aka.ms/azuredeployment) for a complete list of deployment instructions.
+
+## Further reading
+
+- [How Microsoft Teams bots work](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-basics-teams?view=azure-bot-service-4.0&tabs=javascript)
+
diff --git a/samples/55.teams-link-unfurling/deploymentTemplates/new-rg-parameters.json b/samples/55.teams-link-unfurling/deploymentTemplates/new-rg-parameters.json
new file mode 100644
index 000000000..ead339093
--- /dev/null
+++ b/samples/55.teams-link-unfurling/deploymentTemplates/new-rg-parameters.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupLocation": {
+ "value": ""
+ },
+ "groupName": {
+ "value": ""
+ },
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ },
+ "botId": {
+ "value": ""
+ },
+ "botSku": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "newAppServicePlanLocation": {
+ "value": ""
+ },
+ "newWebAppName": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/55.teams-link-unfurling/deploymentTemplates/preexisting-rg-parameters.json b/samples/55.teams-link-unfurling/deploymentTemplates/preexisting-rg-parameters.json
new file mode 100644
index 000000000..b6f5114fc
--- /dev/null
+++ b/samples/55.teams-link-unfurling/deploymentTemplates/preexisting-rg-parameters.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appId": {
+ "value": ""
+ },
+ "appSecret": {
+ "value": ""
+ },
+ "botId": {
+ "value": ""
+ },
+ "botSku": {
+ "value": ""
+ },
+ "newAppServicePlanName": {
+ "value": ""
+ },
+ "newAppServicePlanSku": {
+ "value": {
+ "name": "S1",
+ "tier": "Standard",
+ "size": "S1",
+ "family": "S",
+ "capacity": 1
+ }
+ },
+ "appServicePlanLocation": {
+ "value": ""
+ },
+ "existingAppServicePlan": {
+ "value": ""
+ },
+ "newWebAppName": {
+ "value": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/samples/55.teams-link-unfurling/deploymentTemplates/template-with-new-rg.json b/samples/55.teams-link-unfurling/deploymentTemplates/template-with-new-rg.json
new file mode 100644
index 000000000..dcd6260a5
--- /dev/null
+++ b/samples/55.teams-link-unfurling/deploymentTemplates/template-with-new-rg.json
@@ -0,0 +1,191 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "groupLocation": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the location of the Resource Group."
+ }
+ },
+ "groupName": {
+ "type": "string",
+ "metadata": {
+ "description": "Specifies the name of the Resource Group."
+ }
+ },
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings."
+ }
+ },
+ "botId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
+ }
+ },
+ "botSku": {
+ "defaultValue": "F0",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "newAppServicePlanName": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "The name of the App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "P1v2",
+ "tier": "PremiumV2",
+ "size": "P1v2",
+ "family": "Pv2",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "newAppServicePlanLocation": {
+ "defaultValue": "",
+ "type": "string",
+ "metadata": {
+ "description": "The location of the App Service Plan. Defaults to \"westus\"."
+ }
+ },
+ "newWebAppName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
+ }
+ }
+ },
+ "variables": {
+ "resourcesLocation": "[deployment().location]",
+ "effectiveGroupLocation": "[if(empty(parameters('groupLocation')), variables('resourcesLocation'), parameters('groupLocation'))]",
+ "effectivePlanLocation": "[if(empty(parameters('newAppServicePlanLocation')), variables('resourcesLocation'), parameters('newAppServicePlanLocation'))]",
+ "appServicePlanName": "[if(empty(parameters('newAppServicePlanName')), concat(parameters('botId'), 'ServicePlan'), parameters('newAppServicePlanName'))]",
+ "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
+ "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
+ "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
+ },
+ "resources": [
+ {
+ "name": "[parameters('groupName')]",
+ "type": "Microsoft.Resources/resourceGroups",
+ "apiVersion": "2018-05-01",
+ "location": "[variables('effectiveGroupLocation')]",
+ "properties": {
+ }
+ },
+ {
+ "type": "Microsoft.Resources/deployments",
+ "apiVersion": "2018-05-01",
+ "name": "storageDeployment",
+ "resourceGroup": "[parameters('groupName')]",
+ "dependsOn": [
+ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('groupName'))]"
+ ],
+ "properties": {
+ "mode": "Incremental",
+ "template": {
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {},
+ "variables": {},
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan",
+ "type": "Microsoft.Web/serverfarms",
+ "name": "[variables('appServicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('effectivePlanLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('appServicePlanName')]",
+ "reserved":true
+ }
+ },
+ {
+ "comments": "Create a Web App using the new App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2015-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms/', variables('appServicePlanName'))]"
+ ],
+ "name": "[variables('webAppName')]",
+ "properties": {
+ "name": "[variables('webAppName')]",
+ "serverFarmId": "[variables('appServicePlanName')]",
+ "siteConfig": {
+ "appSettings": [
+ {
+ "name": "JAVA_OPTS",
+ "value": "-Dserver.port=80"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "apiVersion": "2017-12-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('botId')]",
+ "location": "global",
+ "kind": "bot",
+ "sku": {
+ "name": "[parameters('botSku')]"
+ },
+ "properties": {
+ "name": "[parameters('botId')]",
+ "displayName": "[parameters('botId')]",
+ "endpoint": "[variables('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "developerAppInsightsApplicationId": null,
+ "developerAppInsightKey": null,
+ "publishingCredentials": null,
+ "storageResourceId": null
+ },
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
+ ]
+ }
+ ],
+ "outputs": {}
+ }
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/samples/55.teams-link-unfurling/deploymentTemplates/template-with-preexisting-rg.json b/samples/55.teams-link-unfurling/deploymentTemplates/template-with-preexisting-rg.json
new file mode 100644
index 000000000..b790d2bdc
--- /dev/null
+++ b/samples/55.teams-link-unfurling/deploymentTemplates/template-with-preexisting-rg.json
@@ -0,0 +1,158 @@
+{
+ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
+ "contentVersion": "1.0.0.0",
+ "parameters": {
+ "appId": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App ID, set as MicrosoftAppId in the Web App's Application Settings."
+ }
+ },
+ "appSecret": {
+ "type": "string",
+ "metadata": {
+ "description": "Active Directory App Password, set as MicrosoftAppPassword in the Web App's Application Settings. Defaults to \"\"."
+ }
+ },
+ "botId": {
+ "type": "string",
+ "metadata": {
+ "description": "The globally unique and immutable bot ID. Also used to configure the displayName of the bot, which is mutable."
+ }
+ },
+ "botSku": {
+ "defaultValue": "S1",
+ "type": "string",
+ "metadata": {
+ "description": "The pricing tier of the Bot Service Registration. Acceptable values are F0 and S1."
+ }
+ },
+ "newAppServicePlanName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The name of the new App Service Plan."
+ }
+ },
+ "newAppServicePlanSku": {
+ "type": "object",
+ "defaultValue": {
+ "name": "P1v2",
+ "tier": "PremiumV2",
+ "size": "P1v2",
+ "family": "Pv2",
+ "capacity": 1
+ },
+ "metadata": {
+ "description": "The SKU of the App Service Plan. Defaults to Standard values."
+ }
+ },
+ "appServicePlanLocation": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The location of the App Service Plan."
+ }
+ },
+ "existingAppServicePlan": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "Name of the existing App Service Plan used to create the Web App for the bot."
+ }
+ },
+ "newWebAppName": {
+ "type": "string",
+ "defaultValue": "",
+ "metadata": {
+ "description": "The globally unique name of the Web App. Defaults to the value passed in for \"botId\"."
+ }
+ }
+ },
+ "variables": {
+ "defaultAppServicePlanName": "[if(empty(parameters('existingAppServicePlan')), 'createNewAppServicePlan', parameters('existingAppServicePlan'))]",
+ "useExistingAppServicePlan": "[not(equals(variables('defaultAppServicePlanName'), 'createNewAppServicePlan'))]",
+ "servicePlanName": "[if(variables('useExistingAppServicePlan'), parameters('existingAppServicePlan'), if(empty(parameters('newAppServicePlanName')),concat(parameters('botId'), 'ServicePlan'),parameters('newAppServicePlanName')))]",
+ "resourcesLocation": "[if(empty(parameters('appServicePlanLocation')), resourceGroup().location, parameters('appServicePlanLocation'))]",
+ "webAppName": "[if(empty(parameters('newWebAppName')), parameters('botId'), parameters('newWebAppName'))]",
+ "siteHost": "[concat(variables('webAppName'), '.azurewebsites.net')]",
+ "botEndpoint": "[concat('https://', variables('siteHost'), '/api/messages')]"
+ },
+ "resources": [
+ {
+ "comments": "Create a new App Service Plan if no existing App Service Plan name was passed in.",
+ "type": "Microsoft.Web/serverfarms",
+ "condition": "[not(variables('useExistingAppServicePlan'))]",
+ "name": "[variables('servicePlanName')]",
+ "apiVersion": "2018-02-01",
+ "location": "[variables('resourcesLocation')]",
+ "sku": "[parameters('newAppServicePlanSku')]",
+ "kind": "linux",
+ "properties": {
+ "name": "[variables('servicePlanName')]",
+ "reserved":true
+ }
+ },
+ {
+ "comments": "Create a Web App using an App Service Plan",
+ "type": "Microsoft.Web/sites",
+ "apiVersion": "2016-08-01",
+ "location": "[variables('resourcesLocation')]",
+ "kind": "app",
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/serverfarms/', variables('servicePlanName'))]"
+ ],
+ "name": "[variables('webAppName')]",
+ "properties": {
+ "name": "[variables('webAppName')]",
+ "serverFarmId": "[variables('servicePlanName')]",
+ "siteConfig": {
+ "linuxFxVersion": "JAVA|8-jre8",
+ "appSettings": [
+ {
+ "name": "JAVA_OPTS",
+ "value": "-Dserver.port=80"
+ },
+ {
+ "name": "MicrosoftAppId",
+ "value": "[parameters('appId')]"
+ },
+ {
+ "name": "MicrosoftAppPassword",
+ "value": "[parameters('appSecret')]"
+ }
+ ],
+ "cors": {
+ "allowedOrigins": [
+ "https://botservice.hosting.portal.azure.net",
+ "https://hosting.onecloud.azure-test.net/"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "apiVersion": "2017-12-01",
+ "type": "Microsoft.BotService/botServices",
+ "name": "[parameters('botId')]",
+ "location": "global",
+ "kind": "bot",
+ "sku": {
+ "name": "[parameters('botSku')]"
+ },
+ "properties": {
+ "name": "[parameters('botId')]",
+ "displayName": "[parameters('botId')]",
+ "endpoint": "[variables('botEndpoint')]",
+ "msaAppId": "[parameters('appId')]",
+ "developerAppInsightsApplicationId": null,
+ "developerAppInsightKey": null,
+ "publishingCredentials": null,
+ "storageResourceId": null
+ },
+ "dependsOn": [
+ "[resourceId('Microsoft.Web/sites/', variables('webAppName'))]"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/samples/55.teams-link-unfurling/pom.xml b/samples/55.teams-link-unfurling/pom.xml
new file mode 100644
index 000000000..d4179a386
--- /dev/null
+++ b/samples/55.teams-link-unfurling/pom.xml
@@ -0,0 +1,315 @@
+
+
+
+ 4.0.0
+
+ com.microsoft.bot.sample
+ bot-teams-link-unfurl
+ sample
+ jar
+
+ ${project.groupId}:${project.artifactId}
+ This package contains a Java Teams Link Unfurl sample using Spring Boot.
+ http://maven.apache.org
+
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.1.7.RELEASE
+
+
+
+
+
+ MIT License
+ http://www.opensource.org/licenses/mit-license.php
+
+
+
+
+
+ Bot Framework Development
+
+ Microsoft
+ https://dev.botframework.com/
+
+
+
+
+ UTF-8
+ UTF-8
+ 1.8
+ 1.8
+ 1.8
+ com.microsoft.bot.sample.teamsunfurl.Application
+ https://botbuilder.myget.org/F/botbuilder-v4-java-daily/maven/
+
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ 2.1.8.RELEASE
+ test
+
+
+
+ org.slf4j
+ slf4j-api
+
+
+ org.apache.logging.log4j
+ log4j-api
+ 2.11.0
+
+
+ org.apache.logging.log4j
+ log4j-core
+ 2.11.0
+
+
+
+ com.microsoft.bot
+ bot-integration-spring
+ 4.0.0-SNAPSHOT
+ compile
+
+
+
+
+
+ MyGet
+ ${repo.url}
+
+
+
+
+
+ ossrh
+
+ https://oss.sonatype.org/
+
+
+
+
+
+
+ build
+
+ true
+
+
+
+
+ maven-compiler-plugin
+ 3.8.1
+
+ 1.8
+ 1.8
+
+
+
+ maven-war-plugin
+ 3.2.3
+
+ src/main/webapp
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ com.microsoft.bot.sample.teamsunfurl.Application
+
+
+
+
+
+ com.microsoft.azure
+ azure-webapp-maven-plugin
+ 1.7.0
+
+ V2
+ {groupname}
+ {botname}
+
+
+ JAVA_OPTS
+ -Dserver.port=80
+
+
+
+ linux
+ jre8
+ jre8
+
+
+
+
+ ${project.basedir}/target
+
+ *.jar
+
+
+
+
+
+
+
+ org.eluder.coveralls
+ coveralls-maven-plugin
+ 4.3.0
+
+ yourcoverallsprojectrepositorytoken
+
+
+
+ org.codehaus.mojo
+ cobertura-maven-plugin
+ 2.7
+
+ ../../cobertura-report/spring-teamsunfurl-sample
+ xml
+ 256m
+
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+ 3.7.1
+
+
+ org.apache.maven.plugins
+ maven-project-info-reports-plugin
+ 3.0.0
+
+
+
+
+
+
+
+ publish
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ org.sonatype.plugins
+ nexus-staging-maven-plugin
+ 1.6.8
+ true
+
+ true
+ ossrh
+ https://oss.sonatype.org/
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+
+
+ attach-sources
+
+ jar
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+
+ 8
+ false
+
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-pmd-plugin
+ 3.12.0
+
+
+ org.apache.maven.plugins
+ maven-checkstyle-plugin
+ 3.1.0
+
+
+
+ checkstyle
+
+
+
+
+
+
+
+
diff --git a/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/Application.java b/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/Application.java
new file mode 100644
index 000000000..2bb526955
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/Application.java
@@ -0,0 +1,46 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.microsoft.bot.sample.teamsunfurl;
+
+import com.microsoft.bot.integration.AdapterWithErrorHandler;
+import com.microsoft.bot.integration.BotFrameworkHttpAdapter;
+import com.microsoft.bot.integration.Configuration;
+import com.microsoft.bot.integration.spring.BotController;
+import com.microsoft.bot.integration.spring.BotDependencyConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Import;
+
+/**
+ * This is the starting point of the Sprint Boot Bot application.
+ *
+ * This class also provides overrides for dependency injections. A class that extends the
+ * {@link com.microsoft.bot.builder.Bot} interface should be annotated with @Component.
+ *
+ * @see LinkUnfurlingBot
+ */
+@SpringBootApplication
+
+// Use the default BotController to receive incoming Channel messages. A custom controller
+// could be used by eliminating this import and creating a new RestController. The default
+// controller is created by the Spring Boot container using dependency injection. The
+// default route is /api/messages.
+@Import({BotController.class})
+
+public class Application extends BotDependencyConfiguration {
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+
+ /**
+ * Returns a custom Adapter that provides error handling.
+ *
+ * @param configuration The Configuration object to use.
+ * @return An error handling BotFrameworkHttpAdapter.
+ */
+ @Override
+ public BotFrameworkHttpAdapter getBotFrameworkHttpAdaptor(Configuration configuration) {
+ return new AdapterWithErrorHandler(configuration);
+ }
+}
diff --git a/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/LinkUnfurlingBot.java b/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/LinkUnfurlingBot.java
new file mode 100644
index 000000000..8277a408e
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/java/com/microsoft/bot/sample/teamsunfurl/LinkUnfurlingBot.java
@@ -0,0 +1,89 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.microsoft.bot.sample.teamsunfurl;
+
+import com.microsoft.bot.builder.TurnContext;
+import com.microsoft.bot.builder.teams.TeamsActivityHandler;
+import com.microsoft.bot.schema.CardImage;
+import com.microsoft.bot.schema.HeroCard;
+import com.microsoft.bot.schema.ThumbnailCard;
+import com.microsoft.bot.schema.teams.AppBasedLinkQuery;
+import com.microsoft.bot.schema.teams.MessagingExtensionAttachment;
+import com.microsoft.bot.schema.teams.MessagingExtensionQuery;
+import com.microsoft.bot.schema.teams.MessagingExtensionResponse;
+import com.microsoft.bot.schema.teams.MessagingExtensionResult;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * This class implements the functionality of the Bot.
+ *
+ *
This is where application specific logic for interacting with the users would be
+ * added.
+ */
+@Component
+public class LinkUnfurlingBot extends TeamsActivityHandler {
+ @Override
+ protected CompletableFuture onTeamsAppBasedLinkQuery(
+ TurnContext turnContext,
+ AppBasedLinkQuery query
+ ) {
+ ThumbnailCard card = new ThumbnailCard() {{
+ setTitle("Thumbnail Card");
+ setText(query.getUrl());
+ setImages(Collections.singletonList(
+ new CardImage("https://raw.githubusercontent.com/microsoft/botframework-sdk/master/icon.png")
+ ));
+ }};
+
+ MessagingExtensionAttachment attachments = new MessagingExtensionAttachment() {{
+ setContentType(HeroCard.CONTENTTYPE);
+ setContent(card);
+ }};
+
+ MessagingExtensionResult result = new MessagingExtensionResult() {{
+ setAttachmentLayout("list");
+ setType("result");
+ setAttachments(Collections.singletonList(attachments));
+ }};
+
+ return CompletableFuture.completedFuture(new MessagingExtensionResponse(result));
+ }
+
+ protected CompletableFuture onTeamsMessagingExtensionQuery(
+ TurnContext turnContext,
+ MessagingExtensionQuery query
+ ) {
+ //Note: The Teams manifest.json for this sample also includes a Search Query, in order to enable installing from App Studio.
+
+ // These commandIds are defined in the Teams App Manifest.
+ if (StringUtils.equalsIgnoreCase("searchQuery", query.getCommandId())) {
+ HeroCard card = new HeroCard() {{
+ setTitle("This is a Link Unfurling Sample");
+ setSubtitle("It will unfurl links from *.BotFramework.com");
+ setText("This sample demonstrates how to handle link unfurling in Teams. "
+ + "Please review the readme for more information.");
+ }};
+
+ return CompletableFuture.completedFuture(new MessagingExtensionResponse(
+ new MessagingExtensionResult() {{
+ setAttachmentLayout("list");
+ setType("result");
+ setAttachment(
+ new MessagingExtensionAttachment() {{
+ setContent(card);
+ setContentType(HeroCard.CONTENTTYPE);
+ setPreview(card.toAttachment());
+ }}
+ );
+ }}
+ ));
+ }
+
+ return notImplemented(String.format("Invalid CommandId: %s", query.getCommandId()));
+ }
+}
diff --git a/samples/55.teams-link-unfurling/src/main/resources/application.properties b/samples/55.teams-link-unfurling/src/main/resources/application.properties
new file mode 100644
index 000000000..a695b3bf0
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/resources/application.properties
@@ -0,0 +1,2 @@
+MicrosoftAppId=
+MicrosoftAppPassword=
diff --git a/samples/55.teams-link-unfurling/src/main/resources/log4j2.json b/samples/55.teams-link-unfurling/src/main/resources/log4j2.json
new file mode 100644
index 000000000..67c0ad530
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/resources/log4j2.json
@@ -0,0 +1,18 @@
+{
+ "configuration": {
+ "name": "Default",
+ "appenders": {
+ "Console": {
+ "name": "Console-Appender",
+ "target": "SYSTEM_OUT",
+ "PatternLayout": {"pattern": "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"}
+ }
+ },
+ "loggers": {
+ "root": {
+ "level": "debug",
+ "appender-ref": {"ref": "Console-Appender","level": "debug"}
+ }
+ }
+ }
+}
diff --git a/samples/55.teams-link-unfurling/src/main/webapp/META-INF/MANIFEST.MF b/samples/55.teams-link-unfurling/src/main/webapp/META-INF/MANIFEST.MF
new file mode 100644
index 000000000..254272e1c
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/webapp/META-INF/MANIFEST.MF
@@ -0,0 +1,3 @@
+Manifest-Version: 1.0
+Class-Path:
+
diff --git a/samples/55.teams-link-unfurling/src/main/webapp/WEB-INF/web.xml b/samples/55.teams-link-unfurling/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 000000000..383c19004
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,12 @@
+
+
+ dispatcher
+
+ org.springframework.web.servlet.DispatcherServlet
+
+
+ contextConfigLocation
+ /WEB-INF/spring/dispatcher-config.xml
+
+ 1
+
\ No newline at end of file
diff --git a/samples/55.teams-link-unfurling/src/main/webapp/index.html b/samples/55.teams-link-unfurling/src/main/webapp/index.html
new file mode 100644
index 000000000..40b74c007
--- /dev/null
+++ b/samples/55.teams-link-unfurling/src/main/webapp/index.html
@@ -0,0 +1,418 @@
+
+
+
+
+
+
+ EchoBot
+
+
+
+
+
+
+
+
+
Spring Boot Bot
+
+
+
+
+
Your bot is ready!
+
You can test your bot in the Bot Framework Emulator
+ by connecting to http://localhost:8080/api/messages.
This is where application specific logic for interacting with the users would be
- * added. For this sample, the {@link #onMessageActivity(TurnContext)} echos the text
- * back to the user. The {@link #onMembersAdded(List, TurnContext)} will send a greeting
- * to new conversation participants.
+ * added. This sample illustrates how to build a Search-based Messaging Extension.
*/
+
@Component
public class TeamsMessagingExtensionsSearchBot extends TeamsActivityHandler {
private String appId;
@@ -50,163 +34,111 @@ public TeamsMessagingExtensionsSearchBot(Configuration configuration) {
}
@Override
- protected CompletableFuture onMessageActivity(TurnContext turnContext) {
- turnContext.getActivity().removeRecipientMention();
-
- switch (turnContext.getActivity().getText().trim()) {
- case "MentionMe":
- return mentionActivity(turnContext);
-
- case "UpdateCardAction":
- return updateCardActivity(turnContext);
-
- case "Delete":
- return deleteCardActivity(turnContext);
-
- case "MessageAllMembers":
- return messageAllMembers(turnContext);
-
- default:
- // This will come back deserialized as a Map.
- Object value = new Object() {
- int count = 0;
- };
-
- HeroCard card = new HeroCard() {{
- setTitle("Welcome Card");
- setText("Click the buttons below to update this card");
- setButtons(Arrays.asList(
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Update Card");
- setText("UpdateCardAction");
- setValue(value);
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Message All Members");
- setText("MessageAllMembers");
- }}
- ));
- }};
-
- return turnContext.sendActivity(MessageFactory.attachment(card.toAttachment()))
- .thenApply(resourceResponse -> null);
+ protected CompletableFuture onTeamsMessagingExtensionQuery(TurnContext turnContext,
+ MessagingExtensionQuery query) {
+ List queryParams = query.getParameters();
+ String text = "";
+ if (queryParams != null && !queryParams.isEmpty()) {
+ text = (String) queryParams.get(0).getValue();
+ }
+ List packages = FindPackages(text);
+
+ List attachments = new ArrayList<>();
+ for (String [] item: packages) {
+ ThumbnailCard previewCard = new ThumbnailCard(){{
+ setTitle(item[0]);
+ setTap(new CardAction(){{
+ setType(ActionTypes.INVOKE);
+ setValue(new JSONObject().put("data", item).toString());
+ }});
+ }};
+
+ if (!StringUtils.isEmpty(item[4])) {
+ previewCard.setImages(Collections.singletonList(new CardImage(){{
+ setUrl(item[4]);
+ setAlt("Icon");
+ }}));
+ }
+
+ MessagingExtensionAttachment attachment = new MessagingExtensionAttachment(){{
+ setContentType(HeroCard.CONTENTTYPE);
+ setContent(new HeroCard(){{
+ setTitle(item[0]);
+ }});
+ setPreview(previewCard.toAttachment());
+ }};
+
+ attachments.add(attachment);
}
- }
- @Override
- protected CompletableFuture onTeamsMembersAdded(
- List membersAdded,
- TeamInfo teamInfo,
- TurnContext turnContext
- ) {
- return membersAdded.stream()
- .filter(member -> !StringUtils.equals(member.getId(), turnContext.getActivity().getRecipient().getId()))
- .map(channel -> turnContext.sendActivity(
- MessageFactory.text("Welcome to the team " + channel.getGivenName() + " " + channel.getSurname() + ".")))
- .collect(CompletableFutures.toFutureList())
- .thenApply(resourceResponses -> null);
- }
- private CompletableFuture deleteCardActivity(TurnContext turnContext) {
- return turnContext.deleteActivity(turnContext.getActivity().getReplyToId());
- }
+ MessagingExtensionResult composeExtension = new MessagingExtensionResult(){{
+ setType("result");
+ setAttachmentLayout("list");
+ setAttachments(attachments);
+ }};
- // If you encounter permission-related errors when sending this message, see
- // https://aka.ms/BotTrustServiceUrl
- private CompletableFuture messageAllMembers(TurnContext turnContext) {
- String teamsChannelId = turnContext.getActivity().teamsGetChannelId();
- String serviceUrl = turnContext.getActivity().getServiceUrl();
- MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appId, appPassword);
-
- return TeamsInfo.getMembers(turnContext)
- .thenCompose(members -> {
- List> conversations = new ArrayList<>();
-
- // Send a message to each member. These will all go out
- // at the same time.
- for (TeamsChannelAccount member : members) {
- Activity proactiveMessage = MessageFactory.text(
- "Hello " + member.getGivenName() + " " + member.getSurname()
- + ". I'm a Teams conversation bot.");
-
- ConversationParameters conversationParameters = new ConversationParameters() {{
- setIsGroup(false);
- setBot(turnContext.getActivity().getRecipient());
- setMembers(Collections.singletonList(member));
- setTenantId(turnContext.getActivity().getConversation().getTenantId());
- }};
-
- conversations.add(
- ((BotFrameworkAdapter) turnContext.getAdapter()).createConversation(
- teamsChannelId,
- serviceUrl,
- credentials,
- conversationParameters,
- (context) -> {
- ConversationReference reference = context.getActivity().getConversationReference();
- return context.getAdapter().continueConversation(
- appId,
- reference,
- (inner_context) -> inner_context.sendActivity(proactiveMessage)
- .thenApply(resourceResponse -> null)
- );
- }
- )
- );
- }
-
- return CompletableFuture.allOf(conversations.toArray(new CompletableFuture[0]));
- })
- // After all member messages are sent, send confirmation to the user.
- .thenApply(conversations -> turnContext.sendActivity(MessageFactory.text("All messages have been sent.")))
- .thenApply(allSent -> null);
+ return CompletableFuture.completedFuture(new MessagingExtensionResponse(composeExtension));
}
- private CompletableFuture updateCardActivity(TurnContext turnContext) {
- Map data = (Map) turnContext.getActivity().getValue();
- data.put("count", (int) data.get("count") + 1);
-
- HeroCard card = new HeroCard() {{
- setTitle("Welcome Card");
- setText("Update count - " + data.get("count"));
- setButtons(Arrays.asList(
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Update Card");
- setText("UpdateCardAction");
- setValue(data);
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Message All Members");
- setText("MessageAllMembers");
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Delete card");
- setText("Delete");
- }}
- ));
+ @Override
+ protected CompletableFuture onTeamsMessagingExtensionSelectItem(
+ TurnContext turnContext,
+ Object query) {
+
+ LinkedHashMap cardValue = ((LinkedHashMap) query);
+ List data = (ArrayList) cardValue.get("data");
+ ThumbnailCard card = new ThumbnailCard(){{
+ setTitle(data.get(0));
+ setSubtitle(data.get(2));
}};
- Activity updatedActivity = MessageFactory.attachment(card.toAttachment());
- updatedActivity.setId(turnContext.getActivity().getReplyToId());
-
- return turnContext.updateActivity(updatedActivity)
- .thenApply(resourceResponse -> null);
- }
+ if (!StringUtils.isEmpty(data.get(4))) {
+ card.setImages(Collections.singletonList(new CardImage(){{
+ setUrl(data.get(4));
+ setAlt("Icon");
+ }}));
+ }
- private CompletableFuture mentionActivity(TurnContext turnContext) {
- Mention mention = new Mention();
- mention.setMentioned(turnContext.getActivity().getFrom());
- mention.setText("" + URLEncoder.encode(turnContext.getActivity().getFrom().getName()) + "");
+ MessagingExtensionAttachment attachment = new MessagingExtensionAttachment(){{
+ setContentType(ThumbnailCard.CONTENTTYPE);
+ setContent(card);
+ }};
- Activity replyActivity = MessageFactory.text("Hello " + mention.getText() + ".'");
- replyActivity.setMentions(Collections.singletonList(mention));
+ MessagingExtensionResult composeExtension = new MessagingExtensionResult(){{
+ setType("result");
+ setAttachmentLayout("list");
+ setAttachments(Collections.singletonList(attachment));
+ }};
+ return CompletableFuture.completedFuture(new MessagingExtensionResponse(composeExtension));
+ }
- return turnContext.sendActivity(replyActivity)
- .thenApply(resourceResponse -> null);
+ private List FindPackages(String text) {
+
+ OkHttpClient client = new OkHttpClient();
+ Request request = new Request.Builder()
+ .url(String.format("https://azuresearch-usnc.nuget.org/query?q=id:%s&prerelease=true", text))
+ .build();
+
+ List filteredItems = new ArrayList();
+ try {
+ Response response = client.newCall(request).execute();
+ JSONObject obj = new JSONObject(response.body().string());
+ JSONArray dataArray = (JSONArray) obj.get("data");
+ dataArray.forEach(i -> {
+ JSONObject item = (JSONObject) i;
+ filteredItems.add(new String [] {
+ item.getString("id"),
+ item.getString("version"),
+ item.getString("description"),
+ item.has("projectUrl") ? item.getString("projectUrl") : "",
+ item.has("iconUrl") ? item.getString("iconUrl") : ""
+ });
+ });
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return filteredItems;
}
}
diff --git a/samples/50.teams-messaging-extensions-search/teamsAppManifest/manifest.json b/samples/50.teams-messaging-extensions-search/teamsAppManifest/manifest.json
index cd4900030..657f2d048 100644
--- a/samples/50.teams-messaging-extensions-search/teamsAppManifest/manifest.json
+++ b/samples/50.teams-messaging-extensions-search/teamsAppManifest/manifest.json
@@ -1,49 +1,49 @@
{
- "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
- "manifestVersion": "1.5",
- "version": "1.0",
- "id": "<>",
- "packageName": "com.microsoft.teams.samples.searchExtension",
- "developer": {
- "name": "Microsoft Corp",
- "websiteUrl": "https://example.azurewebsites.net",
- "privacyUrl": "https://example.azurewebsites.net/privacy",
- "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
- },
- "name": {
- "short": "search-extension-settings",
- "full": "Microsoft Teams V4 Search Messaging Extension Bot and settings"
- },
- "description": {
- "short": "Microsoft Teams V4 Search Messaging Extension Bot and settings",
- "full": "Sample Search Messaging Extension Bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK"
- },
- "icons": {
- "outline": "icon-outline.png",
- "color": "icon-color.png"
- },
- "accentColor": "#abcdef",
- "composeExtensions": [
- {
- "botId": "<>",
- "canUpdateConfiguration": true,
- "commands": [
+ "$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.5/MicrosoftTeams.schema.json",
+ "manifestVersion": "1.5",
+ "version": "1.0",
+ "id": "",
+ "packageName": "com.microsoft.teams.samples.searchExtension",
+ "developer": {
+ "name": "Microsoft Corp",
+ "websiteUrl": "https://example.azurewebsites.net",
+ "privacyUrl": "https://example.azurewebsites.net/privacy",
+ "termsOfUseUrl": "https://example.azurewebsites.net/termsofuse"
+ },
+ "name": {
+ "short": "search-extension-settings",
+ "full": "Microsoft Teams V4 Search Messaging Extension Bot and settings"
+ },
+ "description": {
+ "short": "Microsoft Teams V4 Search Messaging Extension Bot and settings",
+ "full": "Sample Search Messaging Extension Bot using V4 Bot Builder SDK and V4 Microsoft Teams Extension SDK"
+ },
+ "icons": {
+ "outline": "icon-outline.png",
+ "color": "icon-color.png"
+ },
+ "accentColor": "#abcdef",
+ "composeExtensions": [
{
- "id": "searchQuery",
- "context": [ "compose", "commandBox" ],
- "description": "Test command to run query",
- "title": "Search",
- "type": "query",
- "parameters": [
- {
- "name": "searchQuery",
- "title": "Search Query",
- "description": "Your search query",
- "inputType": "text"
- }
- ]
+ "botId": "",
+ "canUpdateConfiguration": true,
+ "commands": [
+ {
+ "id": "searchQuery",
+ "context": [ "compose", "commandBox" ],
+ "description": "Test command to run query",
+ "title": "Search",
+ "type": "query",
+ "parameters": [
+ {
+ "name": "searchQuery",
+ "title": "Search Query",
+ "description": "Your search query",
+ "inputType": "text"
+ }
+ ]
+ }
+ ]
}
- ]
- }
- ]
-}
\ No newline at end of file
+ ]
+}
From 79e4c8e998500bc3012a69c87e25a3834dd9996a Mon Sep 17 00:00:00 2001
From: Emilio Munoz
Date: Thu, 9 Apr 2020 23:19:00 -0700
Subject: [PATCH 014/354] Fixing README and swith to async http request
---
.../README.md | 21 +++----
.../TeamsMessagingExtensionsSearchBot.java | 62 +++++++++++--------
2 files changed, 43 insertions(+), 40 deletions(-)
diff --git a/samples/50.teams-messaging-extensions-search/README.md b/samples/50.teams-messaging-extensions-search/README.md
index 6dd585698..6f89349c4 100644
--- a/samples/50.teams-messaging-extensions-search/README.md
+++ b/samples/50.teams-messaging-extensions-search/README.md
@@ -1,10 +1,11 @@
# Teams Messaging Extensions Search Bot
-Bot Framework v4 Conversation Bot sample for Teams.
-This bot has been created using [Bot Framework](https://dev.botframework.com). This sample shows
-how to incorporate basic conversational flow into a Teams application. It also illustrates a few of the Teams specific calls you can make from your bot.
+[Messaging Extensions](https://docs.microsoft.com/en-us/microsoftteams/platform/messaging-extensions/what-are-messaging-extensions) are a special kind of Microsoft Teams application that is support by the [Bot Framework](https://dev.botframework.com) v4.
+
+There are two basic types of Messaging Extension in Teams: [Search-based](https://docs.microsoft.com/en-us/microsoftteams/platform/messaging-extensions/how-to/search-commands/define-search-command) and [Action-based](https://docs.microsoft.com/en-us/microsoftteams/platform/messaging-extensions/how-to/action-commands/define-action-command). This sample illustrates how to
+build a Search-based Messaging Extension.
## Prerequisites
@@ -48,19 +49,11 @@ the Teams service needs to call into the bot.
## Interacting with the bot
-You can interact with this bot by sending it a message, or selecting a command from the command list. The bot will respond to the following strings.
+> Note this `manifest.json` specified that the feature will be available from both the `compose` and `commandBox` areas of Teams. Please refer to Teams documentation for more details.
-1. **Show Welcome**
- - **Result:** The bot will send the welcome card for you to interact with
- - **Valid Scopes:** personal, group chat, team chat
-2. **MentionMe**
- - **Result:** The bot will respond to the message and mention the user
- - **Valid Scopes:** personal, group chat, team chat
-3. **MessageAllMembers**
- - **Result:** The bot will send a 1-on-1 message to each member in the current conversation (aka on the conversation's roster).
- - **Valid Scopes:** personal, group chat, team chat
+In Teams, the command bar is located at the top of the window. When you at mention the bot what you type is forwarded (as you type) to the bot for processing. By way of illustration, this sample uses the text it receives to query the NuGet package store.
-You can select an option from the command list by typing ```@TeamsConversationBot``` into the compose message area and ```What can I do?``` text above the compose area.
+There is a secondary, drill down, event illustrated in this sample: clicking on the results from the initial query will result in the bot receiving another event.
### Avoiding Permission-Related Errors
diff --git a/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java b/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
index 17dfc8066..0093aa5e2 100644
--- a/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
+++ b/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
@@ -15,6 +15,7 @@
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
/**
* This class implements the functionality of the Bot.
@@ -41,7 +42,14 @@ protected CompletableFuture onTeamsMessagingExtensio
if (queryParams != null && !queryParams.isEmpty()) {
text = (String) queryParams.get(0).getValue();
}
- List packages = FindPackages(text);
+
+ List packages = null;
+
+ try {
+ packages = FindPackages(text).get();
+ } catch (IOException | InterruptedException | ExecutionException e) {
+ packages = new ArrayList();
+ }
List attachments = new ArrayList<>();
for (String [] item: packages) {
@@ -113,32 +121,34 @@ protected CompletableFuture onTeamsMessagingExtensio
return CompletableFuture.completedFuture(new MessagingExtensionResponse(composeExtension));
}
- private List FindPackages(String text) {
-
- OkHttpClient client = new OkHttpClient();
- Request request = new Request.Builder()
- .url(String.format("https://azuresearch-usnc.nuget.org/query?q=id:%s&prerelease=true", text))
- .build();
-
- List filteredItems = new ArrayList();
- try {
- Response response = client.newCall(request).execute();
- JSONObject obj = new JSONObject(response.body().string());
- JSONArray dataArray = (JSONArray) obj.get("data");
- dataArray.forEach(i -> {
- JSONObject item = (JSONObject) i;
- filteredItems.add(new String [] {
- item.getString("id"),
- item.getString("version"),
- item.getString("description"),
- item.has("projectUrl") ? item.getString("projectUrl") : "",
- item.has("iconUrl") ? item.getString("iconUrl") : ""
+ private CompletableFuture> FindPackages(String text) throws IOException {
+ return CompletableFuture.supplyAsync(() -> {
+ OkHttpClient client = new OkHttpClient();
+ Request request = new Request.Builder()
+ .url(String.format("https://azuresearch-usnc.nuget.org/query?q=id:%s&prerelease=true", text))
+ .build();
+
+ List filteredItems = new ArrayList();
+ try {
+ Response response = client.newCall(request).execute();
+ JSONObject obj = new JSONObject(response.body().string());
+ JSONArray dataArray = (JSONArray) obj.get("data");
+ dataArray.forEach(i -> {
+ JSONObject item = (JSONObject) i;
+ filteredItems.add(new String [] {
+ item.getString("id"),
+ item.getString("version"),
+ item.getString("description"),
+ item.has("projectUrl") ? item.getString("projectUrl") : "",
+ item.has("iconUrl") ? item.getString("iconUrl") : ""
+ });
});
- });
- } catch (IOException e) {
- e.printStackTrace();
- }
- return filteredItems;
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return filteredItems;
+ });
+
}
}
From 9ef0dbb4f3b793b70fa8b0f9bbfba5004526716f Mon Sep 17 00:00:00 2001
From: Emilio Munoz
Date: Fri, 10 Apr 2020 02:29:39 -0700
Subject: [PATCH 015/354] Adding Action Extension Bot
---
.../README.md | 18 +-
.../TeamsMessagingExtensionsActionBot.java | 221 +++++-------------
2 files changed, 61 insertions(+), 178 deletions(-)
diff --git a/samples/51.teams-messaging-extensions-action/README.md b/samples/51.teams-messaging-extensions-action/README.md
index eed334ee8..cbb4a390e 100644
--- a/samples/51.teams-messaging-extensions-action/README.md
+++ b/samples/51.teams-messaging-extensions-action/README.md
@@ -3,8 +3,7 @@
Bot Framework v4 Conversation Bot sample for Teams.
-This bot has been created using [Bot Framework](https://dev.botframework.com). This sample shows
-how to incorporate basic conversational flow into a Teams application. It also illustrates a few of the Teams specific calls you can make from your bot.
+There are two basic types of Messaging Extension in Teams: Search-based and Action-based. This sample illustrates how to build an Action-based Messaging Extension.
## Prerequisites
@@ -48,20 +47,13 @@ the Teams service needs to call into the bot.
## Interacting with the bot
-You can interact with this bot by sending it a message, or selecting a command from the command list. The bot will respond to the following strings.
+> Note this `manifest.json` specified that the bot will be called from both the `compose` and `message` areas of Teams. Please refer to Teams documentation for more details.
-1. **Show Welcome**
- - **Result:** The bot will send the welcome card for you to interact with
- - **Valid Scopes:** personal, group chat, team chat
-2. **MentionMe**
- - **Result:** The bot will respond to the message and mention the user
- - **Valid Scopes:** personal, group chat, team chat
-3. **MessageAllMembers**
- - **Result:** The bot will send a 1-on-1 message to each member in the current conversation (aka on the conversation's roster).
- - **Valid Scopes:** personal, group chat, team chat
+1) Selecting the **Create Card** command from the Compose Box command list. The parameters dialog will be displayed and can be submitted to initiate the card creation within the Messaging Extension code.
-You can select an option from the command list by typing ```@TeamsConversationBot``` into the compose message area and ```What can I do?``` text above the compose area.
+or
+2) Selecting the **Share Message** command from the Message command list.
### Avoiding Permission-Related Errors
You may encounter permission-related errors when sending a proactive message. This can often be mitigated by using `MicrosoftAppCredentials.TrustServiceUrl()`. See [the documentation](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-proactive-message?view=azure-bot-service-4.0&tabs=csharp#avoiding-401-unauthorized-errors) for more information.
diff --git a/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java b/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
index ed13ac0eb..bbb843d87 100644
--- a/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
+++ b/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
@@ -3,32 +3,13 @@
package com.microsoft.bot.sample.teamsaction;
-import com.codepoetics.protonpack.collectors.CompletableFutures;
-import com.microsoft.bot.builder.BotFrameworkAdapter;
-import com.microsoft.bot.builder.MessageFactory;
import com.microsoft.bot.builder.TurnContext;
import com.microsoft.bot.builder.teams.TeamsActivityHandler;
-import com.microsoft.bot.builder.teams.TeamsInfo;
-import com.microsoft.bot.connector.authentication.MicrosoftAppCredentials;
import com.microsoft.bot.integration.Configuration;
-import com.microsoft.bot.schema.ActionTypes;
-import com.microsoft.bot.schema.Activity;
-import com.microsoft.bot.schema.CardAction;
-import com.microsoft.bot.schema.ConversationParameters;
-import com.microsoft.bot.schema.ConversationReference;
import com.microsoft.bot.schema.HeroCard;
-import com.microsoft.bot.schema.Mention;
-import com.microsoft.bot.schema.teams.TeamInfo;
-import com.microsoft.bot.schema.teams.TeamsChannelAccount;
-import org.apache.commons.lang3.StringUtils;
+import com.microsoft.bot.schema.teams.*;
import org.springframework.stereotype.Component;
-
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
@@ -50,163 +31,73 @@ public TeamsMessagingExtensionsActionBot(Configuration configuration) {
}
@Override
- protected CompletableFuture onMessageActivity(TurnContext turnContext) {
- turnContext.getActivity().removeRecipientMention();
-
- switch (turnContext.getActivity().getText().trim()) {
- case "MentionMe":
- return mentionActivity(turnContext);
-
- case "UpdateCardAction":
- return updateCardActivity(turnContext);
-
- case "Delete":
- return deleteCardActivity(turnContext);
-
- case "MessageAllMembers":
- return messageAllMembers(turnContext);
-
+ protected CompletableFuture onTeamsMessagingExtensionSubmitAction(
+ TurnContext turnContext,
+ MessagingExtensionAction action) {
+ switch (action.getCommandId()) {
+ // These commandIds are defined in the Teams App Manifest.
+ case "createCard":
+ return createCardCommand(turnContext, action);
+
+ case "shareMessage":
+ return shareMessageCommand(turnContext, action);
default:
- // This will come back deserialized as a Map.
- Object value = new Object() {
- int count = 0;
- };
-
- HeroCard card = new HeroCard() {{
- setTitle("Welcome Card");
- setText("Click the buttons below to update this card");
- setButtons(Arrays.asList(
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Update Card");
- setText("UpdateCardAction");
- setValue(value);
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Message All Members");
- setText("MessageAllMembers");
- }}
- ));
- }};
-
- return turnContext.sendActivity(MessageFactory.attachment(card.toAttachment()))
- .thenApply(resourceResponse -> null);
+ return notImplemented(String.format("Invalid CommandId: %s", action.getCommandId()));
}
}
- @Override
- protected CompletableFuture onTeamsMembersAdded(
- List membersAdded,
- TeamInfo teamInfo,
- TurnContext turnContext
+ private CompletableFuture createCardCommand(
+ TurnContext turnContext,
+ MessagingExtensionAction action
) {
- return membersAdded.stream()
- .filter(member -> !StringUtils.equals(member.getId(), turnContext.getActivity().getRecipient().getId()))
- .map(channel -> turnContext.sendActivity(
- MessageFactory.text("Welcome to the team " + channel.getGivenName() + " " + channel.getSurname() + ".")))
- .collect(CompletableFutures.toFutureList())
- .thenApply(resourceResponses -> null);
- }
-
- private CompletableFuture deleteCardActivity(TurnContext turnContext) {
- return turnContext.deleteActivity(turnContext.getActivity().getReplyToId());
- }
+ LinkedHashMap actionData = (LinkedHashMap) action.getData();
- // If you encounter permission-related errors when sending this message, see
- // https://aka.ms/BotTrustServiceUrl
- private CompletableFuture messageAllMembers(TurnContext turnContext) {
- String teamsChannelId = turnContext.getActivity().teamsGetChannelId();
- String serviceUrl = turnContext.getActivity().getServiceUrl();
- MicrosoftAppCredentials credentials = new MicrosoftAppCredentials(appId, appPassword);
-
- return TeamsInfo.getMembers(turnContext)
- .thenCompose(members -> {
- List> conversations = new ArrayList<>();
-
- // Send a message to each member. These will all go out
- // at the same time.
- for (TeamsChannelAccount member : members) {
- Activity proactiveMessage = MessageFactory.text(
- "Hello " + member.getGivenName() + " " + member.getSurname()
- + ". I'm a Teams conversation bot.");
-
- ConversationParameters conversationParameters = new ConversationParameters() {{
- setIsGroup(false);
- setBot(turnContext.getActivity().getRecipient());
- setMembers(Collections.singletonList(member));
- setTenantId(turnContext.getActivity().getConversation().getTenantId());
- }};
-
- conversations.add(
- ((BotFrameworkAdapter) turnContext.getAdapter()).createConversation(
- teamsChannelId,
- serviceUrl,
- credentials,
- conversationParameters,
- (context) -> {
- ConversationReference reference = context.getActivity().getConversationReference();
- return context.getAdapter().continueConversation(
- appId,
- reference,
- (inner_context) -> inner_context.sendActivity(proactiveMessage)
- .thenApply(resourceResponse -> null)
- );
- }
- )
- );
- }
+ HeroCard card = new HeroCard() {{
+ setTitle((String) actionData.get("title"));
+ setSubtitle((String) actionData.get("subTitle"));
+ setText((String) actionData.get("text"));
+ }};
- return CompletableFuture.allOf(conversations.toArray(new CompletableFuture[0]));
- })
- // After all member messages are sent, send confirmation to the user.
- .thenApply(conversations -> turnContext.sendActivity(MessageFactory.text("All messages have been sent.")))
- .thenApply(allSent -> null);
+ List attachments = new ArrayList();
+ attachments.add(new MessagingExtensionAttachment(){{
+ setContent(card);
+ setContentType(HeroCard.CONTENTTYPE);
+ setPreview(card.toAttachment());
+ }});
+
+ return CompletableFuture.completedFuture(new MessagingExtensionActionResponse(){{
+ setComposeExtension(new MessagingExtensionResult(){{
+ setAttachmentLayout("list");
+ setType("result");
+ setAttachments(attachments);
+ }});
+ }});
}
- private CompletableFuture updateCardActivity(TurnContext turnContext) {
- Map data = (Map) turnContext.getActivity().getValue();
- data.put("count", (int) data.get("count") + 1);
+ private CompletableFuture shareMessageCommand(
+ TurnContext turnContext,
+ MessagingExtensionAction action
+ ) {
HeroCard card = new HeroCard() {{
- setTitle("Welcome Card");
- setText("Update count - " + data.get("count"));
- setButtons(Arrays.asList(
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Update Card");
- setText("UpdateCardAction");
- setValue(data);
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Message All Members");
- setText("MessageAllMembers");
- }},
- new CardAction() {{
- setType(ActionTypes.MESSAGE_BACK);
- setTitle("Delete card");
- setText("Delete");
- }}
- ));
+ setTitle("Test");
+ setText("Test");
}};
- Activity updatedActivity = MessageFactory.attachment(card.toAttachment());
- updatedActivity.setId(turnContext.getActivity().getReplyToId());
-
- return turnContext.updateActivity(updatedActivity)
- .thenApply(resourceResponse -> null);
- }
-
- private CompletableFuture mentionActivity(TurnContext turnContext) {
- Mention mention = new Mention();
- mention.setMentioned(turnContext.getActivity().getFrom());
- mention.setText("" + URLEncoder.encode(turnContext.getActivity().getFrom().getName()) + "");
-
- Activity replyActivity = MessageFactory.text("Hello " + mention.getText() + ".'");
- replyActivity.setMentions(Collections.singletonList(mention));
+ if (action.getMessagePayload().getAttachments() != null && !action.getMessagePayload().getAttachments().isEmpty()) {
+ card.setSubtitle("Test");
+ }
- return turnContext.sendActivity(replyActivity)
- .thenApply(resourceResponse -> null);
+ return CompletableFuture.completedFuture(new MessagingExtensionActionResponse(){{
+ setComposeExtension(new MessagingExtensionResult(){{
+ setAttachmentLayout("list");
+ setType("result");
+ setAttachments(Arrays.asList(new MessagingExtensionAttachment(){{
+ setContent(card);
+ setContentType(HeroCard.CONTENTTYPE);
+ setPreview(card.toAttachment());
+ }}));
+ }});
+ }});
}
}
From 756f07312bba01f1a4db70b2373bd1431bea3e55 Mon Sep 17 00:00:00 2001
From: Emilio Munoz
Date: Fri, 10 Apr 2020 02:34:14 -0700
Subject: [PATCH 016/354] Fixing format
---
.../teamssearch/TeamsMessagingExtensionsSearchBot.java | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java b/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
index 0093aa5e2..64cba5f5c 100644
--- a/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
+++ b/samples/50.teams-messaging-extensions-search/src/main/java/com/microsoft/bot/sample/teamssearch/TeamsMessagingExtensionsSearchBot.java
@@ -35,8 +35,9 @@ public TeamsMessagingExtensionsSearchBot(Configuration configuration) {
}
@Override
- protected CompletableFuture onTeamsMessagingExtensionQuery(TurnContext turnContext,
- MessagingExtensionQuery query) {
+ protected CompletableFuture onTeamsMessagingExtensionQuery(
+ TurnContext turnContext,
+ MessagingExtensionQuery query) {
List queryParams = query.getParameters();
String text = "";
if (queryParams != null && !queryParams.isEmpty()) {
@@ -121,7 +122,8 @@ protected CompletableFuture onTeamsMessagingExtensio
return CompletableFuture.completedFuture(new MessagingExtensionResponse(composeExtension));
}
- private CompletableFuture> FindPackages(String text) throws IOException {
+ private CompletableFuture> FindPackages(
+ String text) throws IOException {
return CompletableFuture.supplyAsync(() -> {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
From f8cd39f99bc2e46d042b0b929fb046b4eacb0dd6 Mon Sep 17 00:00:00 2001
From: Emilio Munoz
Date: Fri, 10 Apr 2020 15:27:08 -0700
Subject: [PATCH 017/354] Adding missing pieces to sample
---
.../TeamsMessagingExtensionsActionBot.java | 27 ++++++++++++-------
1 file changed, 18 insertions(+), 9 deletions(-)
diff --git a/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java b/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
index bbb843d87..0656dc48f 100644
--- a/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
+++ b/samples/51.teams-messaging-extensions-action/src/main/java/com/microsoft/bot/sample/teamsaction/TeamsMessagingExtensionsActionBot.java
@@ -6,6 +6,7 @@
import com.microsoft.bot.builder.TurnContext;
import com.microsoft.bot.builder.teams.TeamsActivityHandler;
import com.microsoft.bot.integration.Configuration;
+import com.microsoft.bot.schema.CardImage;
import com.microsoft.bot.schema.HeroCard;
import com.microsoft.bot.schema.teams.*;
import org.springframework.stereotype.Component;
@@ -16,9 +17,8 @@
* This class implements the functionality of the Bot.
*
*
This is where application specific logic for interacting with the users would be
- * added. For this sample, the {@link #onMessageActivity(TurnContext)} echos the text
- * back to the user. The {@link #onMembersAdded(List, TurnContext)} will send a greeting
- * to new conversation participants.
+ * added. There are two basic types of Messaging Extension in Teams: Search-based and Action-based.
+ * This sample illustrates how to build an Action-based Messaging Extension.
*/
@Component
public class TeamsMessagingExtensionsActionBot extends TeamsActivityHandler {
@@ -58,8 +58,7 @@ private CompletableFuture createCardCommand(
setText((String) actionData.get("text"));
}};
- List attachments = new ArrayList();
- attachments.add(new MessagingExtensionAttachment(){{
+ List attachments = Arrays.asList(new MessagingExtensionAttachment(){{
setContent(card);
setContentType(HeroCard.CONTENTTYPE);
setPreview(card.toAttachment());
@@ -67,9 +66,9 @@ private CompletableFuture createCardCommand(
return CompletableFuture.completedFuture(new MessagingExtensionActionResponse(){{
setComposeExtension(new MessagingExtensionResult(){{
+ setAttachments(attachments);
setAttachmentLayout("list");
setType("result");
- setAttachments(attachments);
}});
}});
}
@@ -79,13 +78,23 @@ private CompletableFuture shareMessageCommand(
MessagingExtensionAction action
) {
+ LinkedHashMap actionData = (LinkedHashMap) action.getData();
+
HeroCard card = new HeroCard() {{
- setTitle("Test");
- setText("Test");
+ setTitle(action.getMessagePayload().getFrom().getUser().getDisplayName());
+ setText(action.getMessagePayload().getBody().getContent());
}};
if (action.getMessagePayload().getAttachments() != null && !action.getMessagePayload().getAttachments().isEmpty()) {
- card.setSubtitle("Test");
+ card.setSubtitle("Attachments not included)");
+ }
+
+ boolean includeImage = actionData.get("includeImage") != null ? (Boolean.valueOf((String) actionData.get("includeImage"))) : false;
+ if (includeImage)
+ {
+ card.setImages(Arrays.asList(new CardImage(){{
+ setUrl("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtB3AwMUeNoq4gUBGe6Ocj8kyh3bXa9ZbV7u1fVKQoyKFHdkqU");
+ }}));
}
return CompletableFuture.completedFuture(new MessagingExtensionActionResponse(){{
From adedcfa6c0547b396be22d5c744ca78307e232ed Mon Sep 17 00:00:00 2001
From: Emilio Munoz
Date: Fri, 10 Apr 2020 15:30:50 -0700
Subject: [PATCH 018/354] Adding non empty check
---
.../bot/schema/teams/MessagingExtensionActionResponse.java | 2 ++
.../microsoft/bot/schema/teams/MessagingExtensionResult.java | 3 +++
2 files changed, 5 insertions(+)
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionActionResponse.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionActionResponse.java
index 895a99532..48115303e 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionActionResponse.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionActionResponse.java
@@ -3,6 +3,7 @@
package com.microsoft.bot.schema.teams;
+import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
@@ -10,6 +11,7 @@
*/
public class MessagingExtensionActionResponse {
@JsonProperty(value = "task")
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
private TaskModuleResponseBase task;
@JsonProperty(value = "composeExtension")
diff --git a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
index 7c8d200f3..33ab3cdd2 100644
--- a/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
+++ b/libraries/bot-schema/src/main/java/com/microsoft/bot/schema/teams/MessagingExtensionResult.java
@@ -25,12 +25,15 @@ public class MessagingExtensionResult {
private List attachments;
@JsonProperty(value = "suggestedActions")
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
private MessagingExtensionSuggestedAction suggestedActions;
@JsonProperty(value = "text")
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
private String text;
@JsonProperty(value = "activityPreview")
+ @JsonInclude(JsonInclude.Include.NON_EMPTY)
private Activity activityPreview;
/**
From e055be7927cc89b7596b7ff8c6f37fcddd58e5d8 Mon Sep 17 00:00:00 2001
From: tracyboehrer
Date: Sun, 12 Apr 2020 16:00:31 -0500
Subject: [PATCH 019/354] Code formatting changes - No logic changes
---
README.md | 28 +-
etc/bot-checkstyle.xml | 4 +-
etc/botframework-java-formatter.xml | 365 ++++++
.../bot/builder/ActivityHandler.java | 510 ++++----
.../bot/builder/AutoSaveStateMiddleware.java | 12 +-
.../java/com/microsoft/bot/builder/Bot.java | 5 +-
.../com/microsoft/bot/builder/BotAdapter.java | 163 +--
.../bot/builder/BotFrameworkAdapter.java | 1064 ++++++++++-------
.../com/microsoft/bot/builder/BotState.java | 150 ++-
.../microsoft/bot/builder/BotStateSet.java | 20 +-
.../bot/builder/BotTelemetryClient.java | 96 +-
.../bot/builder/ConversationState.java | 9 +-
.../bot/builder/DelegatingTurnContext.java | 13 +-
.../bot/builder/DeleteActivityHandler.java | 25 +-
.../microsoft/bot/builder/IntentScore.java | 6 +-
.../microsoft/bot/builder/InvokeResponse.java | 23 +-
.../microsoft/bot/builder/MemoryStorage.java | 42 +-
.../bot/builder/MemoryTranscriptStore.java | 85 +-
.../microsoft/bot/builder/MessageFactory.java | 217 ++--
.../com/microsoft/bot/builder/Middleware.java | 65 +-
.../microsoft/bot/builder/MiddlewareSet.java | 69 +-
.../microsoft/bot/builder/NextDelegate.java | 1 +
.../bot/builder/NullBotTelemetryClient.java | 48 +-
.../microsoft/bot/builder/PagedResult.java | 8 +-
.../bot/builder/PrivateConversationState.java | 21 +-
.../bot/builder/PropertyManager.java | 2 +-
.../com/microsoft/bot/builder/Recognizer.java | 3 +-
.../bot/builder/RecognizerConvert.java | 1 +
.../bot/builder/RecognizerResult.java | 42 +-
.../bot/builder/SendActivitiesHandler.java | 8 +-
.../com/microsoft/bot/builder/Severity.java | 2 +
.../bot/builder/ShowTypingMiddleware.java | 84 +-
.../SkypeMentionNormalizeMiddleware.java | 32 +-
.../bot/builder/StatePropertyAccessor.java | 15 +-
.../bot/builder/StatePropertyInfo.java | 1 +
.../com/microsoft/bot/builder/Storage.java | 6 +-
.../com/microsoft/bot/builder/StoreItem.java | 2 +
.../bot/builder/TelemetryLoggerConstants.java | 3 +-
.../builder/TelemetryLoggerMiddleware.java | 287 +++--
.../bot/builder/TraceTranscriptLogger.java | 3 +-
.../microsoft/bot/builder/TranscriptInfo.java | 14 +-
.../builder/TranscriptLoggerMiddleware.java | 73 +-
.../bot/builder/TranscriptStore.java | 44 +-
.../microsoft/bot/builder/TurnContext.java | 204 ++--
.../bot/builder/TurnContextImpl.java | 242 ++--
.../builder/TurnContextStateCollection.java | 22 +-
.../bot/builder/UpdateActivityHandler.java | 33 +-
.../com/microsoft/bot/builder/UserState.java | 16 +-
.../bot/builder/UserTokenProvider.java | 115 +-
.../InspectionActivityExtensions.java | 15 +-
.../inspection/InspectionMiddleware.java | 284 +++--
.../builder/inspection/InspectionSession.java | 27 +-
.../builder/inspection/InspectionState.java | 2 +-
.../inspection/InterceptionMiddleware.java | 135 ++-
.../integration/AdapterIntegration.java | 43 +-
.../builder/teams/TeamsActivityHandler.java | 258 ++--
.../bot/builder/teams/TeamsInfo.java | 174 ++-
.../bot/builder/ActivityHandlerTests.java | 251 ++--
.../builder/AnonymousReceiveMiddleware.java | 12 +-
.../builder/AutoSaveStateMiddlewareTests.java | 166 +--
.../bot/builder/BotAdapterBracketingTest.java | 74 +-
.../bot/builder/BotAdapterTests.java | 57 +-
.../bot/builder/BotFrameworkAdapterTests.java | 110 +-
.../microsoft/bot/builder/BotStateTests.java | 185 +--
.../bot/builder/CatchExceptionMiddleware.java | 36 +-
.../bot/builder/InspectionTests.java | 173 ++-
.../microsoft/bot/builder/MentionTests.java | 48 +-
.../bot/builder/MessageFactoryTests.java | 362 ++++--
.../bot/builder/MiddlewareSetTest.java | 89 +-
.../bot/builder/OnTurnErrorTests.java | 24 +-
.../builder/ShowTypingMiddlewareTests.java | 45 +-
.../microsoft/bot/builder/SimpleAdapter.java | 35 +-
.../bot/builder/StorageBaseTests.java | 196 ++-
.../bot/builder/TelemetryMiddlewareTests.java | 457 +++----
.../bot/builder/TestAdapterTests.java | 309 +++--
.../microsoft/bot/builder/TestMessage.java | 29 +-
.../microsoft/bot/builder/TestUtilities.java | 26 +-
.../bot/builder/TranscriptBaseTests.java | 147 ++-
.../bot/builder/TranscriptMiddlewareTest.java | 221 ++--
.../bot/builder/TurnContextTests.java | 135 ++-
.../bot/builder/adapters/TestAdapter.java | 316 +++--
.../bot/builder/adapters/TestFlow.java | 349 ++++--
.../bot/builder/base/InterceptorManager.java | 75 +-
.../microsoft/bot/builder/base/TestBase.java | 69 +-
.../TeamsActivityHandlerBadRequestTests.java | 54 +-
.../TeamsActivityHandlerHidingTests.java | 256 ++--
...amsActivityHandlerNotImplementedTests.java | 342 ++++--
.../teams/TeamsActivityHandlerTests.java | 791 +++++++-----
.../bot/builder/teams/TeamsInfoTests.java | 409 ++++---
.../microsoft/bot/connector/Attachments.java | 11 +-
.../microsoft/bot/connector/BotSignIn.java | 18 +-
.../bot/connector/ConnectorClient.java | 18 +-
.../bot/connector/ConnectorConfiguration.java | 9 +-
.../bot/connector/Conversations.java | 316 ++---
.../bot/connector/ExecutorFactory.java | 11 +-
.../microsoft/bot/connector/OAuthClient.java | 2 +
.../bot/connector/OAuthClientConfig.java | 14 +-
.../bot/connector/OAuthClientOld.java.dep | 360 ------
.../microsoft/bot/connector/UserAgent.java | 4 +-
.../microsoft/bot/connector/UserToken.java | 61 +-
.../authentication/AppCredentials.java | 58 +-
.../AppCredentialsInterceptor.java | 9 +-
.../AuthenticationConfiguration.java | 1 +
.../AuthenticationConstants.java | 66 +-
.../AuthenticationException.java | 5 +-
.../authentication/Authenticator.java | 1 +
.../authentication/ChannelProvider.java | 6 +-
.../authentication/ChannelValidation.java | 216 ++--
.../authentication/ClaimsIdentity.java | 8 +-
.../authentication/CredentialProvider.java | 31 +-
.../CredentialsAuthenticator.java | 28 +-
.../authentication/EmulatorValidation.java | 168 ++-
.../authentication/EndorsementsValidator.java | 53 +-
.../EnterpriseChannelValidation.java | 184 +--
.../GovernmentAuthenticationConstants.java | 14 +-
.../GovernmentChannelValidation.java | 153 ++-
.../authentication/JwtTokenExtractor.java | 114 +-
.../authentication/JwtTokenValidation.java | 141 ++-
.../MicrosoftAppCredentials.java | 23 +-
.../MicrosoftGovernmentAppCredentials.java | 1 +
.../authentication/OAuthConfiguration.java | 3 +-
.../authentication/OpenIdMetadata.java | 10 +-
.../bot/connector/authentication/Retry.java | 12 +-
.../authentication/RetryException.java | 5 +-
.../connector/authentication/RetryParams.java | 19 +-
.../authentication/SimpleChannelProvider.java | 13 +-
.../SimpleCredentialProvider.java | 17 +-
.../TokenValidationParameters.java | 38 +-
.../rest/ErrorResponseException.java | 17 +-
.../bot/connector/rest/RestAttachments.java | 132 +-
.../bot/connector/rest/RestBotSignIn.java | 54 +-
.../connector/rest/RestConnectorClient.java | 82 +-
.../bot/connector/rest/RestConversations.java | 651 ++++++----
.../bot/connector/rest/RestOAuthClient.java | 6 +-
.../rest/RestTeamsConnectorClient.java | 77 +-
.../connector/rest/RestTeamsOperations.java | 52 +-
.../bot/connector/rest/RestUserToken.java | 247 ++--
.../connector/teams/TeamsConnectorClient.java | 24 +-
.../bot/connector/teams/TeamsOperations.java | 2 +
.../integration/AdapterWithErrorHandler.java | 71 +-
.../integration/AdapterWithInspection.java | 27 +-
.../integration/BotFrameworkHttpAdapter.java | 27 +-
.../ClasspathPropertiesConfiguration.java | 13 +-
.../bot/integration/Configuration.java | 1 +
.../ConfigurationChannelProvider.java | 8 +-
.../ConfigurationCredentialProvider.java | 1 +
.../bot/integration/spring/BotController.java | 41 +-
.../spring/BotDependencyConfiguration.java | 45 +-
.../microsoft/bot/schema/AadResourceUrls.java | 2 +
.../com/microsoft/bot/schema/ActionTypes.java | 3 +-
.../com/microsoft/bot/schema/Activity.java | 593 +++++----
.../bot/schema/ActivityImportance.java | 3 +-
.../microsoft/bot/schema/ActivityTypes.java | 14 +-
.../microsoft/bot/schema/AnimationCard.java | 24 +-
.../com/microsoft/bot/schema/Attachment.java | 36 +-
.../bot/schema/AttachmentLayoutTypes.java | 3 +-
.../com/microsoft/bot/schema/AudioCard.java | 24 +-
.../com/microsoft/bot/schema/CardAction.java | 27 +-
.../com/microsoft/bot/schema/CardImage.java | 1 +
.../microsoft/bot/schema/ChannelAccount.java | 78 +-
.../ContactRelationUpdateActionTypes.java | 6 +-
.../bot/schema/ConversationAccount.java | 117 +-
.../bot/schema/ConversationMembers.java | 4 +
.../bot/schema/ConversationParameters.java | 18 +-
.../bot/schema/ConversationReference.java | 28 +-
.../microsoft/bot/schema/DeliveryModes.java | 4 +-
.../bot/schema/EndOfConversationCodes.java | 3 +-
.../java/com/microsoft/bot/schema/Entity.java | 33 +-
.../java/com/microsoft/bot/schema/Error.java | 6 +
.../microsoft/bot/schema/ErrorResponse.java | 1 +
.../java/com/microsoft/bot/schema/Fact.java | 6 +-
.../com/microsoft/bot/schema/HeroCard.java | 11 +-
.../microsoft/bot/schema/InnerHttpError.java | 2 +
.../com/microsoft/bot/schema/InputHints.java | 3 +-
.../schema/InstallationUpdateActionTypes.java | 6 +-
.../com/microsoft/bot/schema/MediaCard.java | 13 +-
.../microsoft/bot/schema/MediaEventValue.java | 3 +-
.../microsoft/bot/schema/MessageReaction.java | 12 +-
.../com/microsoft/bot/schema/OAuthCard.java | 11 +-
.../bot/schema/PagedMembersResult.java | 2 +
.../java/com/microsoft/bot/schema/Pair.java | 10 +-
.../java/com/microsoft/bot/schema/Place.java | 7 +-
.../com/microsoft/bot/schema/ReceiptCard.java | 11 +-
.../com/microsoft/bot/schema/ReceiptItem.java | 8 +-
.../bot/schema/ResourceResponse.java | 1 +
.../com/microsoft/bot/schema/ResultPair.java | 6 +-
.../com/microsoft/bot/schema/RoleTypes.java | 3 +-
.../microsoft/bot/schema/SemanticAction.java | 1 +
.../bot/schema/SemanticActionStates.java | 4 +-
.../microsoft/bot/schema/Serialization.java | 26 +-
.../microsoft/bot/schema/SignInConstants.java | 9 +-
.../com/microsoft/bot/schema/SigninCard.java | 11 +-
.../bot/schema/SuggestedActions.java | 23 +-
.../microsoft/bot/schema/TextFormatTypes.java | 3 +-
.../microsoft/bot/schema/ThumbnailCard.java | 11 +-
.../bot/schema/TokenExchangeState.java | 8 +
.../microsoft/bot/schema/TokenResponse.java | 1 +
.../com/microsoft/bot/schema/TokenStatus.java | 8 +
.../com/microsoft/bot/schema/VideoCard.java | 51 +-
.../bot/schema/teams/AppBasedLinkQuery.java | 5 +-
.../schema/teams/AttachmentExtensions.java | 13 +-
.../bot/schema/teams/ChannelInfo.java | 2 +-
.../bot/schema/teams/ConversationList.java | 2 +
.../bot/schema/teams/FileConsentCard.java | 26 +-
.../schema/teams/FileConsentCardResponse.java | 20 +-
.../bot/schema/teams/FileDownloadInfo.java | 8 +
.../bot/schema/teams/FileInfoCard.java | 6 +
.../bot/schema/teams/FileUploadInfo.java | 16 +-
.../schema/teams/MessageActionsPayload.java | 40 +-
.../teams/MessageActionsPayloadApp.java | 15 +-
.../MessageActionsPayloadAttachment.java | 20 +-
.../teams/MessageActionsPayloadBody.java | 4 +
.../MessageActionsPayloadConversation.java | 14 +-
.../teams/MessageActionsPayloadFrom.java | 10 +-
.../teams/MessageActionsPayloadMention.java | 6 +
.../teams/MessageActionsPayloadReaction.java | 16 +-
.../teams/MessageActionsPayloadUser.java | 16 +-
.../teams/MessagingExtensionAction.java | 26 +-
.../MessagingExtensionActionResponse.java | 4 +
.../teams/MessagingExtensionAttachment.java | 2 +
.../teams/MessagingExtensionParameter.java | 4 +
.../schema/teams/MessagingExtensionQuery.java | 14 +-
.../teams/MessagingExtensionQueryOptions.java | 4 +
.../teams/MessagingExtensionResponse.java | 3 +
.../teams/MessagingExtensionResult.java | 37 +-
.../MessagingExtensionSuggestedAction.java | 2 +
.../bot/schema/teams/NotificationInfo.java | 1 +
.../bot/schema/teams/O365ConnectorCard.java | 12 +
.../teams/O365ConnectorCardActionBase.java | 14 +-
.../teams/O365ConnectorCardActionCard.java | 20 +-
.../teams/O365ConnectorCardActionQuery.java | 20 +-
.../teams/O365ConnectorCardDateInput.java | 6 +-
.../schema/teams/O365ConnectorCardFact.java | 4 +
.../teams/O365ConnectorCardHttpPOST.java | 2 +
.../schema/teams/O365ConnectorCardImage.java | 4 +
.../teams/O365ConnectorCardInputBase.java | 21 +-
.../O365ConnectorCardMultichoiceInput.java | 26 +-
...65ConnectorCardMultichoiceInputChoice.java | 4 +
.../teams/O365ConnectorCardOpenUri.java | 2 +
.../teams/O365ConnectorCardOpenUriTarget.java | 12 +-
.../teams/O365ConnectorCardSection.java | 30 +-
.../teams/O365ConnectorCardTextInput.java | 8 +-
.../teams/O365ConnectorCardViewAction.java | 2 +
.../teams/SigninStateVerificationQuery.java | 10 +-
.../bot/schema/teams/TaskModuleAction.java | 8 +-
.../teams/TaskModuleContinueResponse.java | 2 +
.../teams/TaskModuleMessageResponse.java | 2 +
.../bot/schema/teams/TaskModuleRequest.java | 4 +
.../teams/TaskModuleRequestContext.java | 2 +
.../bot/schema/teams/TaskModuleResponse.java | 2 +
.../schema/teams/TaskModuleResponseBase.java | 10 +-
.../bot/schema/teams/TaskModuleTaskInfo.java | 52 +-
.../bot/schema/teams/TeamDetails.java | 10 +
.../microsoft/bot/schema/teams/TeamInfo.java | 4 +-
.../bot/schema/teams/TeamsChannelAccount.java | 10 +
.../bot/schema/teams/TeamsChannelData.java | 46 +-
.../schema/teams/TeamsPagedMembersResult.java | 31 +-
.../microsoft/bot/schema/ActivityTest.java | 311 +++--
.../microsoft/bot/schema/CardActionTest.java | 12 +-
.../schema/EntitySchemaValidationTest.java | 42 +-
.../bot/sample/echo/Application.java | 16 +-
.../microsoft/bot/sample/echo/EchoBot.java | 30 +-
.../bot/sample/welcomeuser/Application.java | 16 +-
.../sample/welcomeuser/WelcomeUserBot.java | 136 ++-
.../sample/welcomeuser/WelcomeUserState.java | 9 +-
.../sample/suggestedactions/Application.java | 16 +-
.../suggestedactions/SuggestedActionsBot.java | 88 +-
.../bot/sample/proactive/Application.java | 20 +-
.../sample/proactive/NotifyController.java | 20 +-
.../bot/sample/proactive/ProactiveBot.java | 39 +-
.../sample/statemanagement/Application.java | 16 +-
.../statemanagement/ConversationData.java | 9 +-
.../statemanagement/StateManagementBot.java | 94 +-
.../sample/statemanagement/UserProfile.java | 9 +-
.../bot/sample/inspection/Application.java | 55 +-
.../bot/sample/inspection/CustomState.java | 13 +-
.../bot/sample/inspection/EchoBot.java | 68 +-
.../sample/teamsconversation/Application.java | 16 +-
.../TeamsConversationBot.java | 197 +--
279 files changed, 11176 insertions(+), 6959 deletions(-)
create mode 100644 etc/botframework-java-formatter.xml
delete mode 100644 libraries/bot-connector/src/main/java/com/microsoft/bot/connector/OAuthClientOld.java.dep
diff --git a/README.md b/README.md
index cebbedc03..819e29404 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additio
This project uses linting rules to enforce code standardization. These rules are specified in the file [bot-checkstyle.xml](./etc/bot-checkstyle.xml) with [CheckStyle](https://checkstyle.org/) and are hooked to Maven's build cycle.
-**INFO**: Since the CheckStyle plugin is hook to the build cycle, this makes the build **fail** in case there are linting warnings in the project files so be sure to check that the code doesn't break any rule.
+**INFO**: Since the CheckStyle and PMD plugins are hooked into the build cycle, this makes the build **fail** in cases where there are linting warnings in the project files. Errors will be in the file ./target/checkstyle-result.xml and ./target/pmd.xml.
CheckStyle is available in different flavours:
- [Visual Studio Code plugin](https://marketplace.visualstudio.com/items?itemName=shengchen.vscode-checkstyle)
@@ -41,6 +41,32 @@ CheckStyle is available in different flavours:
**INFO**: Be sure to configure your IDE to use the file [bot-checkstyle.xml](./etc/bot-checkstyle.xml) instead of the default rules.
+## Build and IDE
+
+Any IDE that can import and work with Maven projects should work. As a matter of practice we use the command line to perform Maven builds. If your IDE can be configured to defer build and run to Maven it should also work.
+- Java
+ - We use the [Azul JDK 8](https://www.azul.com/downloads/azure-only/zulu/?version=java-8-lts&architecture=x86-64-bit&package=jdk) to build and test with. While not a requirement to develop the SDK with, it is recommended as this is what Azure is using for Java 1.8. If you do install this JDK, make sure your IDE is targeting that JVM, and your path (from command line) and JAVA_HOME point to that.
+
+- Visual Studio Code
+ - Extensions
+ - Java Extension Pack by Microsoft
+ - Checkstyle for Java by ShengChen (Optional)
+ - EditorConfig for VS Code by EditorConfig (Recommended)
+ - Recommended setup
+ - Open the settings for "Language Support for Java by RedHat" and set:
+ - Java > Format > Settings: Profile = "BotFramework"
+ - Java > Format > Settings: Url = "etc/botframework-java-formatter.xml"
+ - This will format the code (on command) to BotFramework style.
+
+- IntelliJ
+ - Extensions
+ - Checkstyle by IDEA
+ - Eclipse Code Formatter by Vojtech-Krasa (Recommended)
+ - Recommended setup
+ - When importing the SDK for the first time, make sure "Auto import" is checked.
+ - If the Eclipse Code Formatter was installed:
+ - Got to Settings > Other Settings -> Eclipse Code Formatter, and set the formatter config file to etc/botframework-java-formatter.xml
+
## Reporting Security Issues
Security issues and bugs should be reported privately, via email, to the Microsoft Security
diff --git a/etc/bot-checkstyle.xml b/etc/bot-checkstyle.xml
index 3218d0f7b..41b3575cb 100644
--- a/etc/bot-checkstyle.xml
+++ b/etc/bot-checkstyle.xml
@@ -69,12 +69,12 @@
-
+
diff --git a/etc/botframework-java-formatter.xml b/etc/botframework-java-formatter.xml
new file mode 100644
index 000000000..577eb8d5e
--- /dev/null
+++ b/etc/botframework-java-formatter.xml
@@ -0,0 +1,365 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
index 577be6fc0..2be630d89 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/ActivityHandler.java
@@ -3,41 +3,49 @@
package com.microsoft.bot.builder;
+import java.net.HttpURLConnection;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+
+import org.apache.commons.lang3.StringUtils;
+
import com.microsoft.bot.schema.Activity;
import com.microsoft.bot.schema.ActivityTypes;
import com.microsoft.bot.schema.ChannelAccount;
import com.microsoft.bot.schema.MessageReaction;
import com.microsoft.bot.schema.ResourceResponse;
import com.microsoft.bot.schema.SignInConstants;
-import org.apache.commons.lang3.StringUtils;
-
-import java.net.HttpURLConnection;
-import java.util.List;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionException;
/**
- * An implementation of the {@link Bot} interface intended for further subclassing.
- * Derive from this class to plug in code to handle particular {@link Activity} types.
- * Pre and post processing of Activities can be plugged in by deriving and calling
- * the base class implementation.
+ * An implementation of the {@link Bot} interface intended for further
+ * subclassing. Derive from this class to plug in code to handle particular
+ * {@link Activity} types. Pre and post processing of Activities can be plugged
+ * in by deriving and calling the base class implementation.
*/
public class ActivityHandler implements Bot {
+
/**
- * Called by the adapter (for example, a {@link BotFrameworkAdapter}) at runtime in order
- * to process an inbound {@link Activity}.
- *
- *
This method calls other methods in this class based on the type of the activity to
- * process, which allows a derived class to provide type-specific logic in a controlled way.
- *
- *
In a derived class, override this method to add logic that applies to all activity types.
- * Add logic to apply before the type-specific logic before the call to the base class
+ * Called by the adapter (for example, a {@link BotFrameworkAdapter}) at runtime
+ * in order to process an inbound {@link Activity}.
+ *
+ *
+ * This method calls other methods in this class based on the type of the
+ * activity to process, which allows a derived class to provide type-specific
+ * logic in a controlled way.
+ *
+ *
+ *
+ * In a derived class, override this method to add logic that applies to all
+ * activity types. Add logic to apply before the type-specific logic before the
+ * call to the base class {@link Bot#onTurn(TurnContext)} method. Add logic to
+ * apply after the type-specific logic after the call to the base class
* {@link Bot#onTurn(TurnContext)} method.
- * Add logic to apply after the type-specific logic after the call to the base class
- * {@link Bot#onTurn(TurnContext)} method.
+ *
*
- * @param turnContext The context object for this turn. Provides information about the
- * incoming activity, and other data needed to process the activity.
+ * @param turnContext The context object for this turn. Provides information
+ * about the incoming activity, and other data needed to
+ * process the activity.
* @return A task that represents the work queued to execute.
*/
@Override
@@ -51,36 +59,43 @@ public CompletableFuture onTurn(TurnContext turnContext) {
}
if (turnContext.getActivity().getType() == null) {
- throw new IllegalArgumentException("turnContext.getActivity must have a non-null Type.");
+ throw new IllegalArgumentException(
+ "turnContext.getActivity must have a non-null Type."
+ );
}
switch (turnContext.getActivity().getType()) {
case ActivityTypes.MESSAGE:
return onMessageActivity(turnContext);
+
case ActivityTypes.CONVERSATION_UPDATE:
return onConversationUpdateActivity(turnContext);
+
case ActivityTypes.MESSAGE_REACTION:
return onMessageReactionActivity(turnContext);
+
case ActivityTypes.EVENT:
return onEventActivity(turnContext);
- case ActivityTypes.INVOKE:
- return onInvokeActivity(turnContext)
- .thenCompose(invokeResponse -> {
- // If OnInvokeActivityAsync has already sent an InvokeResponse, do not send another one.
- if (invokeResponse != null
- && turnContext.getTurnState().get(BotFrameworkAdapter.INVOKE_RESPONSE_KEY) == null) {
-
- Activity activity = new Activity(ActivityTypes.INVOKE_RESPONSE);
- activity.setValue(invokeResponse);
- return turnContext.sendActivity(activity);
- }
+ case ActivityTypes.INVOKE:
+ return onInvokeActivity(turnContext).thenCompose(invokeResponse -> {
+ // If OnInvokeActivityAsync has already sent an InvokeResponse, do not send
+ // another one.
+ if (
+ invokeResponse != null && turnContext.getTurnState()
+ .get(BotFrameworkAdapter.INVOKE_RESPONSE_KEY) == null
+ ) {
+
+ Activity activity = new Activity(ActivityTypes.INVOKE_RESPONSE);
+ activity.setValue(invokeResponse);
+
+ return turnContext.sendActivity(activity);
+ }
- CompletableFuture noAction = new CompletableFuture<>();
- noAction.complete(null);
- return noAction;
- })
- .thenApply(response -> null);
+ CompletableFuture noAction = new CompletableFuture<>();
+ noAction.complete(null);
+ return noAction;
+ }).thenApply(response -> null);
default:
return onUnrecognizedActivityType(turnContext);
@@ -88,10 +103,11 @@ public CompletableFuture onTurn(TurnContext turnContext) {
}
/**
- * Override this in a derived class to provide logic specific to {@link ActivityTypes#MESSAGE}
- * activities, such as the conversational logic.
- *
- * When the {@link #onTurn(TurnContext)} method receives a message activity, it calls this method.
+ * Override this in a derived class to provide logic specific to
+ * {@link ActivityTypes#MESSAGE} activities, such as the conversational logic.
+ *
+ * When the {@link #onTurn(TurnContext)} method receives a message activity, it
+ * calls this method.
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -101,17 +117,17 @@ protected CompletableFuture onMessageActivity(TurnContext turnContext) {
}
/**
- * Invoked when a conversation update activity is received from the channel when the base behavior of
- * {@link #onTurn(TurnContext)} is used.
- *
- * Conversation update activities are useful when it comes to responding to users being added to or
- * removed from the conversation.
- *
+ * Invoked when a conversation update activity is received from the channel when
+ * the base behavior of {@link #onTurn(TurnContext)} is used.
+ *
+ * Conversation update activities are useful when it comes to responding to
+ * users being added to or removed from the conversation.
+ *
* For example, a bot could respond to a user being added by greeting the user.
- * By default, this method will call {@link #onMembersAdded(List, TurnContext)} if any users have
- * been added or {@link #onMembersRemoved(List, TurnContext)} if any users have been removed. The
- * method checks the member ID so that it only responds to updates regarding members other than the
- * bot itself.
+ * By default, this method will call {@link #onMembersAdded(List, TurnContext)}
+ * if any users have been added or {@link #onMembersRemoved(List, TurnContext)}
+ * if any users have been removed. The method checks the member ID so that it
+ * only responds to updates regarding members other than the bot itself.
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -119,17 +135,19 @@ protected CompletableFuture onMessageActivity(TurnContext turnContext) {
protected CompletableFuture onConversationUpdateActivity(TurnContext turnContext) {
Activity activity = turnContext.getActivity();
- if (activity.getMembersAdded() != null
- && activity.getRecipient() != null
- && activity.getMembersAdded().stream().anyMatch(
- m -> !StringUtils.equals(m.getId(), activity.getRecipient().getId()))) {
-
+ if (
+ activity.getMembersAdded() != null && activity.getRecipient() != null
+ && activity.getMembersAdded()
+ .stream()
+ .anyMatch(m -> !StringUtils.equals(m.getId(), activity.getRecipient().getId()))
+ ) {
return onMembersAdded(activity.getMembersAdded(), turnContext);
- } else if (activity.getMembersRemoved() != null
- && activity.getRecipient() != null
- && activity.getMembersRemoved().stream()
- .anyMatch(m -> !StringUtils.equals(m.getId(), activity.getRecipient().getId()))) {
-
+ } else if (
+ activity.getMembersRemoved() != null && activity.getRecipient() != null
+ && activity.getMembersRemoved()
+ .stream()
+ .anyMatch(m -> !StringUtils.equals(m.getId(), activity.getRecipient().getId()))
+ ) {
return onMembersRemoved(activity.getMembersRemoved(), turnContext);
}
@@ -137,58 +155,82 @@ protected CompletableFuture onConversationUpdateActivity(TurnContext turnC
}
/**
- * Override this in a derived class to provide logic for when members other than the bot
- * join the conversation, such as your bot's welcome logic.
+ * Override this in a derived class to provide logic for when members other than
+ * the bot join the conversation, such as your bot's welcome logic.
*
- *
When the {@link #onConversationUpdateActivity(TurnContext)} method receives a conversation
- * update activity that indicates one or more users other than the bo are joining the conversation,
- * it calls this method.
+ *
+ * When the {@link #onConversationUpdateActivity(TurnContext)} method receives a
+ * conversation update activity that indicates one or more users other than the
+ * bo are joining the conversation, it calls this method.
+ *
*
- * @param membersAdded A list of all the members added to the conversation, as described by
- * the conversation update activity.
+ * @param membersAdded A list of all the members added to the conversation, as
+ * described by the conversation update activity.
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
*/
- protected CompletableFuture onMembersAdded(List membersAdded, TurnContext turnContext) {
+ protected CompletableFuture onMembersAdded(
+ List membersAdded,
+ TurnContext turnContext
+ ) {
return CompletableFuture.completedFuture(null);
}
/**
- * Override this in a derived class to provide logic for when members other than the bot
- * leave the conversation, such as your bot's good-bye logic.
- *
- *
When the {@link #onConversationUpdateActivity(TurnContext)} method receives a conversation
- * update activity that indicates one or more users other than the bot are leaving the conversation,
- * it calls this method.
- *
- * @param membersRemoved A list of all the members removed from the conversation, as described
- * by the conversation update activity.
+ * Override this in a derived class to provide logic for when members other than
+ * the bot leave the conversation, such as your bot's good-bye logic.
+ *
+ *
+ * When the {@link #onConversationUpdateActivity(TurnContext)} method receives a
+ * conversation update activity that indicates one or more users other than the
+ * bot are leaving the conversation, it calls this method.
+ *
+ *
+ * @param membersRemoved A list of all the members removed from the
+ * conversation, as described by the conversation update
+ * activity.
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
*/
- protected CompletableFuture onMembersRemoved(List membersRemoved, TurnContext turnContext) {
+ protected CompletableFuture onMembersRemoved(
+ List membersRemoved,
+ TurnContext turnContext
+ ) {
return CompletableFuture.completedFuture(null);
}
/**
- * Invoked when an event activity is received from the connector when the base behavior of
- * {@link #onTurn(TurnContext)} is used.
- *
- *
Message reactions correspond to the user adding a 'like' or 'sad' etc. (often an emoji) to a
- * previously sent activity. Message reactions are only supported by a few channels.
- *
- *
The activity that the message reaction corresponds to is indicated in the replyToId property.
- * The value of this property is the activity id of a previously sent activity given back to the
- * bot as the response from a send call.
- *
- *
When the {@link #onTurn(TurnContext)} method receives a message reaction activity, it calls this
- * method. If the message reaction indicates that reactions were added to a message, it calls
- * {@link #onReactionsAdded(List, TurnContext)}. If the message reaction indicates that reactions were
- * removed from a message, it calls {@link #onReactionsRemoved(List, TurnContext)}.
- *
- *
In a derived class, override this method to add logic that applies to all message reaction activities.
- * Add logic to apply before the reactions added or removed logic before the call to the base class
- * method. Add logic to apply after the reactions added or removed logic after the call to the base class.
+ * Invoked when an event activity is received from the connector when the base
+ * behavior of {@link #onTurn(TurnContext)} is used.
+ *
+ *
+ * Message reactions correspond to the user adding a 'like' or 'sad' etc. (often
+ * an emoji) to a previously sent activity. Message reactions are only supported
+ * by a few channels.
+ *
+ *
+ *
+ * The activity that the message reaction corresponds to is indicated in the
+ * replyToId property. The value of this property is the activity id of a
+ * previously sent activity given back to the bot as the response from a send
+ * call.
+ *
+ *
+ *
+ * When the {@link #onTurn(TurnContext)} method receives a message reaction
+ * activity, it calls this method. If the message reaction indicates that
+ * reactions were added to a message, it calls
+ * {@link #onReactionsAdded(List, TurnContext)}. If the message reaction
+ * indicates that reactions were removed from a message, it calls
+ * {@link #onReactionsRemoved(List, TurnContext)}.
+ *
+ *
+ *
+ * In a derived class, override this method to add logic that applies to all
+ * message reaction activities. Add logic to apply before the reactions added or
+ * removed logic before the call to the base class method. Add logic to apply
+ * after the reactions added or removed logic after the call to the base class.
+ *
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -202,10 +244,15 @@ protected CompletableFuture onMessageReactionActivity(TurnContext turnCont
if (turnContext.getActivity().getReactionsRemoved() != null) {
if (task != null) {
- task.thenApply((result) -> onReactionsRemoved(
- turnContext.getActivity().getReactionsRemoved(), turnContext));
+ task.thenApply(
+ result -> onReactionsRemoved(
+ turnContext.getActivity().getReactionsRemoved(), turnContext
+ )
+ );
} else {
- task = onReactionsRemoved(turnContext.getActivity().getReactionsRemoved(), turnContext);
+ task = onReactionsRemoved(
+ turnContext.getActivity().getReactionsRemoved(), turnContext
+ );
}
}
@@ -213,70 +260,97 @@ protected CompletableFuture onMessageReactionActivity(TurnContext turnCont
}
/**
- * Override this in a derived class to provide logic for when reactions to a previous activity
- * are added to the conversation.
- *
- *
Message reactions correspond to the user adding a 'like' or 'sad' etc. (often an emoji) to a
- * previously sent message on the conversation. Message reactions are supported by only a few channels.
- * The activity that the message is in reaction to is identified by the activity's
- * {@link Activity#getReplyToId()} property. The value of this property is the activity ID
- * of a previously sent activity. When the bot sends an activity, the channel assigns an ID to it,
- * which is available in the {@link com.microsoft.bot.schema.ResourceResponse#getId} of the result.
+ * Override this in a derived class to provide logic for when reactions to a
+ * previous activity are added to the conversation.
+ *
+ *
+ * Message reactions correspond to the user adding a 'like' or 'sad' etc. (often
+ * an emoji) to a previously sent message on the conversation. Message reactions
+ * are supported by only a few channels. The activity that the message is in
+ * reaction to is identified by the activity's {@link Activity#getReplyToId()}
+ * property. The value of this property is the activity ID of a previously sent
+ * activity. When the bot sends an activity, the channel assigns an ID to it,
+ * which is available in the
+ * {@link com.microsoft.bot.schema.ResourceResponse#getId} of the result.
+ *
*
* @param messageReactions The list of reactions added.
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
*/
- protected CompletableFuture onReactionsAdded(List messageReactions,
- TurnContext turnContext) {
+ protected CompletableFuture onReactionsAdded(
+ List messageReactions,
+ TurnContext turnContext
+ ) {
return CompletableFuture.completedFuture(null);
}
/**
- * Override this in a derived class to provide logic for when reactions to a previous activity
- * are removed from the conversation.
- *
- *
Message reactions correspond to the user adding a 'like' or 'sad' etc. (often an emoji) to a
- * previously sent message on the conversation. Message reactions are supported by only a few channels.
- * The activity that the message is in reaction to is identified by the activity's
- * {@link Activity#getReplyToId()} property. The value of this property is the activity ID
- * of a previously sent activity. When the bot sends an activity, the channel assigns an ID to it,
- * which is available in the {@link com.microsoft.bot.schema.ResourceResponse#getId} of the result.
+ * Override this in a derived class to provide logic for when reactions to a
+ * previous activity are removed from the conversation.
+ *
+ *
+ * Message reactions correspond to the user adding a 'like' or 'sad' etc. (often
+ * an emoji) to a previously sent message on the conversation. Message reactions
+ * are supported by only a few channels. The activity that the message is in
+ * reaction to is identified by the activity's {@link Activity#getReplyToId()}
+ * property. The value of this property is the activity ID of a previously sent
+ * activity. When the bot sends an activity, the channel assigns an ID to it,
+ * which is available in the
+ * {@link com.microsoft.bot.schema.ResourceResponse#getId} of the result.
+ *
*
* @param messageReactions The list of reactions removed.
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
*/
- protected CompletableFuture onReactionsRemoved(List messageReactions,
- TurnContext turnContext) {
+ protected CompletableFuture onReactionsRemoved(
+ List messageReactions,
+ TurnContext turnContext
+ ) {
return CompletableFuture.completedFuture(null);
}
/**
- * Invoked when an event activity is received from the connector when the base behavior of
- * {@link #onTurn(TurnContext)} is used.
- *
- *
Event activities can be used to communicate many different things.
- *
- *
By default, this method will call {@link #onTokenResponseEvent(TurnContext)} if the
- * activity's name is "tokens/response" or {@link #onEvent(TurnContext)} otherwise.
- * "tokens/response" event can be triggered by an {@link com.microsoft.bot.schema.OAuthCard}.
- *
- *
When the {@link #onTurn(TurnContext)} method receives an event activity, it calls this method.
- *
- *
If the event {@link Activity#getName} is `tokens/response`, it calls
- * {@link #onTokenResponseEvent(TurnContext)} otherwise, it calls {@link #onEvent(TurnContext)}.
- *
- *
In a derived class, override this method to add logic that applies to all event activities.
- * Add logic to apply before the specific event-handling logic before the call to the base class
- * method. Add logic to apply after the specific event-handling logic after the call to the base class
- * method.
- *
- *
Event activities communicate programmatic information from a client or channel to a bot.
- * The meaning of an event activity is defined by the {@link Activity#getName} property,
- * which is meaningful within the scope of a channel.
- * A `tokens/response` event can be triggered by an {@link com.microsoft.bot.schema.OAuthCard} or
- * an OAuth prompt.
+ * Invoked when an event activity is received from the connector when the base
+ * behavior of {@link #onTurn(TurnContext)} is used.
+ *
+ *
+ * Event activities can be used to communicate many different things.
+ *
+ *
+ *
+ * By default, this method will call {@link #onTokenResponseEvent(TurnContext)}
+ * if the activity's name is "tokens/response" or {@link #onEvent(TurnContext)}
+ * otherwise. "tokens/response" event can be triggered by an
+ * {@link com.microsoft.bot.schema.OAuthCard}.
+ *
+ *
+ *
+ * When the {@link #onTurn(TurnContext)} method receives an event activity, it
+ * calls this method.
+ *
+ *
+ *
+ * If the event {@link Activity#getName} is `tokens/response`, it calls
+ * {@link #onTokenResponseEvent(TurnContext)} otherwise, it calls
+ * {@link #onEvent(TurnContext)}.
+ *
+ *
+ *
+ * In a derived class, override this method to add logic that applies to all
+ * event activities. Add logic to apply before the specific event-handling logic
+ * before the call to the base class method. Add logic to apply after the
+ * specific event-handling logic after the call to the base class method.
+ *
+ *
+ *
+ * Event activities communicate programmatic information from a client or
+ * channel to a bot. The meaning of an event activity is defined by the
+ * {@link Activity#getName} property, which is meaningful within the scope of a
+ * channel. A `tokens/response` event can be triggered by an
+ * {@link com.microsoft.bot.schema.OAuthCard} or an OAuth prompt.
+ *
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -290,35 +364,41 @@ protected CompletableFuture onEventActivity(TurnContext turnContext) {
}
/**
- * Invoked when an invoke activity is received from the connector when the base behavior of
- * onTurn is used.
- *
- * Invoke activities can be used to communicate many different things.
- * By default, this method will call onSignInInvokeAsync if the
- * activity's name is 'signin/verifyState' or 'signin/tokenExchange'.
- *
- * A 'signin/verifyState' or 'signin/tokenExchange' invoke can be triggered by an OAuthCard.
+ * Invoked when an invoke activity is received from the connector when the base
+ * behavior of onTurn is used.
+ *
+ * Invoke activities can be used to communicate many different things. By
+ * default, this method will call onSignInInvokeAsync if the activity's name is
+ * 'signin/verifyState' or 'signin/tokenExchange'.
+ *
+ * A 'signin/verifyState' or 'signin/tokenExchange' invoke can be triggered by
+ * an OAuthCard.
*
* @param turnContext The current TurnContext.
* @return A task that represents the work queued to execute.
*/
protected CompletableFuture onInvokeActivity(TurnContext turnContext) {
- if (StringUtils.equals(turnContext.getActivity().getName(), SignInConstants.VERIFY_STATE_OPERATION_NAME)
- || StringUtils
- .equals(turnContext.getActivity().getName(), SignInConstants.TOKEN_EXCHANGE_OPERATION_NAME)) {
-
- return onSignInInvoke(turnContext)
- .thenApply(aVoid -> createInvokeResponse(null))
+ if (
+ StringUtils.equals(
+ turnContext.getActivity().getName(), SignInConstants.VERIFY_STATE_OPERATION_NAME
+ ) || StringUtils.equals(
+ turnContext.getActivity().getName(), SignInConstants.TOKEN_EXCHANGE_OPERATION_NAME
+ )
+ ) {
+ return onSignInInvoke(turnContext).thenApply(aVoid -> createInvokeResponse(null))
.exceptionally(ex -> {
- if (ex instanceof CompletionException && ex.getCause() instanceof InvokeResponseExcetion) {
- InvokeResponseExcetion ire = (InvokeResponseExcetion) ex.getCause();
+ if (
+ ex instanceof CompletionException
+ && ex.getCause() instanceof InvokeResponseException
+ ) {
+ InvokeResponseException ire = (InvokeResponseException) ex.getCause();
return new InvokeResponse(ire.statusCode, ire.body);
- } else if (ex instanceof InvokeResponseExcetion) {
- InvokeResponseExcetion ire = (InvokeResponseExcetion) ex;
+ } else if (ex instanceof InvokeResponseException) {
+ InvokeResponseException ire = (InvokeResponseException) ex;
return new InvokeResponse(ire.statusCode, ire.body);
}
return new InvokeResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, null);
- });
+ });
}
CompletableFuture result = new CompletableFuture<>();
@@ -327,28 +407,32 @@ protected CompletableFuture onInvokeActivity(TurnContext turnCon
}
/**
- * Invoked when a 'signin/verifyState' or 'signin/tokenExchange' event is received when the base
- * behavior of onInvokeActivity is used.
- *
- * If using an OAuthPrompt, override this method to forward this Activity to the current dialog.
- * By default, this method does nothing.
- *
- * When the onInvokeActivity method receives an Invoke with a name of `tokens/response`,
- * it calls this method.
- *
- * If your bot uses the OAuthPrompt, forward the incoming Activity to the current dialog.
+ * Invoked when a 'signin/verifyState' or 'signin/tokenExchange' event is
+ * received when the base behavior of onInvokeActivity is used.
+ *
+ * If using an OAuthPrompt, override this method to forward this Activity to the
+ * current dialog. By default, this method does nothing.
+ *
+ * When the onInvokeActivity method receives an Invoke with a name of
+ * `tokens/response`, it calls this method.
+ *
+ * If your bot uses the OAuthPrompt, forward the incoming Activity to the
+ * current dialog.
*
* @param turnContext The current TurnContext.
* @return A task that represents the work queued to execute.
*/
protected CompletableFuture onSignInInvoke(TurnContext turnContext) {
CompletableFuture result = new CompletableFuture<>();
- result.completeExceptionally(new InvokeResponseExcetion(HttpURLConnection.HTTP_NOT_IMPLEMENTED));
+ result.completeExceptionally(
+ new InvokeResponseException(HttpURLConnection.HTTP_NOT_IMPLEMENTED)
+ );
return result;
}
/**
* Creates a success InvokeResponse with the specified body.
+ *
* @param body The body to return in the invoke response.
* @return The InvokeResponse object.
*/
@@ -360,13 +444,17 @@ protected static InvokeResponse createInvokeResponse(Object body) {
* Invoked when a "tokens/response" event is received when the base behavior of
* {@link #onEventActivity(TurnContext)} is used.
*
- *
If using an OAuthPrompt, override this method to forward this {@link Activity} to the
- * current dialog.
+ *
+ * If using an OAuthPrompt, override this method to forward this
+ * {@link Activity} to the current dialog.
+ *
*
- *
By default, this method does nothing.
- *
- * When the {@link #onEventActivity(TurnContext)} method receives an event with a {@link Activity#getName()}
- * of `tokens/response`, it calls this method.
+ *
+ * By default, this method does nothing.
+ *
+ *
+ * When the {@link #onEventActivity(TurnContext)} method receives an event with
+ * a {@link Activity#getName()} of `tokens/response`, it calls this method.
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -376,15 +464,21 @@ protected CompletableFuture onTokenResponseEvent(TurnContext turnContext)
}
/**
- * Invoked when an event other than tokens/response is received when the base behavior of
- * {@link #onEventActivity(TurnContext)} is used.
- *
- *
This method could optionally be overridden if the bot is meant to handle miscellaneous events.
+ * Invoked when an event other than tokens/response is received when the base
+ * behavior of {@link #onEventActivity(TurnContext)} is used.
*
- *
By default, this method does nothing.
+ *
+ * This method could optionally be overridden if the bot is meant to handle
+ * miscellaneous events.
+ *
*
- * When the {@link #onEventActivity(TurnContext)} method receives an event with a {@link Activity#getName()}
- * other than `tokens/response`, it calls this method.
+ *
+ * By default, this method does nothing.
+ *
+ *
+ * When the {@link #onEventActivity(TurnContext)} method receives an event with
+ * a {@link Activity#getName()} other than `tokens/response`, it calls this
+ * method.
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -394,17 +488,25 @@ protected CompletableFuture onEvent(TurnContext turnContext) {
}
/**
- * Invoked when an activity other than a message, conversation update, or event is received
- * when the base behavior of {@link #onTurn(TurnContext)} is used.
+ * Invoked when an activity other than a message, conversation update, or event
+ * is received when the base behavior of {@link #onTurn(TurnContext)} is used.
*
- *
If overridden, this could potentially respond to any of the other activity types like
+ *
+ * If overridden, this could potentially respond to any of the other activity
+ * types like
* {@link com.microsoft.bot.schema.ActivityTypes#CONTACT_RELATION_UPDATE} or
- * {@link com.microsoft.bot.schema.ActivityTypes#END_OF_CONVERSATION}.
When the {@link #onTurn(TurnContext)} method receives an activity that is not a message,
- * conversation update, message reaction, or event activity, it calls this method.
+ *
+ * When the {@link #onTurn(TurnContext)} method receives an activity that is not
+ * a message, conversation update, message reaction, or event activity, it calls
+ * this method.
+ *
*
* @param turnContext The context object for this turn.
* @return A task that represents the work queued to execute.
@@ -416,30 +518,34 @@ protected CompletableFuture onUnrecognizedActivityType(TurnContext turnCon
/**
* InvokeResponse Exception.
*/
- protected class InvokeResponseExcetion extends Exception {
+ protected class InvokeResponseException extends Exception {
+
private int statusCode;
private Object body;
/**
* Initializes new instance with HTTP status code value.
+ *
* @param withStatusCode The HTTP status code.
*/
- public InvokeResponseExcetion(int withStatusCode) {
+ public InvokeResponseException(int withStatusCode) {
this(withStatusCode, null);
}
/**
* Initializes new instance with HTTP status code value.
+ *
* @param withStatusCode The HTTP status code.
- * @param withBody The body. Can be null.
+ * @param withBody The body. Can be null.
*/
- public InvokeResponseExcetion(int withStatusCode, Object withBody) {
+ public InvokeResponseException(int withStatusCode, Object withBody) {
statusCode = withStatusCode;
body = withBody;
}
/**
* Returns an InvokeResponse based on this exception.
+ *
* @return The InvokeResponse value.
*/
public InvokeResponse createInvokeResponse() {
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/AutoSaveStateMiddleware.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/AutoSaveStateMiddleware.java
index def7799b5..93be0cce7 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/AutoSaveStateMiddleware.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/AutoSaveStateMiddleware.java
@@ -7,7 +7,8 @@
import java.util.concurrent.CompletableFuture;
/**
- * Middleware to automatically call .SaveChanges() at the end of the turn for all BotState class it is managing.
+ * Middleware to automatically call .SaveChanges() at the end of the turn for
+ * all BotState class it is managing.
*/
public class AutoSaveStateMiddleware implements Middleware {
/**
@@ -67,15 +68,16 @@ public AutoSaveStateMiddleware add(BotState botState) {
}
/**
- * Middleware implementation which calls savesChanges automatically at the end of the turn.
+ * Middleware implementation which calls savesChanges automatically at the end
+ * of the turn.
*
* @param turnContext The context object for this turn.
- * @param next The delegate to call to continue the bot middleware pipeline.
+ * @param next The delegate to call to continue the bot middleware
+ * pipeline.
* @return A task representing the asynchronous operation.
*/
@Override
public CompletableFuture onTurn(TurnContext turnContext, NextDelegate next) {
- return next.next()
- .thenCompose(result -> botStateSet.saveAllChanges(turnContext));
+ return next.next().thenCompose(result -> botStateSet.saveAllChanges(turnContext));
}
}
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/Bot.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/Bot.java
index 06783d545..b73cfa776 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/Bot.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/Bot.java
@@ -12,8 +12,9 @@ public interface Bot {
/**
* When implemented in a bot, handles an incoming activity.
*
- * @param turnContext The context object for this turn. Provides information about the
- * incoming activity, and other data needed to process the activity.
+ * @param turnContext The context object for this turn. Provides information
+ * about the incoming activity, and other data needed to
+ * process the activity.
* @return A task that represents the work queued to execute.
*/
CompletableFuture onTurn(TurnContext turnContext);
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotAdapter.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotAdapter.java
index c6c1f33f5..9678a0d20 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotAdapter.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotAdapter.java
@@ -12,23 +12,24 @@
import java.util.concurrent.CompletionException;
/**
- * Represents a bot adapter that can connect a bot to a service endpoint.
- * This class is abstract.
- *
The bot adapter encapsulates authentication processes and sends
- * activities to and receives activities from the Bot Connector Service. When your
- * bot receives an activity, the adapter creates a context object, passes it to your
- * bot's application logic, and sends responses back to the user's channel.
- *
Use {@link #use(Middleware)} to add {@link Middleware} objects
- * to your adapter’s middleware collection. The adapter processes and directs
- * incoming activities in through the bot middleware pipeline to your bot’s logic
- * and then back out again. As each activity flows in and out of the bot, each piece
- * of middleware can inspect or act upon the activity, both before and after the bot
- * logic runs.
+ * Represents a bot adapter that can connect a bot to a service endpoint. This
+ * class is abstract.
+ *
+ * The bot adapter encapsulates authentication processes and sends activities to
+ * and receives activities from the Bot Connector Service. When your bot
+ * receives an activity, the adapter creates a context object, passes it to your
+ * bot's application logic, and sends responses back to the user's channel.
+ *
+ *
+ * Use {@link #use(Middleware)} to add {@link Middleware} objects to your
+ * adapter’s middleware collection. The adapter processes and directs incoming
+ * activities in through the bot middleware pipeline to your bot’s logic and
+ * then back out again. As each activity flows in and out of the bot, each piece
+ * of middleware can inspect or act upon the activity, both before and after the
+ * bot logic runs.
+ *
*
- * {@link TurnContext}
- * {@link Activity}
- * {@link Bot}
- * {@link Middleware}
+ * {@link TurnContext} {@link Activity} {@link Bot} {@link Middleware}
*/
public abstract class BotAdapter {
/**
@@ -42,18 +43,22 @@ public abstract class BotAdapter {
private OnTurnErrorHandler onTurnError;
/**
- * Gets the error handler that can catch exceptions in the middleware or application.
+ * Gets the error handler that can catch exceptions in the middleware or
+ * application.
*
- * @return An error handler that can catch exceptions in the middleware or application.
+ * @return An error handler that can catch exceptions in the middleware or
+ * application.
*/
public OnTurnErrorHandler getOnTurnError() {
return onTurnError;
}
/**
- * Sets the error handler that can catch exceptions in the middleware or application.
+ * Sets the error handler that can catch exceptions in the middleware or
+ * application.
*
- * @param withTurnError An error handler that can catch exceptions in the middleware or application.
+ * @param withTurnError An error handler that can catch exceptions in the
+ * middleware or application.
*/
public void setOnTurnError(OnTurnErrorHandler withTurnError) {
onTurnError = withTurnError;
@@ -72,9 +77,9 @@ protected MiddlewareSet getMiddlewareSet() {
* Adds middleware to the adapter's pipeline.
*
* @param middleware The middleware to add.
- * @return The updated adapter object.
- * Middleware is added to the adapter at initialization time.
- * For each turn, the adapter calls middleware in the order in which you added it.
+ * @return The updated adapter object. Middleware is added to the adapter at
+ * initialization time. For each turn, the adapter calls middleware in
+ * the order in which you added it.
*/
public BotAdapter use(Middleware middleware) {
middlewareSet.use(middleware);
@@ -86,14 +91,16 @@ public BotAdapter use(Middleware middleware) {
*
* @param context The context object for the turn.
* @param activities The activities to send.
- * @return A task that represents the work queued to execute.
- * If the activities are successfully sent, the task result contains
- * an array of {@link ResourceResponse} objects containing the IDs that
- * the receiving channel assigned to the activities.
- * {@link TurnContext#onSendActivities(SendActivitiesHandler)}
+ * @return A task that represents the work queued to execute. If the activities
+ * are successfully sent, the task result contains an array of
+ * {@link ResourceResponse} objects containing the IDs that the
+ * receiving channel assigned to the activities.
+ * {@link TurnContext#onSendActivities(SendActivitiesHandler)}
*/
- public abstract CompletableFuture sendActivities(TurnContext context,
- List activities);
+ public abstract CompletableFuture sendActivities(
+ TurnContext context,
+ List activities
+ );
/**
* When overridden in a derived class, replaces an existing activity in the
@@ -101,16 +108,20 @@ public abstract CompletableFuture sendActivities(TurnContext
*
* @param context The context object for the turn.
* @param activity New replacement activity.
- * @return A task that represents the work queued to execute.
- * If the activity is successfully sent, the task result contains
- * a {@link ResourceResponse} object containing the ID that the receiving
- * channel assigned to the activity.
- *
Before calling this, set the ID of the replacement activity to the ID
- * of the activity to replace.
- * {@link TurnContext#onUpdateActivity(UpdateActivityHandler)}
+ * @return A task that represents the work queued to execute. If the activity is
+ * successfully sent, the task result contains a
+ * {@link ResourceResponse} object containing the ID that the receiving
+ * channel assigned to the activity.
+ *
+ * Before calling this, set the ID of the replacement activity to the ID
+ * of the activity to replace.
+ *
+ * {@link TurnContext#onUpdateActivity(UpdateActivityHandler)}
*/
- public abstract CompletableFuture updateActivity(TurnContext context,
- Activity activity);
+ public abstract CompletableFuture updateActivity(
+ TurnContext context,
+ Activity activity
+ );
/**
* When overridden in a derived class, deletes an existing activity in the
@@ -118,37 +129,47 @@ public abstract CompletableFuture updateActivity(TurnContext c
*
* @param context The context object for the turn.
* @param reference Conversation reference for the activity to delete.
- * @return A task that represents the work queued to execute.
- * The {@link ConversationReference#getActivityId} of the conversation
- * reference identifies the activity to delete.
- * {@link TurnContext#onDeleteActivity(DeleteActivityHandler)}
+ * @return A task that represents the work queued to execute. The
+ * {@link ConversationReference#getActivityId} of the conversation
+ * reference identifies the activity to delete.
+ * {@link TurnContext#onDeleteActivity(DeleteActivityHandler)}
*/
- public abstract CompletableFuture deleteActivity(TurnContext context, ConversationReference reference);
+ public abstract CompletableFuture deleteActivity(
+ TurnContext context,
+ ConversationReference reference
+ );
/**
* Starts activity processing for the current bot turn.
*
- * The adapter calls middleware in the order in which you added it.
- * The adapter passes in the context object for the turn and a next delegate,
- * and the middleware calls the delegate to pass control to the next middleware
- * in the pipeline. Once control reaches the end of the pipeline, the adapter calls
- * the {@code callback} method. If a middleware component does not call
- * the next delegate, the adapter does not call any of the subsequent middleware’s
- * {@link Middleware#onTurn(TurnContext, NextDelegate)}
- * methods or the callback method, and the pipeline short circuits.
+ * The adapter calls middleware in the order in which you added it. The adapter
+ * passes in the context object for the turn and a next delegate, and the
+ * middleware calls the delegate to pass control to the next middleware in the
+ * pipeline. Once control reaches the end of the pipeline, the adapter calls the
+ * {@code callback} method. If a middleware component does not call the next
+ * delegate, the adapter does not call any of the subsequent middleware’s
+ * {@link Middleware#onTurn(TurnContext, NextDelegate)} methods or the callback
+ * method, and the pipeline short circuits.
*
- *
When the turn is initiated by a user activity (reactive messaging), the
+ *
+ * When the turn is initiated by a user activity (reactive messaging), the
* callback method will be a reference to the bot's
- * {@link Bot#onTurn(TurnContext)} method. When the turn is
- * initiated by a call to {@link #continueConversation(String, ConversationReference, BotCallbackHandler)}
- * (proactive messaging), the callback method is the callback method that was provided in the call.
+ * {@link Bot#onTurn(TurnContext)} method. When the turn is initiated by a call
+ * to
+ * {@link #continueConversation(String, ConversationReference, BotCallbackHandler)}
+ * (proactive messaging), the callback method is the callback method that was
+ * provided in the call.
+ *
*
* @param context The turn's context object.
* @param callback A callback method to run at the end of the pipeline.
* @return A task that represents the work queued to execute.
* @throws NullPointerException {@code context} is null.
*/
- protected CompletableFuture runPipeline(TurnContext context, BotCallbackHandler callback) {
+ protected CompletableFuture runPipeline(
+ TurnContext context,
+ BotCallbackHandler callback
+ ) {
BotAssert.contextNotNull(context);
// Call any registered Middleware Components looking for ReceiveActivity()
@@ -175,24 +196,30 @@ protected CompletableFuture runPipeline(TurnContext context, BotCallbackHa
* Sends a proactive message to a conversation.
*
* @param botAppId The application ID of the bot. This parameter is ignored in
- * single tenant the Adapters (Console, Test, etc) but is critical to the BotFrameworkAdapter
- * which is multi-tenant aware.
+ * single tenant the Adapters (Console, Test, etc) but is
+ * critical to the BotFrameworkAdapter which is multi-tenant
+ * aware.
* @param reference A reference to the conversation to continue.
* @param callback The method to call for the resulting bot turn.
- * @return A task that represents the work queued to execute.
- * Call this method to proactively send a message to a conversation.
- * Most channels require a user to initiate a conversation with a bot
- * before the bot can send activities to the user.
+ * @return A task that represents the work queued to execute. Call this method
+ * to proactively send a message to a conversation. Most channels
+ * require a user to initiate a conversation with a bot before the bot
+ * can send activities to the user.
*
- * {@link #runPipeline(TurnContext, BotCallbackHandler)}
+ * {@link #runPipeline(TurnContext, BotCallbackHandler)}
*/
- public CompletableFuture continueConversation(String botAppId,
- ConversationReference reference,
- BotCallbackHandler callback) {
+ public CompletableFuture continueConversation(
+ String botAppId,
+ ConversationReference reference,
+ BotCallbackHandler callback
+ ) {
CompletableFuture pipelineResult = new CompletableFuture<>();
- try (TurnContextImpl context = new TurnContextImpl(this, reference.getContinuationActivity())) {
+ try (TurnContextImpl context = new TurnContextImpl(
+ this,
+ reference.getContinuationActivity()
+ )) {
pipelineResult = runPipeline(context, callback);
} catch (Exception e) {
pipelineResult.completeExceptionally(e);
diff --git a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotFrameworkAdapter.java b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotFrameworkAdapter.java
index 3b550ae1f..fa0b90968 100644
--- a/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotFrameworkAdapter.java
+++ b/libraries/bot-builder/src/main/java/com/microsoft/bot/builder/BotFrameworkAdapter.java
@@ -57,23 +57,23 @@
/**
* A bot adapter that can connect a bot to a service endpoint.
*
- * The bot adapter encapsulates authentication processes and sends
- * activities to and receives activities from the Bot Connector Service. When your
- * bot receives an activity, the adapter creates a context object, passes it to your
+ * The bot adapter encapsulates authentication processes and sends activities to
+ * and receives activities from the Bot Connector Service. When your bot
+ * receives an activity, the adapter creates a context object, passes it to your
* bot's application logic, and sends responses back to the user's channel.
- *
Use {@link #use(Middleware)} to add {@link Middleware} objects
- * to your adapter’s middleware collection. The adapter processes and directs
- * incoming activities in through the bot middleware pipeline to your bot’s logic
- * and then back out again. As each activity flows in and out of the bot, each piece
- * of middleware can inspect or act upon the activity, both before and after the bot
- * logic runs.
*
- * {@link TurnContext}
- * {@link Activity}
- * {@link Bot}
- * {@link Middleware}
+ * Use {@link #use(Middleware)} to add {@link Middleware} objects to your
+ * adapter’s middleware collection. The adapter processes and directs incoming
+ * activities in through the bot middleware pipeline to your bot’s logic and
+ * then back out again. As each activity flows in and out of the bot, each piece
+ * of middleware can inspect or act upon the activity, both before and after the
+ * bot logic runs.
+ *
+ *
+ * {@link TurnContext} {@link Activity} {@link Bot} {@link Middleware}
*/
-public class BotFrameworkAdapter extends BotAdapter implements AdapterIntegration, UserTokenProvider {
+public class BotFrameworkAdapter extends BotAdapter
+ implements AdapterIntegration, UserTokenProvider {
/**
* Key to store InvokeResponse.
*/
@@ -90,8 +90,7 @@ public class BotFrameworkAdapter extends BotAdapter implements AdapterIntegratio
public static final String CONNECTOR_CLIENT_KEY = "ConnectorClient";
/**
- * Key to store TeamsConnectorClient.
- * For testing only.
+ * Key to store TeamsConnectorClient. For testing only.
*/
public static final String TEAMSCONNECTOR_CLIENT_KEY = "TeamsConnectorClient";
@@ -128,8 +127,8 @@ public class BotFrameworkAdapter extends BotAdapter implements AdapterIntegratio
private Map connectorClients = new ConcurrentHashMap<>();
/**
- * Initializes a new instance of the {@link BotFrameworkAdapter} class,
- * using a credential provider.
+ * Initializes a new instance of the {@link BotFrameworkAdapter} class, using a
+ * credential provider.
*
* @param withCredentialProvider The credential provider.
*/
@@ -138,41 +137,47 @@ public BotFrameworkAdapter(CredentialProvider withCredentialProvider) {
}
/**
- * Initializes a new instance of the {@link BotFrameworkAdapter} class,
- * using a credential provider.
+ * Initializes a new instance of the {@link BotFrameworkAdapter} class, using a
+ * credential provider.
*
* @param withCredentialProvider The credential provider.
- * @param withChannelProvider The channel provider.
- * @param withRetryStrategy Retry policy for retrying HTTP operations.
- * @param withMiddleware The middleware to initially add to the adapter.
+ * @param withChannelProvider The channel provider.
+ * @param withRetryStrategy Retry policy for retrying HTTP operations.
+ * @param withMiddleware The middleware to initially add to the adapter.
*/
- public BotFrameworkAdapter(CredentialProvider withCredentialProvider,
- ChannelProvider withChannelProvider,
- RetryStrategy withRetryStrategy,
- Middleware withMiddleware) {
-
- this(withCredentialProvider,
- new AuthenticationConfiguration(),
- withChannelProvider,
- withRetryStrategy,
- withMiddleware);
+ public BotFrameworkAdapter(
+ CredentialProvider withCredentialProvider,
+ ChannelProvider withChannelProvider,
+ RetryStrategy withRetryStrategy,
+ Middleware withMiddleware
+ ) {
+
+ this(
+ withCredentialProvider,
+ new AuthenticationConfiguration(),
+ withChannelProvider,
+ withRetryStrategy,
+ withMiddleware
+ );
}
/**
- * Initializes a new instance of the {@link BotFrameworkAdapter} class,
- * using a credential provider.
+ * Initializes a new instance of the {@link BotFrameworkAdapter} class, using a
+ * credential provider.
*
* @param withCredentialProvider The credential provider.
- * @param withAuthConfig The authentication configuration.
- * @param withChannelProvider The channel provider.
- * @param withRetryStrategy Retry policy for retrying HTTP operations.
- * @param withMiddleware The middleware to initially add to the adapter.
+ * @param withAuthConfig The authentication configuration.
+ * @param withChannelProvider The channel provider.
+ * @param withRetryStrategy Retry policy for retrying HTTP operations.
+ * @param withMiddleware The middleware to initially add to the adapter.
*/
- public BotFrameworkAdapter(CredentialProvider withCredentialProvider,
- AuthenticationConfiguration withAuthConfig,
- ChannelProvider withChannelProvider,
- RetryStrategy withRetryStrategy,
- Middleware withMiddleware) {
+ public BotFrameworkAdapter(
+ CredentialProvider withCredentialProvider,
+ AuthenticationConfiguration withAuthConfig,
+ ChannelProvider withChannelProvider,
+ RetryStrategy withRetryStrategy,
+ Middleware withMiddleware
+ ) {
if (withCredentialProvider == null) {
throw new IllegalArgumentException("CredentialProvider cannot be null");
@@ -187,9 +192,12 @@ public BotFrameworkAdapter(CredentialProvider withCredentialProvider,
connectorClientRetryStrategy = withRetryStrategy;
authConfiguration = withAuthConfig;
- // Relocate the tenantId field used by MS Teams to a new location (from channelData to conversation)
- // This will only occur on activities from teams that include tenant info in channelData but NOT in
- // conversation, thus should be future friendly. However, once the transition is complete. we can
+ // Relocate the tenantId field used by MS Teams to a new location (from
+ // channelData to conversation)
+ // This will only occur on activities from teams that include tenant info in
+ // channelData but NOT in
+ // conversation, thus should be future friendly. However, once the transition is
+ // complete. we can
// remove this.
use(new TenantIdWorkaroundForTeamsMiddleware());
@@ -199,21 +207,22 @@ public BotFrameworkAdapter(CredentialProvider withCredentialProvider,
}
/**
- * Initializes a new instance of the {@link BotFrameworkAdapter} class,
- * using a credential provider.
+ * Initializes a new instance of the {@link BotFrameworkAdapter} class, using a
+ * credential provider.
*
- * @param withCredentials The credentials to use.
- * @param withAuthConfig The authentication configuration.
+ * @param withCredentials The credentials to use.
+ * @param withAuthConfig The authentication configuration.
* @param withChannelProvider The channel provider.
- * @param withRetryStrategy Retry policy for retrying HTTP operations.
- * @param withMiddleware The middleware to initially add to the adapter.
+ * @param withRetryStrategy Retry policy for retrying HTTP operations.
+ * @param withMiddleware The middleware to initially add to the adapter.
*/
public BotFrameworkAdapter(
AppCredentials withCredentials,
AuthenticationConfiguration withAuthConfig,
ChannelProvider withChannelProvider,
RetryStrategy withRetryStrategy,
- Middleware withMiddleware) {
+ Middleware withMiddleware
+ ) {
if (withCredentials == null) {
throw new IllegalArgumentException("credentials");
@@ -229,9 +238,12 @@ public BotFrameworkAdapter(
}
authConfiguration = withAuthConfig;
- // Relocate the tenantId field used by MS Teams to a new location (from channelData to conversation)
- // This will only occur on activities from teams that include tenant info in channelData but NOT in
- // conversation, thus should be future friendly. However, once the transition is complete. we can
+ // Relocate the tenantId field used by MS Teams to a new location (from
+ // channelData to conversation)
+ // This will only occur on activities from teams that include tenant info in
+ // channelData but NOT in
+ // conversation, thus should be future friendly. However, once the transition is
+ // complete. we can
// remove this.
use(new TenantIdWorkaroundForTeamsMiddleware());
@@ -243,27 +255,34 @@ public BotFrameworkAdapter(
/**
* Sends a proactive message from the bot to a conversation.
*
- *
Call this method to proactively send a message to a conversation.
- * Most channels require a user to initiate a conversation with a bot
- * before the bot can send activities to the user.
- *
This overload differers from the Node implementation by requiring the BotId to be
- * passed in. The .Net code allows multiple bots to be hosted in a single adapter which
- * isn't something supported by Node.
+ *
+ * Call this method to proactively send a message to a conversation. Most
+ * channels require a user to initiate a conversation with a bot before the bot
+ * can send activities to the user.
+ *
+ *
+ * This overload differers from the Node implementation by requiring the BotId
+ * to be passed in. The .Net code allows multiple bots to be hosted in a single
+ * adapter which isn't something supported by Node.
+ *
*
* {@link #processActivity(String, Activity, BotCallbackHandler)}
* {@link BotAdapter#runPipeline(TurnContext, BotCallbackHandler)}
*
- * @param botAppId The application ID of the bot. This is the appId returned by Portal registration, and is
- * generally found in the "MicrosoftAppId" parameter in appSettings.json.
+ * @param botAppId The application ID of the bot. This is the appId returned by
+ * Portal registration, and is generally found in the
+ * "MicrosoftAppId" parameter in appSettings.json.
* @param reference A reference to the conversation to continue.
* @param callback The method to call for the resulting bot turn.
* @return A task that represents the work queued to execute.
* @throws IllegalArgumentException botAppId, reference, or callback is null.
*/
@Override
- public CompletableFuture continueConversation(String botAppId,
- ConversationReference reference,
- BotCallbackHandler callback) {
+ public CompletableFuture continueConversation(
+ String botAppId,
+ ConversationReference reference,
+ BotCallbackHandler callback
+ ) {
if (StringUtils.isEmpty(botAppId)) {
throw new IllegalArgumentException("botAppId");
}
@@ -278,12 +297,17 @@ public CompletableFuture continueConversation(String botAppId,
CompletableFuture pipelineResult = new CompletableFuture<>();
- try (TurnContextImpl context = new TurnContextImpl(this, reference.getContinuationActivity())) {
+ try (TurnContextImpl context = new TurnContextImpl(
+ this,
+ reference.getContinuationActivity()
+ )) {
// Hand craft Claims Identity.
- HashMap claims = new HashMap() {{
- put(AuthenticationConstants.AUDIENCE_CLAIM, botAppId);
- put(AuthenticationConstants.APPID_CLAIM, botAppId);
- }};
+ HashMap claims = new HashMap() {
+ {
+ put(AuthenticationConstants.AUDIENCE_CLAIM, botAppId);
+ put(AuthenticationConstants.APPID_CLAIM, botAppId);
+ }
+ };
ClaimsIdentity claimsIdentity = new ClaimsIdentity("ExternalBearer", claims);
context.getTurnState().add(BOT_IDENTITY_KEY, claimsIdentity);
@@ -303,8 +327,8 @@ public CompletableFuture continueConversation(String botAppId,
/**
* Adds middleware to the adapter's pipeline.
*
- * Middleware is added to the adapter at initialization time.
- * For each turn, the adapter calls middleware in the order in which you added it.
+ * Middleware is added to the adapter at initialization time. For each turn, the
+ * adapter calls middleware in the order in which you added it.
*
* @param middleware The middleware to add.
* @return The updated adapter object.
@@ -315,42 +339,50 @@ public BotFrameworkAdapter use(Middleware middleware) {
}
/**
- * Creates a turn context and runs the middleware pipeline for an incoming activity.
+ * Creates a turn context and runs the middleware pipeline for an incoming
+ * activity.
*
* @param authHeader The HTTP authentication header of the request.
* @param activity The incoming activity.
* @param callback The code to run at the end of the adapter's middleware
* pipeline.
- * @return A task that represents the work queued to execute. If the activity type
- * was 'Invoke' and the corresponding key (channelId + activityId) was found
- * then an InvokeResponse is returned, otherwise null is returned.
+ * @return A task that represents the work queued to execute. If the activity
+ * type was 'Invoke' and the corresponding key (channelId + activityId)
+ * was found then an InvokeResponse is returned, otherwise null is
+ * returned.
* @throws IllegalArgumentException Activity is null.
*/
- public CompletableFuture processActivity(String authHeader,
- Activity activity,
- BotCallbackHandler callback) {
+ public CompletableFuture processActivity(
+ String authHeader,
+ Activity activity,
+ BotCallbackHandler callback
+ ) {
BotAssert.activityNotNull(activity);
- return JwtTokenValidation
- .authenticateRequest(activity, authHeader, credentialProvider, channelProvider, authConfiguration)
- .thenCompose(claimsIdentity -> processActivity(claimsIdentity, activity, callback));
+ return JwtTokenValidation.authenticateRequest(
+ activity, authHeader, credentialProvider, channelProvider, authConfiguration
+ ).thenCompose(claimsIdentity -> processActivity(claimsIdentity, activity, callback));
}
/**
- * Creates a turn context and runs the middleware pipeline for an incoming activity.
+ * Creates a turn context and runs the middleware pipeline for an incoming
+ * activity.
*
* @param identity A {@link ClaimsIdentity} for the request.
* @param activity The incoming activity.
* @param callback The code to run at the end of the adapter's middleware
* pipeline.
- * @return A task that represents the work queued to execute. If the activity type
- * was 'Invoke' and the corresponding key (channelId + activityId) was found
- * then an InvokeResponse is returned, otherwise null is returned.
+ * @return A task that represents the work queued to execute. If the activity
+ * type was 'Invoke' and the corresponding key (channelId + activityId)
+ * was found then an InvokeResponse is returned, otherwise null is
+ * returned.
* @throws IllegalArgumentException Activity is null.
*/
- public CompletableFuture processActivity(ClaimsIdentity identity,
- Activity activity,
- BotCallbackHandler callback) {
+ public CompletableFuture processActivity(
+ ClaimsIdentity identity,
+ Activity activity,
+ BotCallbackHandler callback
+ ) {
BotAssert.activityNotNull(activity);
CompletableFuture pipelineResult = new CompletableFuture<>();
@@ -366,7 +398,8 @@ public CompletableFuture processActivity(ClaimsIdentity identity
return runPipeline(context, callback);
})
- // Handle Invoke scenarios, which deviate from the request/response model in that
+ // Handle Invoke scenarios, which deviate from the request/response model in
+ // that
// the Bot will return a specific body and return code.
.thenCompose(result -> {
if (activity.isType(ActivityTypes.INVOKE)) {
@@ -376,7 +409,8 @@ public CompletableFuture processActivity(ClaimsIdentity identity
new InvokeResponse(HttpURLConnection.HTTP_NOT_IMPLEMENTED, null)
);
} else {
- return CompletableFuture.completedFuture((InvokeResponse) invokeResponse.getValue());
+ return CompletableFuture
+ .completedFuture((InvokeResponse) invokeResponse.getValue());
}
}
@@ -396,16 +430,19 @@ public CompletableFuture processActivity(ClaimsIdentity identity
*
* @param context The context object for the turn.
* @param activities The activities to send.
- * @return A task that represents the work queued to execute.
- * If the activities are successfully sent, the task result contains
- * an array of {@link ResourceResponse} objects containing the IDs that
- * the receiving channel assigned to the activities.
+ * @return A task that represents the work queued to execute. If the activities
+ * are successfully sent, the task result contains an array of
+ * {@link ResourceResponse} objects containing the IDs that the
+ * receiving channel assigned to the activities.
*
- * {@link TurnContext#onSendActivities(SendActivitiesHandler)}
+ * {@link TurnContext#onSendActivities(SendActivitiesHandler)}
*/
@SuppressWarnings("checkstyle:EmptyBlock")
@Override
- public CompletableFuture sendActivities(TurnContext context, List activities) {
+ public CompletableFuture sendActivities(
+ TurnContext context,
+ List activities
+ ) {
if (context == null) {
throw new IllegalArgumentException("context");
}
@@ -415,16 +452,19 @@ public CompletableFuture sendActivities(TurnContext context,
}
if (activities.size() == 0) {
- throw new IllegalArgumentException("Expecting one or more activities, but the array was empty.");
+ throw new IllegalArgumentException(
+ "Expecting one or more activities, but the array was empty."
+ );
}
return CompletableFuture.supplyAsync(() -> {
ResourceResponse[] responses = new ResourceResponse[activities.size()];
/*
- * NOTE: we're using for here (vs. foreach) because we want to simultaneously index into the
- * activities array to get the activity to process as well as use that index to assign
- * the response to the responses array and this is the most cost effective way to do that.
+ * NOTE: we're using for here (vs. foreach) because we want to simultaneously
+ * index into the activities array to get the activity to process as well as use
+ * that index to assign the response to the responses array and this is the most
+ * cost effective way to do that.
*/
for (int index = 0; index < activities.size(); index++) {
Activity activity = activities.get(index);
@@ -445,29 +485,42 @@ public CompletableFuture sendActivities(TurnContext context,
context.getTurnState().add(INVOKE_RESPONSE_KEY, activity);
// No need to create a response. One will be created below.
response = null;
- } else if (activity.isType(ActivityTypes.TRACE)
- && !StringUtils.equals(activity.getChannelId(), Channels.EMULATOR)) {
+ } else if (
+ activity.isType(ActivityTypes.TRACE)
+ && !StringUtils.equals(activity.getChannelId(), Channels.EMULATOR)
+ ) {
// if it is a Trace activity we only send to the channel if it's the emulator.
response = null;
} else if (!StringUtils.isEmpty(activity.getReplyToId())) {
- ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
+ ConnectorClient connectorClient = context.getTurnState()
+ .get(CONNECTOR_CLIENT_KEY);
response = connectorClient.getConversations().replyToActivity(activity).join();
} else {
- ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
- response = connectorClient.getConversations().sendToConversation(activity).join();
+ ConnectorClient connectorClient = context.getTurnState()
+ .get(CONNECTOR_CLIENT_KEY);
+ response = connectorClient.getConversations()
+ .sendToConversation(activity)
+ .join();
}
- // If No response is set, then default to a "simple" response. This can't really be done
- // above, as there are cases where the ReplyTo/SendTo methods will also return null
+ // If No response is set, then default to a "simple" response. This can't really
+ // be done
+ // above, as there are cases where the ReplyTo/SendTo methods will also return
+ // null
// (See below) so the check has to happen here.
- // Note: In addition to the Invoke / Delay / Activity cases, this code also applies
- // with Skype and Teams with regards to typing events. When sending a typing event in
- // these channels they do not return a RequestResponse which causes the bot to blow up.
+ // Note: In addition to the Invoke / Delay / Activity cases, this code also
+ // applies
+ // with Skype and Teams with regards to typing events. When sending a typing
+ // event in
+ // these channels they do not return a RequestResponse which causes the bot to
+ // blow up.
// https://github.com/Microsoft/botbuilder-dotnet/issues/460
// bug report : https://github.com/Microsoft/botbuilder-dotnet/issues/465
if (response == null) {
- response = new ResourceResponse((activity.getId() == null) ? "" : activity.getId());
+ response = new ResourceResponse(
+ (activity.getId() == null) ? "" : activity.getId()
+ );
}
responses[index] = response;
@@ -482,16 +535,21 @@ public CompletableFuture sendActivities(TurnContext context,
*
* @param context The context object for the turn.
* @param activity New replacement activity.
- * @return A task that represents the work queued to execute.
- * If the activity is successfully sent, the task result contains
- * a {@link ResourceResponse} object containing the ID that the receiving
- * channel assigned to the activity.
- *
Before calling this, set the ID of the replacement activity to the ID
- * of the activity to replace.
- * {@link TurnContext#onUpdateActivity(UpdateActivityHandler)}
+ * @return A task that represents the work queued to execute. If the activity is
+ * successfully sent, the task result contains a
+ * {@link ResourceResponse} object containing the ID that the receiving
+ * channel assigned to the activity.
+ *
+ * Before calling this, set the ID of the replacement activity to the ID
+ * of the activity to replace.
+ *
+ * {@link TurnContext#onUpdateActivity(UpdateActivityHandler)}
*/
@Override
- public CompletableFuture updateActivity(TurnContext context, Activity activity) {
+ public CompletableFuture updateActivity(
+ TurnContext context,
+ Activity activity
+ ) {
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
return connectorClient.getConversations().updateActivity(activity);
}
@@ -502,13 +560,16 @@ public CompletableFuture updateActivity(TurnContext context, A
* @param context The context object for the turn.
* @param reference Conversation reference for the activity to delete.
* @return A task that represents the work queued to execute.
- * {@link TurnContext#onDeleteActivity(DeleteActivityHandler)}
+ * {@link TurnContext#onDeleteActivity(DeleteActivityHandler)}
*/
@Override
- public CompletableFuture deleteActivity(TurnContext context, ConversationReference reference) {
+ public CompletableFuture deleteActivity(
+ TurnContext context,
+ ConversationReference reference
+ ) {
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
- return connectorClient.getConversations().deleteActivity(
- reference.getConversation().getId(), reference.getActivityId());
+ return connectorClient.getConversations()
+ .deleteActivity(reference.getConversation().getId(), reference.getActivityId());
}
/**
@@ -518,20 +579,26 @@ public CompletableFuture deleteActivity(TurnContext context, ConversationR
* @param memberId ID of the member to delete from the conversation
* @return A task that represents the work queued to execute.
*/
- public CompletableFuture deleteConversationMember(TurnContextImpl context, String memberId) {
+ public CompletableFuture deleteConversationMember(
+ TurnContextImpl context,
+ String memberId
+ ) {
if (context.getActivity().getConversation() == null) {
throw new IllegalArgumentException(
- "BotFrameworkAdapter.deleteConversationMember(): missing conversation");
+ "BotFrameworkAdapter.deleteConversationMember(): missing conversation"
+ );
}
if (StringUtils.isEmpty(context.getActivity().getConversation().getId())) {
throw new IllegalArgumentException(
- "BotFrameworkAdapter.deleteConversationMember(): missing conversation.id");
+ "BotFrameworkAdapter.deleteConversationMember(): missing conversation.id"
+ );
}
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
String conversationId = context.getActivity().getConversation().getId();
- return connectorClient.getConversations().deleteConversationMember(conversationId, memberId);
+ return connectorClient.getConversations()
+ .deleteConversationMember(conversationId, memberId);
}
/**
@@ -547,22 +614,30 @@ public CompletableFuture> getActivityMembers(TurnContextImp
/**
* Lists the members of a given activity.
*
- * @param context The context object for the turn.
- * @param activityId (Optional) Activity ID to enumerate. If not specified the current activities ID will be used.
+ * @param context The context object for the turn.
+ * @param activityId (Optional) Activity ID to enumerate. If not specified the
+ * current activities ID will be used.
* @return List of Members of the activity
*/
- public CompletableFuture> getActivityMembers(TurnContextImpl context, String activityId) {
+ public CompletableFuture> getActivityMembers(
+ TurnContextImpl context,
+ String activityId
+ ) {
// If no activity was passed in, use the current activity.
if (activityId == null) {
activityId = context.getActivity().getId();
}
if (context.getActivity().getConversation() == null) {
- throw new IllegalArgumentException("BotFrameworkAdapter.GetActivityMembers(): missing conversation");
+ throw new IllegalArgumentException(
+ "BotFrameworkAdapter.GetActivityMembers(): missing conversation"
+ );
}
if (StringUtils.isEmpty(context.getActivity().getConversation().getId())) {
- throw new IllegalArgumentException("BotFrameworkAdapter.GetActivityMembers(): missing conversation.id");
+ throw new IllegalArgumentException(
+ "BotFrameworkAdapter.GetActivityMembers(): missing conversation.id"
+ );
}
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
@@ -579,11 +654,15 @@ public CompletableFuture> getActivityMembers(TurnContextImp
*/
public CompletableFuture> getConversationMembers(TurnContextImpl context) {
if (context.getActivity().getConversation() == null) {
- throw new IllegalArgumentException("BotFrameworkAdapter.GetActivityMembers(): missing conversation");
+ throw new IllegalArgumentException(
+ "BotFrameworkAdapter.GetActivityMembers(): missing conversation"
+ );
}
if (StringUtils.isEmpty(context.getActivity().getConversation().getId())) {
- throw new IllegalArgumentException("BotFrameworkAdapter.GetActivityMembers(): missing conversation.id");
+ throw new IllegalArgumentException(
+ "BotFrameworkAdapter.GetActivityMembers(): missing conversation.id"
+ );
}
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
@@ -593,40 +672,50 @@ public CompletableFuture> getConversationMembers(TurnContex
}
/**
- * Lists the Conversations in which this bot has participated for a given channel server. The
- * channel server returns results in pages and each page will include a `continuationToken`
- * that can be used to fetch the next page of results from the server.
+ * Lists the Conversations in which this bot has participated for a given
+ * channel server. The channel server returns results in pages and each page
+ * will include a `continuationToken` that can be used to fetch the next page of
+ * results from the server.
*
- * @param serviceUrl The URL of the channel server to query. This can be retrieved
- * from `context.activity.serviceUrl`.
- * @param credentials The credentials needed for the Bot to connect to the.services().
+ * @param serviceUrl The URL of the channel server to query. This can be
+ * retrieved from `context.activity.serviceUrl`.
+ * @param credentials The credentials needed for the Bot to connect to
+ * the.services().
* @return List of Members of the current conversation
- *
- * This overload may be called from outside the context of a conversation, as only the
- * Bot's ServiceUrl and credentials are required.
+ *
+ * This overload may be called from outside the context of a
+ * conversation, as only the Bot's ServiceUrl and credentials are
+ * required.
*/
- public CompletableFuture getConversations(String serviceUrl,
- MicrosoftAppCredentials credentials) {
+ public CompletableFuture getConversations(
+ String serviceUrl,
+ MicrosoftAppCredentials credentials
+ ) {
return getConversations(serviceUrl, credentials, null);
}
/**
- * Lists the Conversations in which this bot has participated for a given channel server. The
- * channel server returns results in pages and each page will include a `continuationToken`
- * that can be used to fetch the next page of results from the server.
+ * Lists the Conversations in which this bot has participated for a given
+ * channel server. The channel server returns results in pages and each page
+ * will include a `continuationToken` that can be used to fetch the next page of
+ * results from the server.
*
- * This overload may be called from outside the context of a conversation, as only the
- * Bot's ServiceUrl and credentials are required.
+ * This overload may be called from outside the context of a conversation, as
+ * only the Bot's ServiceUrl and credentials are required.
*
- * @param serviceUrl The URL of the channel server to query. This can be retrieved
- * from `context.activity.serviceUrl`.
- * @param credentials The credentials needed for the Bot to connect to the.services().
- * @param continuationToken The continuation token from the previous page of results.
+ * @param serviceUrl The URL of the channel server to query. This can be
+ * retrieved from `context.activity.serviceUrl`.
+ * @param credentials The credentials needed for the Bot to connect to
+ * the.services().
+ * @param continuationToken The continuation token from the previous page of
+ * results.
* @return List of Members of the current conversation
*/
- public CompletableFuture getConversations(String serviceUrl,
- MicrosoftAppCredentials credentials,
- String continuationToken) {
+ public CompletableFuture getConversations(
+ String serviceUrl,
+ MicrosoftAppCredentials credentials,
+ String continuationToken
+ ) {
if (StringUtils.isEmpty(serviceUrl)) {
throw new IllegalArgumentException("serviceUrl");
}
@@ -636,17 +725,21 @@ public CompletableFuture getConversations(String serviceUrl
}
return getOrCreateConnectorClient(serviceUrl, credentials)
- .thenCompose(connectorClient -> connectorClient.getConversations().getConversations(continuationToken));
+ .thenCompose(
+ connectorClient -> connectorClient.getConversations()
+ .getConversations(continuationToken)
+ );
}
/**
- * Lists the Conversations in which this bot has participated for a given channel server. The
- * channel server returns results in pages and each page will include a `continuationToken`
- * that can be used to fetch the next page of results from the server.
+ * Lists the Conversations in which this bot has participated for a given
+ * channel server. The channel server returns results in pages and each page
+ * will include a `continuationToken` that can be used to fetch the next page of
+ * results from the server.
*
- * This overload may be called during standard Activity processing, at which point the Bot's
- * service URL and credentials that are part of the current activity processing pipeline
- * will be used.
+ * This overload may be called during standard Activity processing, at which
+ * point the Bot's service URL and credentials that are part of the current
+ * activity processing pipeline will be used.
*
* @param context The context object for the turn.
* @return List of Members of the current conversation
@@ -657,19 +750,24 @@ public CompletableFuture getConversations(TurnContextImpl c
}
/**
- * Lists the Conversations in which this bot has participated for a given channel server. The
- * channel server returns results in pages and each page will include a `continuationToken`
- * that can be used to fetch the next page of results from the server.
+ * Lists the Conversations in which this bot has participated for a given
+ * channel server. The channel server returns results in pages and each page
+ * will include a `continuationToken` that can be used to fetch the next page of
+ * results from the server.
*
- * This overload may be called during standard Activity processing, at which point the Bot's
- * service URL and credentials that are part of the current activity processing pipeline
- * will be used.
+ * This overload may be called during standard Activity processing, at which
+ * point the Bot's service URL and credentials that are part of the current
+ * activity processing pipeline will be used.
*
- * @param context The context object for the turn.
- * @param continuationToken The continuation token from the previous page of results.
+ * @param context The context object for the turn.
+ * @param continuationToken The continuation token from the previous page of
+ * results.
* @return List of Members of the current conversation
*/
- public CompletableFuture getConversations(TurnContextImpl context, String continuationToken) {
+ public CompletableFuture getConversations(
+ TurnContextImpl context,
+ String continuationToken
+ ) {
ConnectorClient connectorClient = context.getTurnState().get(CONNECTOR_CLIENT_KEY);
return connectorClient.getConversations().getConversations(continuationToken);
}
@@ -677,90 +775,111 @@ public CompletableFuture getConversations(TurnContextImpl c
/**
* Attempts to retrieve the token for a user that's in a login flow.
*
- * @param context Context for the current turn of conversation with the user.
+ * @param context Context for the current turn of conversation with the
+ * user.
* @param connectionName Name of the auth connection to use.
* @param magicCode (Optional) Optional user entered code to validate.
* @return Token Response
*/
@Override
- public CompletableFuture getUserToken(TurnContext context, String connectionName, String magicCode) {
+ public CompletableFuture getUserToken(
+ TurnContext context,
+ String connectionName,
+ String magicCode
+ ) {
BotAssert.contextNotNull(context);
- if (context.getActivity().getFrom() == null || StringUtils.isEmpty(context.getActivity().getFrom().getId())) {
- throw new IllegalArgumentException("BotFrameworkAdapter.GetuserToken(): missing from or from.id");
+ if (
+ context.getActivity().getFrom() == null
+ || StringUtils.isEmpty(context.getActivity().getFrom().getId())
+ ) {
+ throw new IllegalArgumentException(
+ "BotFrameworkAdapter.GetuserToken(): missing from or from.id"
+ );
}
if (StringUtils.isEmpty(connectionName)) {
throw new IllegalArgumentException("connectionName");
}
- return createOAuthClient(context)
- .thenCompose(oAuthClient -> {
- return oAuthClient.getUserToken().getToken(
- context.getActivity().getFrom().getId(),
- connectionName,
- context.getActivity().getChannelId(),
- magicCode);
+ return createOAuthClient(context).thenCompose(oAuthClient -> {
+ return oAuthClient.getUserToken()
+ .getToken(
+ context.getActivity().getFrom().getId(), connectionName,
+ context.getActivity().getChannelId(), magicCode
+ );
});
}
/**
- * Get the raw signin link to be sent to the user for signin for a connection name.
+ * Get the raw signin link to be sent to the user for signin for a connection
+ * name.
*
- * @param context Context for the current turn of conversation with the user.
+ * @param context Context for the current turn of conversation with the
+ * user.
* @param connectionName Name of the auth connection to use.
* @return A task that represents the work queued to execute.
*/
@Override
- public CompletableFuture getOauthSignInLink(TurnContext context, String connectionName) {
+ public CompletableFuture getOauthSignInLink(
+ TurnContext context,
+ String connectionName
+ ) {
BotAssert.contextNotNull(context);
if (StringUtils.isEmpty(connectionName)) {
throw new IllegalArgumentException("connectionName");
}
- return createOAuthClient(context)
- .thenCompose(oAuthClient -> {
- try {
- Activity activity = context.getActivity();
+ return createOAuthClient(context).thenCompose(oAuthClient -> {
+ try {
+ Activity activity = context.getActivity();
- TokenExchangeState tokenExchangeState = new TokenExchangeState() {{
+ TokenExchangeState tokenExchangeState = new TokenExchangeState() {
+ {
setConnectionName(connectionName);
- setConversation(new ConversationReference() {{
- setActivityId(activity.getId());
- setBot(activity.getRecipient());
- setChannelId(activity.getChannelId());
- setConversation(activity.getConversation());
- setServiceUrl(activity.getServiceUrl());
- setUser(activity.getFrom());
- }});
- }};
-
- ObjectMapper mapper = new ObjectMapper();
- String serializedState = mapper.writeValueAsString(tokenExchangeState);
- byte[] encodedState = serializedState.getBytes(StandardCharsets.UTF_8);
- String state = BaseEncoding.base64().encode(encodedState);
-
- return oAuthClient.getBotSignIn().getSignInUrl(state);
- } catch (Throwable t) {
- throw new CompletionException(t);
- }
- });
+ setConversation(new ConversationReference() {
+ {
+ setActivityId(activity.getId());
+ setBot(activity.getRecipient());
+ setChannelId(activity.getChannelId());
+ setConversation(activity.getConversation());
+ setServiceUrl(activity.getServiceUrl());
+ setUser(activity.getFrom());
+ }
+ });
+ }
+ };
+
+ ObjectMapper mapper = new ObjectMapper();
+ String serializedState = mapper.writeValueAsString(tokenExchangeState);
+ byte[] encodedState = serializedState.getBytes(StandardCharsets.UTF_8);
+ String state = BaseEncoding.base64().encode(encodedState);
+
+ return oAuthClient.getBotSignIn().getSignInUrl(state);
+ } catch (Throwable t) {
+ throw new CompletionException(t);
+ }
+ });
}
/**
- * Get the raw signin link to be sent to the user for signin for a connection name.
+ * Get the raw signin link to be sent to the user for signin for a connection
+ * name.
*
- * @param context Context for the current turn of conversation with the user.
+ * @param context Context for the current turn of conversation with the
+ * user.
* @param connectionName Name of the auth connection to use.
- * @param userId The user id that will be associated with the token.
- * @param finalRedirect The final URL that the OAuth flow will redirect to.
+ * @param userId The user id that will be associated with the token.
+ * @param finalRedirect The final URL that the OAuth flow will redirect to.
* @return A task that represents the work queued to execute.
*/
@Override
- public CompletableFuture getOauthSignInLink(TurnContext context,
- String connectionName,
- String userId,
- String finalRedirect) {
+ public CompletableFuture getOauthSignInLink(
+ TurnContext context,
+ String connectionName,
+ String userId,
+ String finalRedirect
+ ) {
BotAssert.contextNotNull(context);
if (StringUtils.isEmpty(connectionName)) {
@@ -770,100 +889,122 @@ public CompletableFuture getOauthSignInLink(TurnContext context,
throw new IllegalArgumentException("userId");
}
- return createOAuthClient(context)
- .thenCompose(oAuthClient -> {
- try {
- TokenExchangeState tokenExchangeState = new TokenExchangeState() {{
+ return createOAuthClient(context).thenCompose(oAuthClient -> {
+ try {
+ TokenExchangeState tokenExchangeState = new TokenExchangeState() {
+ {
setConnectionName(connectionName);
- setConversation(new ConversationReference() {{
- setActivityId(null);
- setBot(new ChannelAccount() {{
- setRole(RoleTypes.BOT);
- }});
- setChannelId(Channels.DIRECTLINE);
- setConversation(new ConversationAccount());
- setServiceUrl(null);
- setUser(new ChannelAccount() {{
- setRole(RoleTypes.USER);
- setId(userId);
- }});
- }});
- }};
-
- ObjectMapper mapper = new ObjectMapper();
- String serializedState = mapper.writeValueAsString(tokenExchangeState);
- byte[] encodedState = serializedState.getBytes(StandardCharsets.UTF_8);
- String state = BaseEncoding.base64().encode(encodedState);
-
- return oAuthClient.getBotSignIn().getSignInUrl(state);
- } catch (Throwable t) {
- throw new CompletionException(t);
- }
- });
+ setConversation(new ConversationReference() {
+ {
+ setActivityId(null);
+ setBot(new ChannelAccount() {
+ {
+ setRole(RoleTypes.BOT);
+ }
+ });
+ setChannelId(Channels.DIRECTLINE);
+ setConversation(new ConversationAccount());
+ setServiceUrl(null);
+ setUser(new ChannelAccount() {
+ {
+ setRole(RoleTypes.USER);
+ setId(userId);
+ }
+ });
+ }
+ });
+ }
+ };
+
+ ObjectMapper mapper = new ObjectMapper();
+ String serializedState = mapper.writeValueAsString(tokenExchangeState);
+ byte[] encodedState = serializedState.getBytes(StandardCharsets.UTF_8);
+ String state = BaseEncoding.base64().encode(encodedState);
+
+ return oAuthClient.getBotSignIn().getSignInUrl(state);
+ } catch (Throwable t) {
+ throw new CompletionException(t);
+ }
+ });
}
/**
* Signs the user out with the token server.
*
- * @param context Context for the current turn of conversation with the user.
+ * @param context Context for the current turn of conversation with the
+ * user.
* @param connectionName Name of the auth connection to use.
* @return A task that represents the work queued to execute.
*/
@Override
- public CompletableFuture signOutUser(TurnContext context, String connectionName, String userId) {
+ public CompletableFuture signOutUser(
+ TurnContext context,
+ String connectionName,
+ String userId
+ ) {
BotAssert.contextNotNull(context);
if (StringUtils.isEmpty(connectionName)) {
throw new IllegalArgumentException("connectionName");
}
- return createOAuthClient(context)
- .thenCompose(oAuthClient -> {
- return oAuthClient.getUserToken().signOut(
- context.getActivity().getFrom().getId(), connectionName, context.getActivity().getChannelId());
- })
- .thenApply(signOutResult -> null);
+ return createOAuthClient(context).thenCompose(oAuthClient -> {
+ return oAuthClient.getUserToken()
+ .signOut(
+ context.getActivity().getFrom().getId(), connectionName,
+ context.getActivity().getChannelId()
+ );
+ }).thenApply(signOutResult -> null);
}
/**
* Retrieves the token status for each configured connection for the given user.
*
- * @param context Context for the current turn of conversation with the user.
- * @param userId The user Id for which token status is retrieved.
- * @param includeFilter Optional comma separated list of connection's to include.
- * Blank will return token status for all configured connections.
+ * @param context Context for the current turn of conversation with the
+ * user.
+ * @param userId The user Id for which token status is retrieved.
+ * @param includeFilter Optional comma separated list of connection's to
+ * include. Blank will return token status for all
+ * configured connections.
* @return Array of {@link TokenStatus}.
*/
@Override
- public CompletableFuture> getTokenStatus(TurnContext context,
- String userId,
- String includeFilter) {
+ public CompletableFuture> getTokenStatus(
+ TurnContext context,
+ String userId,
+ String includeFilter
+ ) {
BotAssert.contextNotNull(context);
if (StringUtils.isEmpty(userId)) {
throw new IllegalArgumentException("userId");
}
- return createOAuthClient(context)
- .thenCompose(oAuthClient -> {
- return oAuthClient.getUserToken().getTokenStatus(
- userId, context.getActivity().getChannelId(), includeFilter);
- });
+ return createOAuthClient(context).thenCompose(oAuthClient -> {
+ return oAuthClient.getUserToken()
+ .getTokenStatus(userId, context.getActivity().getChannelId(), includeFilter);
+ });
}
/**
- * Retrieves Azure Active Directory tokens for particular resources on a configured connection.
+ * Retrieves Azure Active Directory tokens for particular resources on a
+ * configured connection.
*
- * @param context Context for the current turn of conversation with the user.
- * @param connectionName The name of the Azure Active Directory connection configured with this bot.
- * @param resourceUrls The list of resource URLs to retrieve tokens for.
- * @param userId The user Id for which tokens are retrieved. If passing in null the userId is taken
- * from the Activity in the TurnContext.
+ * @param context Context for the current turn of conversation with the
+ * user.
+ * @param connectionName The name of the Azure Active Directory connection
+ * configured with this bot.
+ * @param resourceUrls The list of resource URLs to retrieve tokens for.
+ * @param userId The user Id for which tokens are retrieved. If passing
+ * in null the userId is taken from the Activity in the
+ * TurnContext.
* @return Map of resourceUrl to the corresponding {@link TokenResponse}.
*/
@Override
- public CompletableFuture