Hreflang Tag Generator — Java source
Turn a list of language versions into a valid hreflang set — locale normalization, duplicate detection and x-default handling — emitted as HTML link tags or an XML sitemap block.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// hreflang-tag-generator — pure locale-list validation + alternate-link
// emission (SEO/meta trio).
//
// Language: Java (17+), standard library only (no external jars — the
// hreflang grammar is pure, so nothing display-only needs to be linked)
// CosmoDev polyglot showcase port of the `hreflang-tag-generator` tool.
// Ported from src/lib/hreflang.ts — display source, part of CosmoDev's
// polyglot tool pages.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** One locale/URL pair. Mirrors the TS HreflangRow interface. */
record HreflangRow(String locale, String url) {}
/** The field set for buildHreflang — rows plus an optional x-default URL.
* The two-arg constructor covers the TS shape; rows-only callers pass null. */
record HreflangInput(List<HreflangRow> rows, String xDefaultUrl) {
HreflangInput {
rows = rows == null ? List.of() : rows;
}
static HreflangInput ofRows(List<HreflangRow> rows) {
return new HreflangInput(rows, null);
}
}
/** Diagnostics plus both emitted flavors. On failure ok is false, errors
* lists every row-located problem, and normalized/html/sitemap are empty —
* exactly like the TS result. */
record HreflangResult(
boolean ok, List<String> errors, List<HreflangRow> normalized,
String html, String sitemap) {}
/** The Java twin of the TS hreflang lib (all members static, like the
* PDFBox-based pdf-split port). */
final class HreflangTagGenerator {
/** ll (ISO-639-1 language) — two ASCII letters. */
private static final Pattern SINGLE_LOCALE = Pattern.compile("^([a-zA-Z]{2})$");
/** ll-CC — two-letter language, two-letter region (ISO-3166). */
private static final Pattern REGION_LOCALE = Pattern.compile("^([a-zA-Z]{2})-([a-zA-Z]{2})$");
/** http:// or https:// scheme prefix. */
private static final Pattern VALID_URL_RE = Pattern.compile("^https?://");
/** Normalize a locale tag to Google's hreflang grammar: ll (ISO-639-1,
* lowercase) or ll-CC (region uppercase, ISO-3166). Case and surrounding
* whitespace are corrected ("en-us" -> "en-US"); anything else is invalid
* and returns null. The Java twin of normalizeLocale() in
* src/lib/hreflang.ts — null stands in for the TS null. */
static String normalizeLocale(String raw) {
String t = raw == null ? "" : raw.trim();
Matcher single = SINGLE_LOCALE.matcher(t);
if (single.matches()) return single.group(1).toLowerCase();
Matcher region = REGION_LOCALE.matcher(t);
if (region.matches()) {
return region.group(1).toLowerCase() + "-" + region.group(2).toUpperCase();
}
return null;
}
/** Trim raw and return it when it starts with http:// or https://,
* otherwise null. Mirrors the TS validUrl() helper. */
private static String validUrl(String raw) {
String t = raw == null ? "" : raw.trim();
return VALID_URL_RE.matcher(t).find() ? t : null;
}
/** Validate a locale/URL table and emit both hreflang flavors. Invalid
* input collects every error (row-located) and emits empty blocks; valid
* input normalizes locales, preserves row order, and appends x-default
* last. */
static HreflangResult buildHreflang(HreflangInput input) {
List<String> errors = new ArrayList<>();
List<HreflangRow> normalized = new ArrayList<>();
Set<String> seen = new HashSet<>();
List<HreflangRow> rows = input.rows();
for (int i = 0; i < rows.size(); i++) {
int n = i + 1;
HreflangRow row = rows.get(i);
String rawLocale = row.locale() == null ? "" : row.locale();
String locale = normalizeLocale(rawLocale);
if (locale == null) {
errors.add("Row " + n + ": \"" + rawLocale.trim()
+ "\" is not a valid locale — use ll or ll-CC (e.g. en, de-AT).");
continue;
}
if (seen.contains(locale)) {
errors.add("Row " + n + ": locale \"" + locale + "\" is already used.");
continue;
}
if (row.url() == null || row.url().trim().isEmpty()) {
errors.add("Row " + n + ": URL is required.");
continue;
}
String url = validUrl(row.url());
if (url == null) {
errors.add("Row " + n + ": URL must start with http:// or https://.");
continue;
}
seen.add(locale);
normalized.add(new HreflangRow(locale, url));
}
String xDefault = null;
if (input.xDefaultUrl() != null && !input.xDefaultUrl().trim().isEmpty()) {
xDefault = validUrl(input.xDefaultUrl());
if (xDefault == null) {
errors.add("x-default: URL must start with http:// or https://.");
}
}
if (!errors.isEmpty()) {
return new HreflangResult(false, errors, List.of(), "", "");
}
List<String> htmlLines = new ArrayList<>();
List<String> sitemapLines = new ArrayList<>();
for (HreflangRow r : normalized) {
htmlLines.add("<link rel=\"alternate\" href=\"" + r.url()
+ "\" hreflang=\"" + r.locale() + "\" />");
sitemapLines.add(" <xhtml:link rel=\"alternate\" hreflang=\"" + r.locale()
+ "\" href=\"" + r.url() + "\"/>");
}
if (xDefault != null) {
htmlLines.add("<link rel=\"alternate\" href=\"" + xDefault
+ "\" hreflang=\"x-default\" />");
sitemapLines.add(" <xhtml:link rel=\"alternate\" hreflang=\"x-default\" href=\""
+ xDefault + "\"/>");
}
return new HreflangResult(
true, List.of(), normalized,
String.join("\n", htmlLines), String.join("\n", sitemapLines));
}
private HreflangTagGenerator() {}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →