Skip to content

Commit

Permalink
4.x: Helidon SE Media Form Example (#93)
Browse files Browse the repository at this point in the history
Fixes #92

Also add minor updates to the multipart example.
  • Loading branch information
romain-grecourt authored Oct 5, 2024
1 parent 5ac7c8e commit f5a9c3c
Show file tree
Hide file tree
Showing 15 changed files with 528 additions and 40 deletions.
23 changes: 23 additions & 0 deletions examples/media/form/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Helidon SE Media Form Example

This example demonstrates how to use `Parameters` consume or upload form data with both the `WebServer`
and `WebClient` APIs.

This project implements a simple web application that supports uploading
and listing form data. The unit test uses the `WebClient` API to test the endpoints.

## Build

```shell
mvn package
```

## Run

First, start the server:

```shell
java -jar target/helidon-examples-media-form.jar
```

Then open <http://localhost:8080/ui> in your browser.
106 changes: 106 additions & 0 deletions examples/media/form/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2020, 2024 Oracle and/or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.helidon.applications</groupId>
<artifactId>helidon-se</artifactId>
<version>4.2.0-SNAPSHOT</version>
<relativePath/>
</parent>
<groupId>io.helidon.examples.media</groupId>
<artifactId>helidon-examples-media-form</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Helidon Examples Media Support Form</name>

<description>
Example of a form usage.
</description>

<properties>
<mainClass>io.helidon.examples.media.form.Main</mainClass>
</properties>

<dependencies>
<dependency>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.http.media</groupId>
<artifactId>helidon-http-media-jsonp</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.webserver</groupId>
<artifactId>helidon-webserver-static-content</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.logging</groupId>
<artifactId>helidon-logging-jul</artifactId>
</dependency>
<dependency>
<groupId>jakarta.json</groupId>
<artifactId>jakarta.json-api</artifactId>
</dependency>
<dependency>
<groupId>io.helidon.webserver.testing.junit5</groupId>
<artifactId>helidon-webserver-testing-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-libs</id>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright (c) 2020, 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.examples.media.form;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.helidon.common.parameters.Parameters;
import io.helidon.http.Header;
import io.helidon.http.HeaderNames;
import io.helidon.http.HeaderValues;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;

import jakarta.json.Json;
import jakarta.json.JsonBuilderFactory;
import jakarta.json.JsonObjectBuilder;

import static io.helidon.http.Status.MOVED_PERMANENTLY_301;

/**
* Form service.
*/
public final class FormService implements HttpService {
private static final Header UI_LOCATION = HeaderValues.createCached(HeaderNames.LOCATION, "/ui");
private final JsonBuilderFactory jsonFactory = Json.createBuilderFactory(Map.of());
private final Map<String, List<String>> data = new ConcurrentHashMap<>();

@Override
public void routing(HttpRules rules) {
rules.get("/", this::list)
.post("/", this::post);
}

private void list(ServerRequest req, ServerResponse res) {
JsonObjectBuilder jsonBuilder = jsonFactory.createObjectBuilder();
data.forEach((k, list) -> jsonBuilder.add(k, jsonFactory.createArrayBuilder(list)));
res.send(jsonBuilder.build());
}

private void post(ServerRequest req, ServerResponse res) {
Parameters form = req.content().asOptional(Parameters.class).orElseThrow();
form.names().forEach(name -> data.compute(name, (k, v) -> addAll(v, form.all(k))));
res.status(MOVED_PERMANENTLY_301)
.header(UI_LOCATION)
.send();
}

private static List<String> addAll(List<String> list, List<String> values) {
if (list == null) {
list = new ArrayList<>();
}
list.addAll(values);
return list;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2020, 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.helidon.examples.media.form;

import io.helidon.http.Header;
import io.helidon.http.HeaderNames;
import io.helidon.http.HeaderValues;
import io.helidon.http.Status;
import io.helidon.logging.common.LogConfig;
import io.helidon.webserver.WebServer;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.staticcontent.StaticContentService;

/**
* This application provides a simple service with a UI to exercise forms.
*/
public final class Main {
private static final Header UI_LOCATION = HeaderValues.createCached(HeaderNames.LOCATION, "/ui");

private Main() {
}

/**
* Executes the example.
*
* @param args command line arguments, ignored
*/
public static void main(String[] args) {
// load logging configuration
LogConfig.configureRuntime();

WebServer server = WebServer.builder()
.routing(Main::routing)
.port(8080)
.build()
.start();

System.out.println("WEB server is up! http://localhost:" + server.port());
}

/**
* Updates the routing rules.
*
* @param rules routing rules
*/
static void routing(HttpRules rules) {
rules.any("/", (req, res) -> {
res.status(Status.MOVED_PERMANENTLY_301);
res.header(UI_LOCATION);
res.send();
})
.register("/ui", StaticContentService.builder("WEB")
.welcomeFileName("index.html")
.build())
.register("/api", new FormService());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
* Copyright (c) 2020, 2024 Oracle and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* Helidon Examples Media MultiPart.
*/
package io.helidon.examples.media.form;
82 changes: 82 additions & 0 deletions examples/media/form/src/main/resources/WEB/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<!DOCTYPE html>
<!--
Copyright (c) 2020, 2024 Oracle and/or its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html lang="en">
<meta charset="utf-8"/>
<head>
<title>Helidon Examples Media Form</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.js"></script>
<script id="data_tpl" type="x-tmpl-mustache">
<ul>
{{#entries}}
<li>
<span>{{key}}</span>
<ul>
{{#value}}
<li>{{.}}</li>
{{/value}}
</ul>
</li>
{{/entries}}
</ul>
</script>
<style>
label {
display: block;
margin: 20px 0 20px 0;
}
</style>
</head>
<body>
<h1>Data</h1>
<div id="data"></div>

<h1>Form</h1>
<form action="/api" method="post">
<label>
Foo:
<input type="text" name="foo" value="foo1" />
<input type="text" name="foo" value="foo2" />
<input type="text" name="foo" value="foo3" />
</label>
<label>
Bar:
<input type="text" name="bar" value="bar1" />
<input type="text" name="bar" value="bar2" />
<input type="text" name="bar" value="bar3" />
</label>
<input type="submit" />
</form>

<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "/api",
method: "GET"
}).done(function(data) {
const template = $('#data_tpl').html()
Mustache.parse(template);
$("#data").append(Mustache.render(template, {
entries: Object.entries(data).map(e => { return { key: e[0], value: e[1]}})
}))
});
});
</script>
</body>
</html>
Loading

0 comments on commit f5a9c3c

Please sign in to comment.