Skip to content

Commit

Permalink
Add javadoc to the LocaleNegotiation example
Browse files Browse the repository at this point in the history
  • Loading branch information
testinfected committed Oct 25, 2015
1 parent 882fb75 commit 3014bd0
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/test/java/examples/locale/LocaleNegotiationExample.java
Expand Up @@ -7,10 +7,25 @@
import java.util.Arrays;
import java.util.Locale;

/**
* <p>
* This example demonstrates locale detection from the HTTP <code>Accept-Language</code> header.
* </p>
* <p>
* We use the {@link Locales} middleware to detect the user agent locale and figure out the best
* possible locale knowing the application supported locales.
* </p>
*
*/
public class LocaleNegotiationExample {

private final String[] supportedLanguages;

/**
* Constructs this example with the list of locales we support
*
* @param supportedLanguages the list of languages the application supports
*/
public LocaleNegotiationExample(String... supportedLanguages) {
this.supportedLanguages = supportedLanguages;
}
Expand All @@ -19,22 +34,29 @@ public void run(WebServer server) throws IOException {
// Knowing what languages we support, figure out the best locale to use for each incoming request
server.add(new Locales(supportedLanguages))
.start((request, response) -> {
// The best possible locale is available as a request attribute
Locale locale = request.attribute(Locale.class);
// Set the response to plain text
response.contentType("text/plain");
response.done(
// What the client asked for
"You asked for: " + request.header("accept-language") + "\n" +
// All the locales we support
"We support: " + Arrays.asList(supportedLanguages) + "\n" +
// The application default locale
"Our default is: " + Locale.getDefault().toLanguageTag() + "\n" +
// The best locale for this request, depending on supported locales and requested locale
"The best match is: " + locale.toLanguageTag() + "\n"
);
});
}

public static void main(String[] args) throws IOException {
// We run the example with support for English, US English and French
LocaleNegotiationExample example = new LocaleNegotiationExample("en", "en_US", "fr");
// Run the default web server
WebServer webServer = WebServer.create();
example.run(webServer);
System.out.println("Access at " + webServer.uri());
}
}
}

0 comments on commit 3014bd0

Please sign in to comment.