Skip to content

Add java samples #458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 170 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Azure SQL bindings for Azure Functions are supported for:
- .NET functions (C# in-process)
- NodeJS functions (JavaScript/TypeScript)
- Python functions
- Java functions

## Table of Contents

Expand All @@ -32,6 +33,7 @@ Azure SQL bindings for Azure Functions are supported for:
- [.NET functions](#net-functions)
- [JavaScript functions](#javascript-functions)
- [Python functions](#python-functions)
- [Java functions](#java-functions)
- [More Samples](#more-samples)
- [Input Binding](#input-binding)
- [Query String](#query-string)
Expand Down Expand Up @@ -100,7 +102,7 @@ These steps can be done in the Terminal/CLI or with PowerShell.

1. Install [Azure Functions Core Tools](https://docs.microsoft.com/azure/azure-functions/functions-run-local)

2. Create a function app for .NET, JavaScript, TypeScript or Python.
2. Create a function app for .NET, JavaScript, TypeScript, Python, or Java.

**.NET**
```bash
Expand Down Expand Up @@ -132,6 +134,13 @@ These steps can be done in the Terminal/CLI or with PowerShell.
func init --worker-runtime python
```

**Java**
```bash
mkdir MyApp
cd MyApp
func init --worker-runtime java
```

3. Enable SQL bindings on the function app. More information can be found [in Microsoft Docs](https://docs.microsoft.com/azure/azure-functions/functions-bindings-azure-sql).

**.NET:** Install the extension.
Expand Down Expand Up @@ -167,6 +176,24 @@ These steps can be done in the Terminal/CLI or with PowerShell.
"PYTHON_ISOLATE_WORKER_DEPENDENCIES": "1"
```

**Java:**
Update the `host.json` file to the preview extension bundle.
```json
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle.Preview",
"version": "[4.*, 5.0.0)"
}
```

Add the `azure-functions-java-library-sql` dependency to the pom.xml file.
```xml
<dependency>
<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library-sql</artifactId>
<version>0.1.0</version>
</dependency>
```

### Configure Function App

Once you have your Function App you need to configure it for use with Azure SQL bindings for Azure Functions.
Expand Down Expand Up @@ -502,6 +529,148 @@ Note: This tutorial requires that a SQL database is setup as shown in [Create a
- Hit 'F5' to run your code. Click the link to upsert the output array values in your SQL table. Your upserted values should launch in the browser.
- Congratulations! You have successfully created your first SQL output binding! Checkout [Output Binding](#Output-Binding) for more information on how to use it and explore on your own!

### Java functions

#### Input Binding Tutorial

Note: This tutorial requires that a SQL database is setup as shown in [Create a SQL Server](#Create-a-SQL-Server).

- Open your app that you created in [Create a Function App](#create-a-function-app) in VSCode
- Press 'F1' and search for 'Azure Functions: Create Function'
- Choose HttpTrigger -> (Provide a package name) -> (Provide a function name) -> anonymous
- In the file that opens, replace the `public HttpResponseMessage run` block with the below code.

```java
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS,
route = "getemployees")
HttpRequestMessage<Optional<String>> request,
@SQLInput(
commandText = "SELECT * FROM Employees",
commandType = "Text",
connectionStringSetting = "SqlConnectionString")
Employee[] employees) {

return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(employees).build();
}
```

*In the above, "select * from Employees" is the SQL script run by the input binding. The CommandType on the line below specifies whether the first line is a query or a stored procedure. On the next line, the ConnectionStringSetting specifies that the app setting that contains the SQL connection string used to connect to the database is "SqlConnectionString." For more information on this, see the [Input Binding](#Input-Binding) section*

- Add 'import com.microsoft.azure.functions.sql.annotation.SQLInput;'
- Create a new file and call it 'Employee.java'
- Paste the below in the file. These are the column names of our SQL table.

```java
package com.function.Common;

public class Employee {
private int EmployeeId;
private String LastName;
private String FirstName;
private String Company;
private String Team;

public Employee() {
}

public Employee(int employeeId, String lastName, String firstName, String company, String team) {
EmployeeId = employeeId;
LastName = lastName;
FirstName = firstName;
Company = company;
Team = team;
}

public int getEmployeeId() {
return EmployeeId;
}

public void setEmployeeId(int employeeId) {
this.EmployeeId = employeeId;
}

public String getLastName() {
return LastName;
}

public void setLastName(String lastName) {
this.LastName = lastName;
}

public String getFirstName() {
return FirstName;
}

public void setFirstName(String firstName) {
this.FirstName = firstName;
}

public String getCompany() {
return Company;
}

public void setCompany(String company) {
this.Company = company;
}

public String getTeam() {
return Team;
}

public void setTeam(String team) {
this.Team = team;
}
}
```

- Navigate back to your HttpTriggerJava file.
- Open the local.settings.json file, and in the brackets for "Values," verify there is a 'SqlConnectionString.' If not, add it.
- Hit 'F5' to run your code. This will start up the Functions Host with a local HTTP Trigger and SQL Input Binding.
- Click the link that appears in your terminal.
- You should see your database output in the browser window.
- Congratulations! You have successfully created your first SQL input binding! Checkout [Input Binding](#Input-Binding) for more information on how to use it and explore on your own!

#### Output Binding Tutorial

Note: This tutorial requires that a SQL database is setup as shown in [Create a SQL Server](#Create-a-SQL-Server), and that you have the 'Employee.java' class from the [Input Binding Tutorial](#Input-Binding-Tutorial).

- Open your app in VSCode
- Press 'F1' and search for 'Azure Functions: Create Function'
- Choose HttpTrigger -> (Provide a package name) -> (Provide a function name) -> anonymous
- In the file that opens, replace the `public HttpResponseMessage run` block with the below code.

```java
public HttpResponseMessage run(
@HttpTrigger(
name = "req",
methods = {HttpMethod.GET},
authLevel = AuthorizationLevel.ANONYMOUS,
route = "addemployees-array")
HttpRequestMessage<Optional<String>> request,
@SQLOutput(
commandText = "dbo.Employees",
connectionStringSetting = "SqlConnectionString")
OutputBinding<Employee[]> output) {

output = new Employee[]
{
new Employee(1, "Hello", "World", "Microsoft", "Functions"),
new Employee(2, "Hi", "SQLupdate", "Microsoft", "Functions")
};

return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(output).build();
}
```

*In the above, "dbo.Employees" is the name of the table our output binding is upserting into. The line below is similar to the input binding and specifies where our SqlConnectionString is. For more information on this, see the [Output Binding](#Output-Binding) section*

- Hit 'F5' to run your code. Click the link to upsert the output array values in your SQL table. Your upserted values should launch in the browser.
- Congratulations! You have successfully created your first SQL output binding! Checkout [Output Binding](#Output-Binding) for more information on how to use it and explore on your own!

## More Samples

### Input Binding
Expand Down
2 changes: 1 addition & 1 deletion java-library/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

<groupId>com.microsoft.azure.functions</groupId>
<artifactId>azure-functions-java-library-sql</artifactId>
<version>0.1.0</version>
<version>0.1.0</version> <!-- Update the dependency version in samples-java/pom.xml too if this version is updated. -->
<packaging>jar</packaging>

<parent>
Expand Down
39 changes: 39 additions & 0 deletions samples/samples-java/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Build output
target/
repo/
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

# IDE
.idea/
*.iml
.settings/
.project
.classpath

# macOS
.DS_Store

# Azure Functions
local.settings.json
bin/
obj/
6 changes: 6 additions & 0 deletions samples/samples-java/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"ms-azuretools.vscode-azurefunctions",
"vscjava.vscode-java-debug"
]
}
13 changes: 13 additions & 0 deletions samples/samples-java/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Java Functions",
"type": "java",
"request": "attach",
"hostName": "127.0.0.1",
"port": 5005,
"preLaunchTask": "func: host start"
}
]
}
9 changes: 9 additions & 0 deletions samples/samples-java/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"azureFunctions.javaBuildTool": "maven",
"azureFunctions.deploySubpath": "target/azure-functions/samples-java-1665766173929",
"azureFunctions.projectLanguage": "Java",
"azureFunctions.projectRuntime": "~4",
"debug.internalConsoleOptions": "neverOpen",
"azureFunctions.preDeployTask": "package (functions)",
"java.configuration.updateBuildConfiguration": "automatic"
}
24 changes: 24 additions & 0 deletions samples/samples-java/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "func",
"command": "host start",
"problemMatcher": "$func-java-watch",
"isBackground": true,
"options": {
"cwd": "${workspaceFolder}/target/azure-functions/samples-java-1665766173929"
},
"dependsOn": "package (functions)"
},
{
"label": "package (functions)",
"command": "mvn clean package",
"type": "shell",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
7 changes: 7 additions & 0 deletions samples/samples-java/host.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"version": "2.0",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle.Preview",
"version": "[4.*, 5.0.0)"
}
}
Loading