Create Azure Functions in Java

Microsoft documentation ["Create your first function using Java and Maven (preview)"](https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-first- I tried java-maven) in the following environment.

Since it worked safely, the following memo.

Install Azure Functions Core Tools

I installed Azure Functions Core Tools by referring to Documentation. According to the procedure, I first installed .NET Core.

Download the .NET Core SDK at the .NET Core Download Page (https://www.microsoft.com/net/download) 2018-09-16_12h36_38.png

Proceed with the installation. 2018-09-16_12h39_37.png

Installation is complete. 2018-09-16_12h45_16.png

Install Azure Functions Core Tools with npm. My environment used npm 5.6.0 which was already installed.

npm install -g azure-functions-core-tools@core

Create a template with azure-functions-archetype

Create a template using Maven's "azure-functions-archetypes".

In VS Code, select ** "View" **-> ** "Command Palette" ** and then ** "Maven: Generate from Maven Archetype" ** to select the destination folder. 2018-09-17_21h09_55.png

** Select "azure-functions-archetype" **. 2018-09-17_21h11_09.png

Then, the following processing will start automatically.

PS D:\web\azure\AzureFunctionsJava> cmd /c mvn archetype:generate -DarchetypeArtifactId="azure-functions-archetype" -DarchetypeGroupId="com.microsoft.azure"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
[INFO] Archetype [com.microsoft.azure:azure-functions-archetype:1.15] found in catalog remote
Downloading from central: https://repo.maven.apache.org/maven2/com/microsoft/azure/azure-functions-archetype/1.15/azure-functions-archetype-1.15.pom
Downloaded from central: https://repo.maven.apache.org/maven2/com/microsoft/azure/azure-functions-archetype/1.15/azure-functions-archetype-1.15.pom (1.5 kB at 4.3 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/com/microsoft/azure/azure-functions-archetype/1.15/azure-functions-archetype-1.15.jar
Downloaded from central: https://repo.maven.apache.org/maven2/com/microsoft/azure/azure-functions-archetype/1.15/azure-functions-archetype-1.15.jar (15 kB at 44 kB/s)

Set to interactive. Here, only groupId and artifactId are specified, and the rest is left blank by default.

Define value for property 'groupId' (should match expression '[A-Za-z0-9_\-\.]+'): tech.kikutaro
[INFO] Using property: groupId = tech.kikutaro
Define value for property 'artifactId' (should match expression '[A-Za-z0-9_\-\.]+'): AzureFunctionsJava
[INFO] Using property: artifactId = AzureFunctionsJava
Define value for property 'version' 1.0-SNAPSHOT: :
Define value for property 'package' tech.kikutaro: :
Define value for property 'appName' azurefunctionsjava-20180917211315850: :
Define value for property 'appRegion' westus: :
Define value for property 'resourceGroup' java-functions-group: :
Confirm properties configuration:
groupId: tech.kikutaro
groupId: tech.kikutaro
artifactId: AzureFunctionsJava
artifactId: AzureFunctionsJava
version: 1.0-SNAPSHOT
package: tech.kikutaro
appName: azurefunctionsjava-20180917211315850
appRegion: westus
resourceGroup: java-functions-group
 Y: : Y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Archetype: azure-functions-archetype:1.15
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: tech.kikutaro
[INFO] Parameter: artifactId, Value: AzureFunctionsJava
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: package, Value: tech.kikutaro
[INFO] Parameter: packageInPathFormat, Value: tech/kikutaro
[INFO] Parameter: appName, Value: azurefunctionsjava-20180917211315850
[INFO] Parameter: resourceGroup, Value: java-functions-group
[INFO] Parameter: package, Value: tech.kikutaro
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] Parameter: groupId, Value: tech.kikutaro
[INFO] Parameter: appRegion, Value: westus
[INFO] Parameter: artifactId, Value: AzureFunctionsJava
[INFO] Project created from Archetype in dir: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:20 min
[INFO] Finished at: 2018-09-17T21:13:37+09:00
[INFO] ------------------------------------------------------------------------

This completes the template. Although it is called a template, the following code is written, so you can move it as it is.

package tech.kikutaro;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

/**
 * Azure Functions with HTTP Trigger.
 */
public class Function {
    /**
     * This function listens at endpoint "/api/HttpTrigger-Java". Two ways to invoke it using "curl" command in bash:
     * 1. curl -d "HTTP Body" {your host}/api/HttpTrigger-Java
     * 2. curl {your host}/api/HttpTrigger-Java?name=HTTP%20Query
     */
    @FunctionName("HttpTrigger-Java")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
            final ExecutionContext context) {
        context.getLogger().info("Java HTTP trigger processed a request.");

        // Parse query parameter
        String query = request.getQueryParameters().get("name");
        String name = request.getBody().orElse(query);

        if (name == null) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
        } else {
            return request.createResponseBuilder(HttpStatus.OK).body("Hello, " + name).build();
        }
    }
}

Local operation check

Build.

mvn clean package

