URI uri = new UriBuilder(whatever).someMethod().someMethod().toURI();
The UriBuilder utility class is used to create, modify, and parse URIs.
The pattern of this builder is:
URI uri = new UriBuilder(whatever).someMethod().someMethod().toURI();
Most aspects are as-expected, but there are two significant features to note:
"secure" flag: In the event that the URI that you want to generate may be HTTP vs HTTPS (or WS vs WSS), but you don’t want external logic to select the correct scheme, simply use any version of the scheme, and then use the secure flag to have it appear correctly in the final URI.
variables: If a path contains a macro name
, then it will be replaced with the corresponding variable value. This is an easy way to inject variables into path segments.
URI / URL
A URI is uniform resource identifier, which is a simple way to identify resources, especially on the internet. The KOS URI has the following components:
Here’s a typical URI:
|
This section defines the following two classes:
UriBuilder
UriParam
The following code defines the UriBuilder class.
UriBuilder
classpublic class UriBuilder {
// Constructors:
public UriBuilder();
public UriBuilder(String url);
public UriBuilder(URI uri);
// Primary items:
public UriBuilder setScheme(String scheme);
public UriBuilder setSecure(boolean secure);
public UriBuilder setHost(String host);
public UriBuilder setPort(int port);
// Setting the path:
public UriBuilder setPath(String path);
public UriBuilder setPaths(String... paths);
public UriBuilder setPaths(List<String> paths);
// Modifying the path:
public UriBuilder addPath(String path);
public UriBuilder addPaths(String... paths);
public UriBuilder addPaths(List<String> paths);
// Variables:
public UriBuilder setVar(String name, Object val);
// Setting parameters:
public UriBuilder setParam(URIParam param);
public UriBuilder setParam(String name, String val);
public UriBuilder setParams(List<URIParam> params);
// Adding parameters:
public UriBuilder addParam(String name, String val);
public UriBuilder addParam(URIParam param);
public UriBuilder addParams(List<URIParam> params);
// Removing parameters:
public UriBuilder removeParam(String name);
public UriBuilder removeAllParams();
// Optional fragment:
public UriBuilder setFragment(String fragment);
// Gives us the payload:
public URI toURI();
}
This section demonstrates some ways to use the UriBuilder class.
Source code for this and most other Java reference pages is available on GitHub. |
In our app note code framework, add the following code.
The first step is to create an interface to our app note framework code. Add the following class (missing methods are defined in succeeding sections).
UriBuilderModule
classpackage com.example.uribuilder;
import com.example.Module;
import com.tccc.kos.commons.core.context.BeanContext;
import com.tccc.kos.commons.util.net.UriBuilder;
import com.tccc.kos.commons.util.net.UriParam;
import java.net.URI;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class UriBuilderModule implements Module {
@Override
public void init(BeanContext ctx) {
log.info("> UriBuilderModule.init()");
}
@Override
public void run() {
log.info("> UriBuilderModule.run()");
createFromScratch(); (1)
createFromString();
createFromUri();
addingPaths();
addingQueryParams();
pathVariableSubstitution();
}
// . . . INSERT METHODS GIVEN IN THE FOLLOWING SECTIONS . . .
}
1 | These six methods are split out into their own sections. Copy and paste these code snippets into the module class. |
MyKosApp
classpublic class MyKosApp extends SystemApplication<BaseAppConfig> {
private Module module;
public void initModule() {
module = new UriBuilderModule(); (1)
}
// . . .
}
1 | Instantiate the UriBuilderModule object |
In this example, an empty builder is created, then every individual component is added:
private void createFromScratch() {
UriBuilder builder = new UriBuilder();
builder.setScheme("http");
builder.setSecure(true); // this changes scheme from "http" to "https"
builder.setHost("www.twitter.com");
builder.setPort(12345);
builder.setPath("/foo/bar/page.html");
builder.setParam("param1", "value1");
builder.setParam("param2", "value2");
builder.setFragment("frag");
URI uri = builder.toURI();
// uri == "https://www.twitter.com:12345/foo/bar/page.html#frag?param1=value1¶m2=value2"
log.info("> createFromScratch: {}", uri);
}
Here, a builder is created from a full URL string:
private void createFromString() {
UriBuilder builder = new UriBuilder("http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2");
URI uri = builder.toURI();
// uri == "http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2"
log.info("> createFromString: {}", uri);
}
This code shows a builder that is created from an existing URI, and the secure
flag is demonstrated:
@SneakyThrows
private void createFromUri() {
URI uri1 = new URI("ws", null, "example.com", 3579, "/path/dir/file.name", "parm=val", "frag");
UriBuilder builder = new UriBuilder(uri1);
builder.setSecure(true); // this changes scheme from "ws" to "wss"
URI uri = builder.toURI();
// uri == "wss://example.com:3579/path/dir/file.name#frag?parm=val"
log.info("> createFromUri: {}", uri);
}
This sample demonstrates how path components are added dynamically:
private void addingPaths() {
UriBuilder builder = new UriBuilder("http://google.com");
builder.addPath("foo");
builder.addPath("bar");
builder.addPaths("baz", "buz");
URI uri = builder.toURI();
// uri == "http://google.com/foo/bar/baz/buz"
log.info("> addingPaths: {}", uri);
}
Here’s some code that shows how query parameters are added dynamically:
private void addingQueryParams() {
UriBuilder builder = new UriBuilder("https://google.com/page.name");
builder.addParam("p1", "v1");
builder.addParam(new UriParam("p2", "v2")); // note the use of UriParam class
URI uri = builder.toURI();
// uri == "https://google.com/page.name?p1=v1&p2=v2"
log.info("> addingQueryParams: {}", uri);
}
Here we see how to substitute values into the path where {var}
markers exist:
private void pathVariableSubstitution() {
UriBuilder builder = new UriBuilder("wss://domain.name");
builder.setPaths("{var1}", "{var2}", "{var3}");
builder.setVar("var1", "dir1");
builder.setVar("var2", "dir2");
builder.setVar("var3", "dir3");
URI uri = builder.toURI();
// uri == "wss://domain.name/dir1/dir2/dir3"
log.info("> pathVariableSubstitution: {}", uri);
}
Once this code is assembled, run it in your debugger. The output logs should look like:
UriBuilderModule
output> ====== BEGIN =========================================
> MyKosApp.load()
> UriBuilderModule.init()
> MyKosApp.start()
> UriBuilderModule.run()
> createFromScratch: https://www.twitter.com:12345/foo/bar/page.html#frag?param1=value1¶m2=value2
> createFromString: http://google.com:80/a/path/to/nowhere.page?p1=v1&p2=v2
> createFromUri: wss://example.com:3579/path/dir/file.name#frag?parm=val
> addingPaths: http://google.com/foo/bar/baz/buz
> addingQueryParams: https://google.com/page.name?p1=v1&p2=v2
> pathVariableSubstitution: wss://domain.name/dir1/dir2/dir3
> ====== END ===========================================