Below, some download parts are omitted.

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< tech.kikutaro:AzureFunctionsJava >------------------
[INFO] Building Azure Java Functions 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ AzureFunctionsJava ---
[INFO] Deleting D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ AzureFunctionsJava ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ AzureFunctionsJava ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ AzureFunctionsJava ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ AzureFunctionsJava ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\test-classes
[WARNING] /D:/web/azure/AzureFunctionsJava/AzureFunctionsJava/src/test/java/tech/kikutaro/FunctionTest.java: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\src\test\java\tech\kikutaro\FunctionTest.Java operations are unchecked or unsafe.
[WARNING] /D:/web/azure/AzureFunctionsJava/AzureFunctionsJava/src/test/java/tech/kikutaro/FunctionTest.java:Detail is,-Xlint:Recon with the unchecked option
Please pile.
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ AzureFunctionsJava ---
[INFO] Surefire report directory: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running tech.kikutaro.FunctionTest
9 17, 2018 9:25:20 pm tech.kikutaro.Function run
information: Java HTTP trigger processed a request.
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.302 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]
[INFO] --- maven-dependency-plugin:3.1.1:copy-dependencies (copy-dependencies) @ AzureFunctionsJava ---
[INFO]
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ AzureFunctionsJava ---
[INFO] Building jar: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\AzureFunctionsJava-1.0-SNAPSHOT.jar
[INFO]
[INFO] --- azure-functions-maven-plugin:1.0.0-beta-6:package (package-functions) @ AzureFunctionsJava ---
Downloading from central: https://repo.maven.apache.org/maven2/com/microsoft/azure/azure-maven-plugin-lib/1.2.0/azure-maven-plugin-lib-1.2.0.pom
AI: INFO 17-09-2018 21:27, 1: Configuration file has been successfully found as resource
AI: INFO 17-09-2018 21:27, 1: Configuration file has been successfully found as resource
[INFO]
[INFO] Step 1 of 7: Searching for Azure Functions entry points
[INFO] 1 Azure Functions entry point(s) found.
[INFO]
[INFO] Step 2 of 7: Generating Azure Functions configurations
[INFO] Generation done.
[INFO]
[INFO] Step 3 of 7: Validating generated configurations
[INFO] Validation done.
[INFO]
[INFO] Step 4 of 7: Saving empty host.json
[INFO] Successfully saved to D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850\host.json
[INFO]
[INFO] Step 5 of 7: Saving configurations to function.json
[INFO] Starting processing function: HttpTrigger-Java
[INFO] Successfully saved to D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850\HttpTrigger-Java\function.json
[INFO]
[INFO] Step 6 of 7: Copying JARs to staging directoryD:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource to D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850
[INFO] Copied successfully.
[INFO]
[INFO] Step 7 of 7: Installing function extensions if needed
  Writing C:\Users\kikuta\AppData\Local\Temp\tmpC1CE.tmp
info :package'Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator'PackageReference project'D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.csproj'I am adding to.
log  : D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.Restoring the csproj package...
info :package'Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator'Is a project'D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.csproj'Compatible with all specified frameworks of.
info :package'Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator'version'1.0.0'PackageReference is a file'D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.csproj'Updated with.


.Microsoft for .NET Core(R)Build Engine version 15.8.166+gd4e8d81a88
Copyright (C) Microsoft Corporation.All rights reserved.

  D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.Restoring the csproj package...
MSBuild File D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\obj\extensions.csproj.nuget.g.Generating props.
MSBuild File D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\obj\extensions.csproj.nuget.g.Generating targets.
  D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\extensions.Restoration of csproj is 971.Completed in 41 ms.
  extensions -> D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850\bin\extensions.dll

The build was successful.
0 warnings
0 error

Elapsed time 00:00:17.67


[INFO] Function extension installation done.
[INFO] Successfully built Azure Functions.
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:copy-resources (copy-resources) @ AzureFunctionsJava ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:07 min
[INFO] Finished at: 2018-09-17T21:28:15+09:00
[INFO] ------------------------------------------------------------------------

I will do it.

mvn azure-functions:run
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< tech.kikutaro:AzureFunctionsJava >------------------
[INFO] Building Azure Java Functions 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- azure-functions-maven-plugin:1.0.0-beta-6:run (default-cli) @ AzureFunctionsJava ---
AI: INFO 17-09-2018 22:00, 1: Configuration file has been successfully found as resource
AI: INFO 17-09-2018 22:00, 1: Configuration file has been successfully found as resource
[INFO] Azure Function App's staging directory found at: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850
[INFO] Azure Functions Core Tools found.

                  %%%%%%
                 %%%%%%
            @   %%%%%%    @
          @@   %%%%%%      @@
       @@@    %%%%%%%%%%%    @@@
     @@      %%%%%%%%%%        @@
       @@         %%%%       @@
         @@      %%%       @@
           @@    %%      @@
                %%
                %

Azure Functions Core Tools (2.0.1-beta.38)
Function Runtime Version: 2.0.12050.0
Skipping 'AzureWebJobsStorage' from local settings as it's already defined in current environment variables.
Skipping 'AzureWebJobsDashboard' from local settings as it's already defined in current environment variables.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\kikuta\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Host.Startup[0]
      Reading host configuration file 'D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850\host.json'info: Host.Startup[0]
      Host configuration file read:
      {
        "version": "2.0"
      }
[2018/09/17 13:00:43] Initializing Host.
[2018/09/17 13:00:43] Host initialization: ConsecutiveErrors=0, StartupCount=1
[2018/09/17 13:00:44] Starting JobHost
[2018/09/17 13:00:44] Starting Host (HostId=xxxxxxxxx-xxxxxxxx, InstanceId=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, Version=2.0.12050.0, ProcessId=11372, AppDomainId=1, Debug=False, FunctionsExtensionVersion=)
[2018/09/17 13:00:44] Starting language worker process:C:\Program Files\Java\jdk1.8.0_152\bin\java  -jar "C:\Users\kikuta\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\java\azure-functions-java-worker.jar" --host 127.0.0.1 --port 36887 --workerId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx --requestId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx --grpcMaxMessageLength 134217728
[2018/09/17 13:00:44] C:\Program Files\Java\jdk1.8.0_152\bin\java process with Id=26080 started
[2018/09/17 13:00:44] Generating 1 job function(s)
[2018/09/17 13:00:44] Found the following functions:
[2018/09/17 13:00:44] Host.Functions.HttpTrigger-Java
[2018/09/17 13:00:44]
[2018/09/17 13:00:44] Host initialized (678ms)
[2018/09/17 13:00:44] Host started (695ms)
[2018/09/17 13:00:44] Job host started
Hosting environment: Production
Content root path: D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850
Now listening on: http://0.0.0.0:7071
Application started. Press Ctrl+C to shut down.
Listening on http://0.0.0.0:7071/
Hit CTRL-C to exit...

Http Functions:

        HttpTrigger-Java: http://localhost:7071/api/HttpTrigger-Java

[2018/09/17 13:00:45] Microsoft Azure Functions Java Runtime [build 1.1.0-beta9]
[2018/09/17 13:00:49] [INFO] {MessageHandler.handle}: Message generated by "StartStream.Builder"
[2018/09/17 13:00:49] Host lock lease acquired by instance ID '0000000000000000000000000xxxxxxx'.
[2018/09/17 13:00:57] Worker initialized
[2018/09/17 13:00:57] "HttpTrigger-Java" loaded (ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, Reflection: "D:\web\azure\AzureFunctionsJava\AzureFunctionsJava\target\azure-functions\azurefunctionsjava-20180917211315850\AzureFunctionsJava-1.0-SNAPSHOT.jar"::"tech.kikutaro.Function.run")

When I accessed "http: // localhost: 7071", the following was displayed. 2018-09-16_13h13_14.png

Furthermore, I confirmed the following display at "http: // localhost: 7071 / api / HttpTrigger-Java? Name = kikutaro". 2018-09-16_13h14_27.png

Deploy to Microsoft Azure

Since we were able to confirm the operation locally, we will finally deploy it to Azure. First, log in.

az login

Deploy.

mvn azure-functions:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< tech.kikutaro:AzureFunctionsJava >------------------
[INFO] Building Azure Java Functions 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- azure-functions-maven-plugin:1.0.0-beta-6:deploy (default-cli) @ AzureFunctionsJava ---
AI: INFO 17-09-2018 22:07, 1: Configuration file has been successfully found as resource
AI: INFO 17-09-2018 22:07, 1: Configuration file has been successfully found as resource
[INFO] Authenticate with Azure CLI 2.0
[INFO] The specified function app does not exist. Creating a new function app...
[INFO] Successfully created the function app: azurefunctionsjava-20180917211315850
[INFO] Trying to deploy the function app...
[INFO] Successfully deployed the function app at https://azurefunctionsjava-20180917211315850.azurewebsites.net
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:59 min
[INFO] Finished at: 2018-09-17T22:09:03+09:00
[INFO] ------------------------------------------------------------------------

If you check in the Azure portal, a resource group with the name specified in Maven is created. 2018-09-17_22h09_57.png

You can check the URL by clicking the created Function. 2018-09-17_22h08_29.png

Check as local. First of all, the top URL. 2018-09-17_22h14_58.png

It behaves the same as local. 2018-09-17_22h14_25.png

It was easier than I expected.

Recommended Posts

Create Azure Functions in Java
Create JSON in Java
Create hyperlinks in Java PowerPoint
I dealt with Azure Functions not working in Java
Run Java application in Azure Batch
Create variable length binary data in Java
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Create Java Spring Boot project in IntelliJ
Create a TODO app in Java 7 Create Header
Pi in Java
FizzBuzz in Java
Create Java applications with IBM Cloud Functions
Create barcodes and QR codes in Java PDF
Create a CSR with extended information in Java
Try to create a bulletin board in Java
Let's create a super-simple web framework in Java
I tried to create Alexa skill in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
[Java] Create a filter
Comments in Java source
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
How to call functions in bulk with Java reflection
How to create a Java environment in just 3 seconds
Delete All from Java SDK in Azure Cosmos DB
Change Java heap size in Tomcat in Azure App Service
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
Android-Upload image files to Azure Blob Storage in Java
Remote debugging of Java applications in Azure Web Apps
Operate Azure Blob Storage in Java (SAS token, file operation)