diff --git a/README.md b/README.md index 5fbcc34..d934533 100644 --- a/README.md +++ b/README.md @@ -120,3 +120,116 @@ Google can understand a wide variety of custom sitemap formats that they made up To generate a special type of sitemap, just use GoogleMobileSitemapGenerator, GoogleGeoSitemapGenerator, GoogleCodeSitemapGenerator, GoogleCodeSitemapGenerator, GoogleNewsSitemapGenerator, or GoogleVideoSitemapGenerator instead of WebSitemapGenerator. You can't mix-and-match regular URLs with Google-specific sitemaps, so you'll also have to use a GoogleMobileSitemapUrl, GoogleGeoSitemapUrl, GoogleCodeSitemapUrl, GoogleNewsSitemapUrl, or GoogleVideoSitemapUrl instead of a WebSitemapUrl. Each of them has unique configurable options not available to regular web URLs. + + +How to use SitemapGen4j + +

How to use SitemapGen4j

+ +SitemapGen4j is a library to generate XML sitemaps in Java. + +

What's an XML sitemap?

+ +Quoting from sitemaps.org: + +

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

+ +

Web crawlers usually discover pages from links within the site and from other sites. Sitemaps supplement this data to allow crawlers that support Sitemaps to pick up all URLs in the Sitemap and learn about those URLs using the associated metadata. Using the Sitemap protocol does not guarantee that web pages are included in search engines, but provides hints for web crawlers to do a better job of crawling your site.

+ +

Sitemap 0.90 is offered under the terms of the Attribution-ShareAlike Creative Commons License and has wide adoption, including support from Google, Yahoo!, and Microsoft.

+
+ +

Getting started

+ +

The easiest way to get started is to just use the WebSitemapGenerator class, like this: + +

WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
+wsg.addUrl("http://www.example.com/index.html"); // repeat multiple times
+wsg.write();
+ +

Configuring options

+ +But there are a lot of nifty options available for URLs and for the generator as a whole. To configure the generator, use a builder: + +
WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
+    .gzip(true).build(); // enable gzipped output
+wsg.addUrl("http://www.example.com/index.html");
+wsg.write();
+ +To configure the URLs, construct a WebSitemapUrl with WebSitemapUrl.Options. + +
WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
+WebSitemapUrl url = new WebSitemapUrl.Options("http://www.example.com/index.html")
+    .lastMod(new Date()).priority(1.0).changeFreq(ChangeFreq.HOURLY).build();
+// this will configure the URL with lastmod=now, priority=1.0, changefreq=hourly 
+wsg.addUrl(url);
+wsg.write();
+ +

Configuring the date format

+ +One important configuration option for the sitemap generator is the date format. The W3C datetime standard allows you to choose the precision of your datetime (anything from just specifying the year like "1997" to specifying the fraction of the second like "1997-07-16T19:20:30.45+01:00"); if you don't specify one, we'll try to guess which one you want, and we'll use the default timezone of the local machine, which might not be what you prefer. + +
+// Use DAY pattern (2009-02-07), Greenwich Mean Time timezone
+W3CDateFormat dateFormat = new W3CDateFormat(Pattern.DAY); 
+dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
+WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
+    .dateFormat(dateFormat).build(); // actually use the configured dateFormat
+wsg.addUrl("http://www.example.com/index.html");
+wsg.write();
+ +

Lots of URLs: a sitemap index file

+ +One sitemap can contain a maximum of 50,000 URLs. (Some sitemaps, like Google News sitemaps, can contain only 1,000 URLs.) If you need to put more URLs than that in a sitemap, you'll have to use a sitemap index file. Fortunately, WebSitemapGenerator can manage the whole thing for you. + +
WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
+for (int i = 0; i < 60000; i++) wsg.addUrl("http://www.example.com/doc"+i+".html");
+wsg.write();
+wsg.writeSitemapsWithIndex(); // generate the sitemap_index.xml
+
+ +

That will generate two sitemaps for 60K URLs: sitemap1.xml (with 50K urls) and sitemap2.xml (with the remaining 10K), and then generate a sitemap_index.xml file describing the two.

+ +

It's also possible to carefully organize your sub-sitemaps. For example, it's recommended to group URLs with the same changeFreq together (have one sitemap for changeFreq "daily" and another for changeFreq "yearly"), so you can modify the lastMod of the daily sitemap without modifying the lastMod of the yearly sitemap. To do that, just construct your sitemaps one at a time using the WebSitemapGenerator, then use the SitemapIndexGenerator to create a single index for all of them.

+ +
WebSitemapGenerator wsg;
+// generate foo sitemap
+wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
+    .fileNamePrefix("foo").build();
+for (int i = 0; i < 5; i++) wsg.addUrl("http://www.example.com/foo"+i+".html");
+wsg.write();
+// generate bar sitemap
+wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
+    .fileNamePrefix("bar").build();
+for (int i = 0; i < 5; i++) wsg.addUrl("http://www.example.com/bar"+i+".html");
+wsg.write();
+// generate sitemap index for foo + bar 
+SitemapIndexGenerator sig = new SitemapIndexGenerator("http://www.example.com", myFile);
+sig.addUrl("http://www.example.com/foo.xml");
+sig.addUrl("http://www.example.com/bar.xml");
+sig.write();
+ +

You could also use the SitemapIndexGenerator to incorporate sitemaps generated by other tools. For example, you might use Google's official Python sitemap generator to generate some sitemaps, and use WebSitemapGenerator to generate some sitemaps, and use SitemapIndexGenerator to make an index of all of them.

+ +

Validate your sitemaps

+ +

SitemapGen4j can also validate your sitemaps using the official XML Schema Definition (XSD). If you used SitemapGen4j to make the sitemaps, you shouldn't need to do this unless there's a bug in our code. But you can use it to validate sitemaps generated by other tools, and it provides an extra level of safety.

+ +

It's easy to configure the WebSitemapGenerator to automatically validate your sitemaps right after you write them (but this does slow things down, naturally).

+ +
WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
+    .autoValidate(true).build(); // validate the sitemap after writing
+wsg.addUrl("http://www.example.com/index.html");
+wsg.write();
+ +

You can also use the SitemapValidator directly to manage sitemaps. It has two methods: validateWebSitemap(File f) and validateSitemapIndex(File f).

+ +

Google-specific sitemaps

+ +

Google can understand a wide variety of custom sitemap formats that they made up, including a Mobile sitemaps, Geo sitemaps, Code sitemaps (for Google Code search), Google News sitemaps, and Video sitemaps. SitemapGen4j can generate any/all of these different types of sitemaps.

+ +

To generate a special type of sitemap, just use GoogleMobileSitemapGenerator, GoogleGeoSitemapGenerator, GoogleCodeSitemapGenerator, GoogleCodeSitemapGenerator, GoogleNewsSitemapGenerator, or GoogleVideoSitemapGenerator instead of WebSitemapGenerator.

+ +

You can't mix-and-match regular URLs with Google-specific sitemaps, so you'll also have to use a GoogleMobileSitemapUrl, GoogleGeoSitemapUrl, GoogleCodeSitemapUrl, GoogleNewsSitemapUrl, or GoogleVideoSitemapUrl instead of a WebSitemapUrl. Each of them has unique configurable options not available to regular web URLs.

+ + \ No newline at end of file diff --git a/pom.xml b/pom.xml index be73866..01155f6 100644 --- a/pom.xml +++ b/pom.xml @@ -83,7 +83,7 @@ org.apache.maven.plugins maven-source-plugin - 2.4 + 3.2.1 attach-sources @@ -96,16 +96,15 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.1 + 3.4.1 - attach-javadocs + create-javadoc-jar + javadoc jar - - -Xdoclint:none - + package diff --git a/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapGenerator.java b/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapGenerator.java index 06fe971..9d73558 100644 --- a/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapGenerator.java +++ b/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapGenerator.java @@ -6,100 +6,109 @@ import java.net.URL; /** * Builds a code sitemap for Google Code Search. To configure options, use {@link #builder(URL, File)} + * * @author Dan Fabulich * @see Creating Code Search Sitemaps */ -public class GoogleCodeSitemapGenerator extends SitemapGenerator { - - GoogleCodeSitemapGenerator(AbstractSitemapGeneratorOptions options) { - super(options, new Renderer()); - } +public class GoogleCodeSitemapGenerator extends SitemapGenerator { - /** Configures the generator with a base URL and directory to write the sitemap files. - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. - * @throws MalformedURLException - */ - public GoogleCodeSitemapGenerator(String baseUrl, File baseDir) - throws MalformedURLException { - this(new SitemapGeneratorOptions(baseUrl, baseDir)); - } + GoogleCodeSitemapGenerator(AbstractSitemapGeneratorOptions options) { + super(options, new Renderer()); + } - /**Configures the generator with a base URL and directory to write the sitemap files. - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. - */ - public GoogleCodeSitemapGenerator(URL baseUrl, File baseDir) { - this(new SitemapGeneratorOptions(baseUrl, baseDir)); - } - - /**Configures the generator with a base URL and a null directory. The object constructed - * is not intended to be used to write to files. Rather, it is intended to be used to obtain - * XML-formatted strings that represent sitemaps. - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - */ - public GoogleCodeSitemapGenerator(String baseUrl) throws MalformedURLException { - this(new SitemapGeneratorOptions(new URL(baseUrl))); - } - - /**Configures the generator with a base URL and a null directory. The object constructed - * is not intended to be used to write to files. Rather, it is intended to be used to obtain - * XML-formatted strings that represent sitemaps. - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - */ - public GoogleCodeSitemapGenerator(URL baseUrl) { - this(new SitemapGeneratorOptions(baseUrl)); - } - - /** Configures a builder so you can specify sitemap generator options - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. - * @return a builder; call .build() on it to make a sitemap generator - */ - public static SitemapGeneratorBuilder builder(URL baseUrl, File baseDir) { - return new SitemapGeneratorBuilder(baseUrl, baseDir, GoogleCodeSitemapGenerator.class); - } - - /** Configures a builder so you can specify sitemap generator options - * - * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL - * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. - * @return a builder; call .build() on it to make a sitemap generator - * @throws MalformedURLException - */ - public static SitemapGeneratorBuilder builder(String baseUrl, File baseDir) throws MalformedURLException { - return new SitemapGeneratorBuilder(baseUrl, baseDir, GoogleCodeSitemapGenerator.class); - } + /** + * Configures the generator with a base URL and directory to write the sitemap files. + * + * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL + * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. + * @throws MalformedURLException Exception + */ + public GoogleCodeSitemapGenerator(String baseUrl, File baseDir) + throws MalformedURLException { + this(new SitemapGeneratorOptions(baseUrl, baseDir)); + } - private static class Renderer extends AbstractSitemapUrlRenderer implements ISitemapUrlRenderer { + /** + * Configures the generator with a base URL and directory to write the sitemap files. + * + * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL + * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. + */ + public GoogleCodeSitemapGenerator(URL baseUrl, File baseDir) { + this(new SitemapGeneratorOptions(baseUrl, baseDir)); + } - public Class getUrlClass() { - return GoogleCodeSitemapUrl.class; - } - - public String getXmlNamespaces() { - return "xmlns:codesearch=\"http://www.google.com/codesearch/schemas/sitemap/1.0\""; - } - public void render(GoogleCodeSitemapUrl url, StringBuilder sb, - W3CDateFormat dateFormat) { - StringBuilder tagSb = new StringBuilder(); - tagSb.append(" \n"); - renderTag(tagSb, "codesearch", "filetype", url.getFileType()); - renderTag(tagSb, "codesearch", "license", url.getLicense()); - renderTag(tagSb, "codesearch", "filename", url.getFileName()); - renderTag(tagSb, "codesearch", "packageurl", url.getPackageUrl()); - renderTag(tagSb, "codesearch", "packagemap", url.getPackageMap()); - tagSb.append(" \n"); - super.render(url, sb, dateFormat, tagSb.toString()); - } - - } + /** + * Configures the generator with a base URL and a null directory. The object constructed + * is not intended to be used to write to files. Rather, it is intended to be used to obtain + * XML-formatted strings that represent sitemaps. + * + * @param baseUrl + * @throws MalformedURLException Exception + */ + public GoogleCodeSitemapGenerator(String baseUrl) throws MalformedURLException { + this(new SitemapGeneratorOptions(new URL(baseUrl))); + } + + /** + * Configures the generator with a base URL and a null directory. The object constructed + * is not intended to be used to write to files. Rather, it is intended to be used to obtain + * XML-formatted strings that represent sitemaps. + * + * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL + */ + public GoogleCodeSitemapGenerator(URL baseUrl) { + this(new SitemapGeneratorOptions(baseUrl)); + } + + /** + * Configures a builder so you can specify sitemap generator options + * + * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL + * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. + * @return a builder; call .build() on it to make a sitemap generator + */ + public static SitemapGeneratorBuilder builder(URL baseUrl, File baseDir) { + return new SitemapGeneratorBuilder(baseUrl, baseDir, GoogleCodeSitemapGenerator.class); + } + + /** + * Configures a builder so you can specify sitemap generator options + * + * @param baseUrl All URLs in the generated sitemap(s) should appear under this base URL + * @param baseDir Sitemap files will be generated in this directory as either "sitemap.xml" or "sitemap1.xml" "sitemap2.xml" and so on. + * @return a builder; call .build() on it to make a sitemap generator + * @throws MalformedURLException + */ + public static SitemapGeneratorBuilder builder(String baseUrl, File baseDir) throws MalformedURLException { + return new SitemapGeneratorBuilder(baseUrl, baseDir, GoogleCodeSitemapGenerator.class); + } + + private static class Renderer extends AbstractSitemapUrlRenderer implements ISitemapUrlRenderer { + + public Class getUrlClass() { + return GoogleCodeSitemapUrl.class; + } + + public String getXmlNamespaces() { + return "xmlns:codesearch=\"http://www.google.com/codesearch/schemas/sitemap/1.0\""; + } + + public void render(GoogleCodeSitemapUrl url, StringBuilder sb, + W3CDateFormat dateFormat) { + StringBuilder tagSb = new StringBuilder(); + tagSb.append(" \n"); + renderTag(tagSb, "codesearch", "filetype", url.getFileType()); + renderTag(tagSb, "codesearch", "license", url.getLicense()); + renderTag(tagSb, "codesearch", "filename", url.getFileName()); + renderTag(tagSb, "codesearch", "packageurl", url.getPackageUrl()); + renderTag(tagSb, "codesearch", "packagemap", url.getPackageMap()); + tagSb.append(" \n"); + super.render(url, sb, dateFormat, tagSb.toString()); + } + + } + - } diff --git a/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapUrl.java b/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapUrl.java index aefa5d7..3409ea8 100644 --- a/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapUrl.java +++ b/src/main/java/com/redfin/sitemapgenerator/GoogleCodeSitemapUrl.java @@ -18,7 +18,7 @@ public class GoogleCodeSitemapUrl extends WebSitemapUrl { */ public enum FileType { /** A special value meaning that the URL is a compressed archive containing code. - * @see @see Supported archive suffixes + * @see Supported archive suffixes */ ARCHIVE("Archive"), ADA("Ada"), diff --git a/src/main/java/com/redfin/sitemapgenerator/GoogleMobileSitemapUrl.java b/src/main/java/com/redfin/sitemapgenerator/GoogleMobileSitemapUrl.java index 4d702a8..ae76a59 100644 --- a/src/main/java/com/redfin/sitemapgenerator/GoogleMobileSitemapUrl.java +++ b/src/main/java/com/redfin/sitemapgenerator/GoogleMobileSitemapUrl.java @@ -18,8 +18,11 @@ public class GoogleMobileSitemapUrl extends WebSitemapUrl { public Options(String url) throws MalformedURLException { this(new URL(url)); } - - /** Specifies the url */ + + /** + * Specifies the url + * @param url + */ public Options(URL url) { super(url, GoogleMobileSitemapUrl.class); } diff --git a/src/main/java/com/redfin/sitemapgenerator/GoogleVideoSitemapUrl.java b/src/main/java/com/redfin/sitemapgenerator/GoogleVideoSitemapUrl.java index e2045b1..e98be56 100644 --- a/src/main/java/com/redfin/sitemapgenerator/GoogleVideoSitemapUrl.java +++ b/src/main/java/com/redfin/sitemapgenerator/GoogleVideoSitemapUrl.java @@ -5,347 +5,396 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Date; -/** One configurable Google Video Search URL. To configure, use {@link Options} - * +/** + * One configurable Google Video Search URL. To configure, use {@link Options} + * * @author Dan Fabulich * @see Options * @see Creating Video Sitemaps */ public class GoogleVideoSitemapUrl extends WebSitemapUrl { - private final URL playerUrl; - private final URL contentUrl; - private final URL thumbnailUrl; - private final String title; - private final String description; - private final Double rating; - private final Integer viewCount; - private final Date publicationDate; - private final ArrayList tags; - private final String category; - // TODO can there be multiple categories? - // "Usually a video will belong to a single category." - // http://www.google.com/support/webmasters/bin/answer.py?answer=80472 - private final String familyFriendly; - private final Integer durationInSeconds; - private final String allowEmbed; - - /** Options to configure Google Video URLs */ - public static class Options extends AbstractSitemapUrlOptions { - private URL playerUrl; - private URL contentUrl; - private URL thumbnailUrl; - private String title; - private String description; - private Double rating; - private Integer viewCount; - private Date publicationDate; - private ArrayList tags; - private String category; - // TODO can there be multiple categories? - // "Usually a video will belong to a single category." - // http://www.google.com/support/webmasters/bin/answer.py?answer=80472 - private Boolean familyFriendly; - private Integer durationInSeconds; - private Boolean allowEmbed; - - /** Specifies a landing page URL, together with a "player" (e.g. SWF) - * - * @param url the landing page URL - * @param playerUrl the URL of the "player" (e.g. SWF file) - * @param allowEmbed when specifying a player, you must specify whether embedding is allowed - */ - public Options(URL url, URL playerUrl, boolean allowEmbed) { - super(url, GoogleVideoSitemapUrl.class); - this.playerUrl = playerUrl; - this.allowEmbed = allowEmbed; - } - - /** Specifies a landing page URL, together with the URL of the underlying video (e.g. FLV) - * - * @param url the landing page URL - * @param contentUrl the URL of the underlying video (e.g. FLV) - */ - public Options(URL url, URL contentUrl) { - super(url, GoogleVideoSitemapUrl.class); - this.contentUrl = contentUrl; - } - - /** Specifies a player URL (e.g. SWF) - * - * @param playerUrl the URL of the "player" (e.g. SWF file) - * @param allowEmbed when specifying a player, you must specify whether embedding is allowed - */ - public Options playerUrl(URL playerUrl, boolean allowEmbed) { - this.playerUrl = playerUrl; - this.allowEmbed = allowEmbed; - return this; - } - - /** Specifies the URL of the underlying video (e.g FLV) */ - public Options contentUrl(URL contentUrl) { - this.contentUrl = contentUrl; - return this; - } - - /** - * A URL pointing to the URL for the video thumbnail image file. This - * allows you to suggest the thumbnail you want displayed in search - * results. If you provide a {@link #contentUrl(URL)}, Google will attempt - * to generate a set of representative thumbnail images from your actual - * video content. However, we strongly recommended that you provide a - * thumbnail URL to increase the likelihood of your video being included - * in the video index. - */ - public Options thumbnailUrl(URL thumbnailUrl) { - this.thumbnailUrl = thumbnailUrl; - return this; - } - - /** The title of the video. Limited to 100 characters. */ - public Options title(String title) { - if (title != null) { - if (title.length() > 100) { - throw new RuntimeException("Video title is limited to 100 characters: " + title); - } - } - this.title = title; - return this; - } - - /** The description of the video. Descriptions longer than 2048 characters will be truncated. */ - public Options description(String description) { - if (description != null) { - if (description.length() > 2048) { - throw new RuntimeException("Truncate video descriptions to 2048 characters: " + description); - } - } - this.description = description; - return this; - } - - /** The rating of the video. The value must be number in the range 0.0-5.0. */ - public Options rating(Double rating) { - if (rating != null) { - if (rating < 0 || rating > 5.0) { - throw new RuntimeException("Rating must be between 0.0 and 5.0:" + rating); - } - } - this.rating = rating; - return this; - } - - /** The number of times the video has been viewed */ - public Options viewCount(int viewCount) { - this.viewCount = viewCount; - return this; - } - - /** The date the video was first published, in {@link W3CDateFormat}. */ - public Options publicationDate(Date publicationDate) { - this.publicationDate = publicationDate; - return this; - } - - /** - * Tag associated with the video; tags are generally very short - * descriptions of key concepts associated with a video or piece of - * content. A single video could have several tags, although it might - * belong to only one category. For example, a video about grilling food - * may belong in the Grilling category, but could be tagged "steak", - * "meat", "summer", and "outdoor". Create a new element for - * each tag associated with a video. A maximum of 32 tags is permitted. - */ - public Options tags(ArrayList tags) { - this.tags = tags; - return this; - } - - /** - * Tag associated with the video; tags are generally very short - * descriptions of key concepts associated with a video or piece of - * content. A single video could have several tags, although it might - * belong to only one category. For example, a video about grilling food - * may belong in the Grilling category, but could be tagged "steak", - * "meat", "summer", and "outdoor". Create a new element for - * each tag associated with a video. A maximum of 32 tags is permitted. - */ - public Options tags(Iterable tags) { - this.tags = new ArrayList(); - for (String tag : tags) { - this.tags.add(tag); - } - return this; - } - - /** - * Tag associated with the video; tags are generally very short - * descriptions of key concepts associated with a video or piece of - * content. A single video could have several tags, although it might - * belong to only one category. For example, a video about grilling food - * may belong in the Grilling category, but could be tagged "steak", - * "meat", "summer", and "outdoor". Create a new element for - * each tag associated with a video. A maximum of 32 tags is permitted. - */ - public Options tags(String... tags) { - return tags(Arrays.asList(tags)); - } - - /** - * The video's category; for example, cooking. The value - * should be a string no longer than 256 characters. In general, - * categories are broad groupings of content by subject. Usually a video - * will belong to a single category. For example, a site about cooking - * could have categories for Broiling, Baking, and Grilling - */ - public Options category(String category) { - if (category != null) { - if (category.length() > 256) { - throw new RuntimeException("Video category is limited to 256 characters: " + title); - } - } - this.category = category; - return this; - } - - /** Whether the video is suitable for viewing by children */ - public Options familyFriendly(boolean familyFriendly) { - this.familyFriendly = familyFriendly; - return this; - } - - /** The duration of the video in seconds; value must be between 0 and 28800 (8 hours). */ - public Options durationInSeconds(int durationInSeconds) { - if (durationInSeconds < 0 || durationInSeconds > 28800) { - throw new RuntimeException("Duration must be between 0 and 28800 (8 hours):" + durationInSeconds); - } - this.durationInSeconds = durationInSeconds; - return this; - } - - } + private final URL playerUrl; + private final URL contentUrl; + private final URL thumbnailUrl; + private final String title; + private final String description; + private final Double rating; + private final Integer viewCount; + private final Date publicationDate; + private final ArrayList tags; + private final String category; + // TODO can there be multiple categories? + // "Usually a video will belong to a single category." + // http://www.google.com/support/webmasters/bin/answer.py?answer=80472 + private final String familyFriendly; + private final Integer durationInSeconds; + private final String allowEmbed; - /** Specifies a landing page URL, together with a "player" (e.g. SWF) - * - * @param url the landing page URL - * @param playerUrl the URL of the "player" (e.g. SWF file) - * @param allowEmbed when specifying a player, you must specify whether embedding is allowed - */ - public GoogleVideoSitemapUrl(URL url, URL playerUrl, boolean allowEmbed) { - this(new Options(url, playerUrl, allowEmbed)); - } - - /** Specifies a landing page URL, together with the URL of the underlying video (e.g. FLV) - * - * @param url the landing page URL - * @param contentUrl the URL of the underlying video (e.g. FLV) - */ - public GoogleVideoSitemapUrl(URL url, URL contentUrl) { - this(new Options(url, contentUrl)); - } - - /** Configures the url with options */ - public GoogleVideoSitemapUrl(Options options) { - super(options); - contentUrl = options.contentUrl; - playerUrl = options.playerUrl; - if (playerUrl == null && contentUrl == null) { - throw new RuntimeException("You must specify either contentUrl or playerUrl or both; neither were specified"); - } - allowEmbed = convertBooleanToYesOrNo(options.allowEmbed); - if (playerUrl != null && allowEmbed == null) { - throw new RuntimeException("allowEmbed must be specified if playerUrl is specified"); - } - category = options.category; - - description = options.description; - durationInSeconds = options.durationInSeconds; - familyFriendly = convertBooleanToYesOrNo(options.familyFriendly); - - publicationDate = options.publicationDate; - rating = options.rating; - tags = options.tags; - if (tags != null && tags.size() > 32) { - throw new RuntimeException("A maximum of 32 tags is permitted"); - } - thumbnailUrl = options.thumbnailUrl; - title = options.title; - viewCount = options.viewCount; - } - - private static String convertBooleanToYesOrNo(Boolean value) { - if (value == null) return null; - return value ? "Yes" : "No"; - } - - - /** Retrieves the {@link Options#playerUrl}*/ - public URL getPlayerUrl() { - return playerUrl; - } - - /** Retrieves the {@link Options#contentUrl}*/ - public URL getContentUrl() { - return contentUrl; - } + /** + * Options to configure Google Video URLs + */ + public static class Options extends AbstractSitemapUrlOptions { + private URL playerUrl; + private URL contentUrl; + private URL thumbnailUrl; + private String title; + private String description; + private Double rating; + private Integer viewCount; + private Date publicationDate; + private ArrayList tags; + private String category; + // TODO can there be multiple categories? + // "Usually a video will belong to a single category." + // http://www.google.com/support/webmasters/bin/answer.py?answer=80472 + private Boolean familyFriendly; + private Integer durationInSeconds; + private Boolean allowEmbed; - /** Retrieves the {@link Options#thumbnailUrl}*/ - public URL getThumbnailUrl() { - return thumbnailUrl; - } + /** + * Specifies a landing page URL, together with a "player" (e.g. SWF) + * + * @param url the landing page URL + * @param playerUrl the URL of the "player" (e.g. SWF file) + * @param allowEmbed when specifying a player, you must specify whether embedding is allowed + */ + public Options(URL url, URL playerUrl, boolean allowEmbed) { + super(url, GoogleVideoSitemapUrl.class); + this.playerUrl = playerUrl; + this.allowEmbed = allowEmbed; + } - /** Retrieves the {@link Options#title}*/ - public String getTitle() { - return title; - } + /** + * Specifies a landing page URL, together with the URL of the underlying video (e.g. FLV) + * + * @param url the landing page URL + * @param contentUrl the URL of the underlying video (e.g. FLV) + */ + public Options(URL url, URL contentUrl) { + super(url, GoogleVideoSitemapUrl.class); + this.contentUrl = contentUrl; + } - /** Retrieves the {@link Options#description}*/ - public String getDescription() { - return description; - } + /** + * Specifies a player URL (e.g. SWF) + * + * @param playerUrl the URL of the "player" (e.g. SWF file) + * @param allowEmbed when specifying a player, you must specify whether embedding is allowed + */ + public Options playerUrl(URL playerUrl, boolean allowEmbed) { + this.playerUrl = playerUrl; + this.allowEmbed = allowEmbed; + return this; + } - /** Retrieves the {@link Options#rating}*/ - public Double getRating() { - return rating; - } + /** + * Specifies the URL of the underlying video (e.g FLV) + */ + public Options contentUrl(URL contentUrl) { + this.contentUrl = contentUrl; + return this; + } - /** Retrieves the {@link Options#viewCount}*/ - public Integer getViewCount() { - return viewCount; - } + /** + * A URL pointing to the URL for the video thumbnail image file. This + * allows you to suggest the thumbnail you want displayed in search + * results. If you provide a {@link #contentUrl(URL)}, Google will attempt + * to generate a set of representative thumbnail images from your actual + * video content. However, we strongly recommended that you provide a + * thumbnail URL to increase the likelihood of your video being included + * in the video index. + */ + public Options thumbnailUrl(URL thumbnailUrl) { + this.thumbnailUrl = thumbnailUrl; + return this; + } - /** Retrieves the {@link Options#publicationDate}*/ - public Date getPublicationDate() { - return publicationDate; - } + /** + * The title of the video. Limited to 100 characters. + */ + public Options title(String title) { + if (title != null) { + if (title.length() > 100) { + throw new RuntimeException("Video title is limited to 100 characters: " + title); + } + } + this.title = title; + return this; + } - /** Retrieves the {@link Options#tags}*/ - public ArrayList getTags() { - return tags; - } + /** + * The description of the video. Descriptions longer than 2048 characters will be truncated. + */ + public Options description(String description) { + if (description != null) { + if (description.length() > 2048) { + throw new RuntimeException("Truncate video descriptions to 2048 characters: " + description); + } + } + this.description = description; + return this; + } - /** Retrieves the {@link Options#category}*/ - public String getCategory() { - return category; - } + /** + * The rating of the video. The value must be number in the range 0.0-5.0. + */ + public Options rating(Double rating) { + if (rating != null) { + if (rating < 0 || rating > 5.0) { + throw new RuntimeException("Rating must be between 0.0 and 5.0:" + rating); + } + } + this.rating = rating; + return this; + } - /** Retrieves whether the video is {@link Options#familyFriendly}*/ - public String getFamilyFriendly() { - return familyFriendly; - } + /** + * The number of times the video has been viewed + */ + public Options viewCount(int viewCount) { + this.viewCount = viewCount; + return this; + } - /** Retrieves the {@link Options#durationInSeconds}*/ - public Integer getDurationInSeconds() { - return durationInSeconds; - } + /** + * The date the video was first published, in {@link W3CDateFormat}. + */ + public Options publicationDate(Date publicationDate) { + this.publicationDate = publicationDate; + return this; + } - /** Retrieves whether embedding is allowed */ - public String getAllowEmbed() { - return allowEmbed; - } + /** + * Tag associated with the video; tags are generally very short + * descriptions of key concepts associated with a video or piece of + * content. A single video could have several tags, although it might + * belong to only one category. For example, a video about grilling food + * may belong in the Grilling category, but could be tagged "steak", + * "meat", "summer", and "outdoor". Create a new <video:tag> element for + * each tag associated with a video. A maximum of 32 tags is permitted. + */ + public Options tags(ArrayList tags) { + this.tags = tags; + return this; + } + + /** + * Tag associated with the video; tags are generally very short + * descriptions of key concepts associated with a video or piece of + * content. A single video could have several tags, although it might + * belong to only one category. For example, a video about grilling food + * may belong in the Grilling category, but could be tagged "steak", + * "meat", "summer", and "outdoor". Create a new <video:tag> element for + * each tag associated with a video. A maximum of 32 tags is permitted. + */ + public Options tags(Iterable tags) { + this.tags = new ArrayList(); + for (String tag : tags) { + this.tags.add(tag); + } + return this; + } + + /** + * Tag associated with the video; tags are generally very short + * descriptions of key concepts associated with a video or piece of + * content. A single video could have several tags, although it might + * belong to only one category. For example, a video about grilling food + * may belong in the Grilling category, but could be tagged "steak", + * "meat", "summer", and "outdoor". Create a new <video:tag> element for + * each tag associated with a video. A maximum of 32 tags is permitted. + */ + public Options tags(String... tags) { + return tags(Arrays.asList(tags)); + } + + /** + * The video's category; for example, cooking. The value + * should be a string no longer than 256 characters. In general, + * categories are broad groupings of content by subject. Usually a video + * will belong to a single category. For example, a site about cooking + * could have categories for Broiling, Baking, and Grilling + */ + public Options category(String category) { + if (category != null) { + if (category.length() > 256) { + throw new RuntimeException("Video category is limited to 256 characters: " + title); + } + } + this.category = category; + return this; + } + + /** + * Whether the video is suitable for viewing by children + */ + public Options familyFriendly(boolean familyFriendly) { + this.familyFriendly = familyFriendly; + return this; + } + + /** + * The duration of the video in seconds; value must be between 0 and 28800 (8 hours). + */ + public Options durationInSeconds(int durationInSeconds) { + if (durationInSeconds < 0 || durationInSeconds > 28800) { + throw new RuntimeException("Duration must be between 0 and 28800 (8 hours):" + durationInSeconds); + } + this.durationInSeconds = durationInSeconds; + return this; + } + + } + + /** + * Specifies a landing page URL, together with a "player" (e.g. SWF) + * + * @param url the landing page URL + * @param playerUrl the URL of the "player" (e.g. SWF file) + * @param allowEmbed when specifying a player, you must specify whether embedding is allowed + */ + public GoogleVideoSitemapUrl(URL url, URL playerUrl, boolean allowEmbed) { + this(new Options(url, playerUrl, allowEmbed)); + } + + /** + * Specifies a landing page URL, together with the URL of the underlying video (e.g. FLV) + * + * @param url the landing page URL + * @param contentUrl the URL of the underlying video (e.g. FLV) + */ + public GoogleVideoSitemapUrl(URL url, URL contentUrl) { + this(new Options(url, contentUrl)); + } + + /** + * Configures the url with options + */ + public GoogleVideoSitemapUrl(Options options) { + super(options); + contentUrl = options.contentUrl; + playerUrl = options.playerUrl; + if (playerUrl == null && contentUrl == null) { + throw new RuntimeException("You must specify either contentUrl or playerUrl or both; neither were specified"); + } + allowEmbed = convertBooleanToYesOrNo(options.allowEmbed); + if (playerUrl != null && allowEmbed == null) { + throw new RuntimeException("allowEmbed must be specified if playerUrl is specified"); + } + category = options.category; + + description = options.description; + durationInSeconds = options.durationInSeconds; + familyFriendly = convertBooleanToYesOrNo(options.familyFriendly); + + publicationDate = options.publicationDate; + rating = options.rating; + tags = options.tags; + if (tags != null && tags.size() > 32) { + throw new RuntimeException("A maximum of 32 tags is permitted"); + } + thumbnailUrl = options.thumbnailUrl; + title = options.title; + viewCount = options.viewCount; + } + + private static String convertBooleanToYesOrNo(Boolean value) { + if (value == null) return null; + return value ? "Yes" : "No"; + } + /** + * Retrieves the {@link Options#playerUrl} + */ + public URL getPlayerUrl() { + return playerUrl; + } + /** + * Retrieves the {@link Options#contentUrl} + */ + public URL getContentUrl() { + return contentUrl; + } + + /** + * Retrieves the {@link Options#thumbnailUrl} + */ + public URL getThumbnailUrl() { + return thumbnailUrl; + } + + /** + * Retrieves the {@link Options#title} + */ + public String getTitle() { + return title; + } + + /** + * Retrieves the {@link Options#description} + */ + public String getDescription() { + return description; + } + + /** + * Retrieves the {@link Options#rating} + */ + public Double getRating() { + return rating; + } + + /** + * Retrieves the {@link Options#viewCount} + */ + public Integer getViewCount() { + return viewCount; + } + + /** + * Retrieves the {@link Options#publicationDate} + */ + public Date getPublicationDate() { + return publicationDate; + } + + /** + * Retrieves the {@link Options#tags} + */ + public ArrayList getTags() { + return tags; + } + + /** + * Retrieves the {@link Options#category} + */ + public String getCategory() { + return category; + } + + /** + * Retrieves whether the video is {@link Options#familyFriendly} + */ + public String getFamilyFriendly() { + return familyFriendly; + } + + /** + * Retrieves the {@link Options#durationInSeconds} + */ + public Integer getDurationInSeconds() { + return durationInSeconds; + } + + /** + * Retrieves whether embedding is allowed + */ + public String getAllowEmbed() { + return allowEmbed; + } } diff --git a/src/main/java/com/redfin/sitemapgenerator/SitemapGenerator.java b/src/main/java/com/redfin/sitemapgenerator/SitemapGenerator.java index 43eb193..3b16c82 100644 --- a/src/main/java/com/redfin/sitemapgenerator/SitemapGenerator.java +++ b/src/main/java/com/redfin/sitemapgenerator/SitemapGenerator.java @@ -12,283 +12,306 @@ import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; -abstract class SitemapGenerator> { - /** 50000 URLs per sitemap maximum */ - public static final int MAX_URLS_PER_SITEMAP = 50000; - - private final URL baseUrl; - private final File baseDir; - private final String fileNamePrefix; - private final String fileNameSuffix; - private final boolean allowEmptySitemap; - private final boolean allowMultipleSitemaps; - private final ArrayList urls = new ArrayList(); - private final W3CDateFormat dateFormat; - private final int maxUrls; - private final boolean autoValidate; - private final boolean gzip; - private final ISitemapUrlRenderer renderer; - private int mapCount = 0; - private boolean finished = false; - - private final ArrayList outFiles = new ArrayList(); - - public SitemapGenerator(AbstractSitemapGeneratorOptions options, ISitemapUrlRenderer renderer) { - baseDir = options.baseDir; - baseUrl = options.baseUrl; - fileNamePrefix = options.fileNamePrefix; - W3CDateFormat dateFormat = options.dateFormat; - if (dateFormat == null) dateFormat = new W3CDateFormat(); - this.dateFormat = dateFormat; - allowEmptySitemap = options.allowEmptySitemap; - allowMultipleSitemaps = options.allowMultipleSitemaps; - maxUrls = options.maxUrls; - autoValidate = options.autoValidate; - gzip = options.gzip; - this.renderer = renderer; +abstract class SitemapGenerator> { + /** + * 50000 URLs per sitemap maximum + */ + public static final int MAX_URLS_PER_SITEMAP = 50000; - if(options.suffixStringPattern != null && !options.suffixStringPattern.isEmpty()) { - fileNameSuffix = gzip ? options.suffixStringPattern + ".xml.gz" : options.suffixStringPattern + ".xml"; - } - else { - fileNameSuffix = gzip ? ".xml.gz" : ".xml"; - } - } + private final URL baseUrl; + private final File baseDir; + private final String fileNamePrefix; + private final String fileNameSuffix; + private final boolean allowEmptySitemap; + private final boolean allowMultipleSitemaps; + private final ArrayList urls = new ArrayList(); + private final W3CDateFormat dateFormat; + private final int maxUrls; + private final boolean autoValidate; + private final boolean gzip; + private final ISitemapUrlRenderer renderer; + private int mapCount = 0; + private boolean finished = false; - /** Add one URL of the appropriate type to this sitemap. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or else write out one sitemap immediately. - * @param url the URL to add to this sitemap - * @return this - */ - public THIS addUrl(U url) { - if (finished) throw new RuntimeException("Sitemap already printed; you must create a new generator to make more sitemaps"); - UrlUtils.checkUrl(url.getUrl(), baseUrl); - if (urls.size() == maxUrls) { - if (!allowMultipleSitemaps) throw new RuntimeException("More than " + maxUrls + " urls, but allowMultipleSitemaps is false. Enable allowMultipleSitemaps to split the sitemap into multiple files with a sitemap index."); - if (baseDir != null) { - if (mapCount == 0) mapCount++; - try { - writeSiteMap(); - } catch(IOException ex) { - throw new RuntimeException("Closing of stream failed.", ex); - } - mapCount++; - urls.clear(); - } - } - urls.add(url); - return getThis(); - } - - /** Add multiple URLs of the appropriate type to this sitemap, one at a time. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or write out one sitemap immediately. - * @param urls the URLs to add to this sitemap - * @return this - */ - public THIS addUrls(Iterable urls) { - for (U url : urls) addUrl(url); - return getThis(); - } - - /** Add multiple URLs of the appropriate type to this sitemap, one at a time. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or write out one sitemap immediately. - * @param urls the URLs to add to this sitemap - * @return this - */ - public THIS addUrls(U... urls) { - for (U url : urls) addUrl(url); - return getThis(); - } - - /** Add multiple URLs of the appropriate type to this sitemap, one at a time. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or write out one sitemap immediately. - * @param urls the URLs to add to this sitemap - * @return this - */ - public THIS addUrls(String... urls) { - for (String url : urls) addUrl(url); - return getThis(); - } - - /** Add one URL of the appropriate type to this sitemap. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or else write out one sitemap immediately. - * @param url the URL to add to this sitemap - * @return this - */ - public THIS addUrl(String url) { - U sitemapUrl; - try { - sitemapUrl = renderer.getUrlClass().getConstructor(String.class).newInstance(url); - return addUrl(sitemapUrl); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** Add multiple URLs of the appropriate type to this sitemap, one at a time. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or write out one sitemap immediately. - * @param urls the URLs to add to this sitemap - * @return this - */ - public THIS addUrls(URL... urls) { - for (URL url : urls) addUrl(url); - return getThis(); - } - - /** Add one URL of the appropriate type to this sitemap. - * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, - * or write out one sitemap immediately. - * @param url the URL to add to this sitemap - * @return this - */ - public THIS addUrl(URL url) { - U sitemapUrl; - try { - sitemapUrl = renderer.getUrlClass().getConstructor(URL.class).newInstance(url); - return addUrl(sitemapUrl); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - THIS getThis() { - return (THIS)this; - } - - /** Write out remaining URLs; this method can only be called once. This is necessary so we can keep an accurate count for {@link #writeSitemapsWithIndex()}. - * - * @return a list of files we wrote out to disk - */ - public List write() { - if (finished) throw new RuntimeException("Sitemap already printed; you must create a new generator to make more sitemaps"); - if (!allowEmptySitemap && urls.isEmpty() && mapCount == 0) throw new RuntimeException("No URLs added, sitemap would be empty; you must add some URLs with addUrls"); - try { - writeSiteMap(); - } catch (IOException ex) { - throw new RuntimeException("Closing of streams has failed at some point.", ex); - } - finished = true; - return outFiles; - } - - /** - * Writes out the sitemaps as a list of strings. - * Each string in the list is a formatted list of URLs. - * We return a list because the URLs may not all fit -- - * google specifies a maximum of 50,000 URLs in one sitemap. - * @return a list of XML-formatted strings - */ - public List writeAsStrings() { - List listOfSiteMapStrings = new ArrayList(); - for (int start = 0; start < urls.size(); start += maxUrls) { - int end = start + maxUrls; - if (end > urls.size()) { - end = urls.size(); - } - StringBuilder sb = new StringBuilder(); - writeSiteMapAsString(sb, urls.subList(start, end)); - listOfSiteMapStrings.add(sb.toString()); - } - return listOfSiteMapStrings; - } - - private void writeSiteMapAsString(StringBuilder sb, List urls) { - sb.append("\n"); - sb.append("\n"); - for (U url : urls) { - renderer.render(url, sb, dateFormat); - } - sb.append(""); - } - - /** - * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. - * The sitemap index is written to {baseDir}/sitemap_index.xml - */ - public File writeSitemapsWithIndex() { - return writeSitemapsWithIndex(new File(baseDir, "sitemap_index.xml")); - } + private final ArrayList outFiles = new ArrayList(); - /** - * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. - */ - public String writeSitemapsWithIndexAsString() { - return prepareSitemapIndexGenerator(null).writeAsString(); - } + public SitemapGenerator(AbstractSitemapGeneratorOptions options, ISitemapUrlRenderer renderer) { + baseDir = options.baseDir; + baseUrl = options.baseUrl; + fileNamePrefix = options.fileNamePrefix; + W3CDateFormat dateFormat = options.dateFormat; + if (dateFormat == null) dateFormat = new W3CDateFormat(); + this.dateFormat = dateFormat; + allowEmptySitemap = options.allowEmptySitemap; + allowMultipleSitemaps = options.allowMultipleSitemaps; + maxUrls = options.maxUrls; + autoValidate = options.autoValidate; + gzip = options.gzip; + this.renderer = renderer; - /** - * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. - * - * @param outFile the destination file of the sitemap index. - */ - public File writeSitemapsWithIndex(File outFile) { - prepareSitemapIndexGenerator(outFile).write(); - return outFile; - } + if (options.suffixStringPattern != null && !options.suffixStringPattern.isEmpty()) { + fileNameSuffix = gzip ? options.suffixStringPattern + ".xml.gz" : options.suffixStringPattern + ".xml"; + } else { + fileNameSuffix = gzip ? ".xml.gz" : ".xml"; + } + } - private SitemapIndexGenerator prepareSitemapIndexGenerator(File outFile) { - if (!finished) throw new RuntimeException("Sitemaps not generated yet; call write() first"); - SitemapIndexGenerator sig; - sig = new SitemapIndexGenerator.Options(baseUrl, outFile).dateFormat(dateFormat).autoValidate(autoValidate).build(); - sig.addUrls(fileNamePrefix, fileNameSuffix, mapCount); - return sig; - } - - private void writeSiteMap() throws IOException { - if (baseDir == null) { - throw new NullPointerException("To write to files, baseDir must not be null"); - } - if (urls.isEmpty() && (mapCount > 0 || !allowEmptySitemap)) return; - String fileNamePrefix; - if (mapCount > 0) { - fileNamePrefix = this.fileNamePrefix + mapCount; - } else { - fileNamePrefix = this.fileNamePrefix; - } - File outFile = new File(baseDir, fileNamePrefix+fileNameSuffix); - outFiles.add(outFile); + /** + * Add one URL of the appropriate type to this sitemap. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or else write out one sitemap immediately. + * + * @param url the URL to add to this sitemap + * @return this + */ + public THIS addUrl(U url) { + if (finished) + throw new RuntimeException("Sitemap already printed; you must create a new generator to make more sitemaps"); + UrlUtils.checkUrl(url.getUrl(), baseUrl); + if (urls.size() == maxUrls) { + if (!allowMultipleSitemaps) + throw new RuntimeException("More than " + maxUrls + " urls, but allowMultipleSitemaps is false. Enable allowMultipleSitemaps to split the sitemap into multiple files with a sitemap index."); + if (baseDir != null) { + if (mapCount == 0) mapCount++; + try { + writeSiteMap(); + } catch (IOException ex) { + throw new RuntimeException("Closing of stream failed.", ex); + } + mapCount++; + urls.clear(); + } + } + urls.add(url); + return getThis(); + } - OutputStreamWriter out = null; - try { - if (gzip) { - FileOutputStream fileStream = new FileOutputStream(outFile); - GZIPOutputStream gzipStream = new GZIPOutputStream(fileStream); - out = new OutputStreamWriter(gzipStream, Charset.forName("UTF-8").newEncoder()); - } else { - out = new OutputStreamWriter(new FileOutputStream(outFile), Charset.forName("UTF-8").newEncoder()); - } + /** + * Add multiple URLs of the appropriate type to this sitemap, one at a time. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or write out one sitemap immediately. + * + * @param urls the URLs to add to this sitemap + * @return this + */ + public THIS addUrls(Iterable urls) { + for (U url : urls) addUrl(url); + return getThis(); + } - writeSiteMap(out); - out.flush(); + /** + * Add multiple URLs of the appropriate type to this sitemap, one at a time. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or write out one sitemap immediately. + * + * @param urls the URLs to add to this sitemap + * @return this + */ + public THIS addUrls(U... urls) { + for (U url : urls) addUrl(url); + return getThis(); + } + + /** + * Add multiple URLs of the appropriate type to this sitemap, one at a time. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or write out one sitemap immediately. + * + * @param urls the URLs to add to this sitemap + * @return this + */ + public THIS addUrls(String... urls) { + for (String url : urls) addUrl(url); + return getThis(); + } + + /** + * Add one URL of the appropriate type to this sitemap. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or else write out one sitemap immediately. + * + * @param url the URL to add to this sitemap + * @return this + */ + public THIS addUrl(String url) { + U sitemapUrl; + try { + sitemapUrl = renderer.getUrlClass().getConstructor(String.class).newInstance(url); + return addUrl(sitemapUrl); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Add multiple URLs of the appropriate type to this sitemap, one at a time. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or write out one sitemap immediately. + * + * @param urls the URLs to add to this sitemap + * @return this + */ + public THIS addUrls(URL... urls) { + for (URL url : urls) addUrl(url); + return getThis(); + } + + /** + * Add one URL of the appropriate type to this sitemap. + * If we have reached the maximum number of URLs, we'll throw an exception if {@link #allowMultipleSitemaps} is false, + * or write out one sitemap immediately. + * + * @param url the URL to add to this sitemap + * @return this + */ + public THIS addUrl(URL url) { + U sitemapUrl; + try { + sitemapUrl = renderer.getUrlClass().getConstructor(URL.class).newInstance(url); + return addUrl(sitemapUrl); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @SuppressWarnings("unchecked") + THIS getThis() { + return (THIS) this; + } + + /** + * Write out remaining URLs; this method can only be called once. This is necessary so we can keep an accurate count for {@link #writeSitemapsWithIndex()}. + * + * @return a list of files we wrote out to disk + */ + public List write() { + if (finished) + throw new RuntimeException("Sitemap already printed; you must create a new generator to make more sitemaps"); + if (!allowEmptySitemap && urls.isEmpty() && mapCount == 0) + throw new RuntimeException("No URLs added, sitemap would be empty; you must add some URLs with addUrls"); + try { + writeSiteMap(); + } catch (IOException ex) { + throw new RuntimeException("Closing of streams has failed at some point.", ex); + } + finished = true; + return outFiles; + } + + /** + * Writes out the sitemaps as a list of strings. + * Each string in the list is a formatted list of URLs. + * We return a list because the URLs may not all fit -- + * google specifies a maximum of 50,000 URLs in one sitemap. + * + * @return a list of XML-formatted strings + */ + public List writeAsStrings() { + List listOfSiteMapStrings = new ArrayList(); + for (int start = 0; start < urls.size(); start += maxUrls) { + int end = start + maxUrls; + if (end > urls.size()) { + end = urls.size(); + } + StringBuilder sb = new StringBuilder(); + writeSiteMapAsString(sb, urls.subList(start, end)); + listOfSiteMapStrings.add(sb.toString()); + } + return listOfSiteMapStrings; + } + + private void writeSiteMapAsString(StringBuilder sb, List urls) { + sb.append("\n"); + sb.append("\n"); + for (U url : urls) { + renderer.render(url, sb, dateFormat); + } + sb.append(""); + } + + /** + * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. + * The sitemap index is written to {baseDir}/sitemap_index.xml + */ + public File writeSitemapsWithIndex() { + return writeSitemapsWithIndex(new File(baseDir, "sitemap_index.xml")); + } + + /** + * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. + * + * @return + */ + public String writeSitemapsWithIndexAsString() { + return prepareSitemapIndexGenerator(null).writeAsString(); + } + + /** + * After you've called {@link #write()}, call this to generate a sitemap index of all sitemaps you generated. + * + * @param outFile the destination file of the sitemap index. + */ + public File writeSitemapsWithIndex(File outFile) { + prepareSitemapIndexGenerator(outFile).write(); + return outFile; + } + + private SitemapIndexGenerator prepareSitemapIndexGenerator(File outFile) { + if (!finished) throw new RuntimeException("Sitemaps not generated yet; call write() first"); + SitemapIndexGenerator sig; + sig = new SitemapIndexGenerator.Options(baseUrl, outFile).dateFormat(dateFormat).autoValidate(autoValidate).build(); + sig.addUrls(fileNamePrefix, fileNameSuffix, mapCount); + return sig; + } + + private void writeSiteMap() throws IOException { + if (baseDir == null) { + throw new NullPointerException("To write to files, baseDir must not be null"); + } + if (urls.isEmpty() && (mapCount > 0 || !allowEmptySitemap)) return; + String fileNamePrefix; + if (mapCount > 0) { + fileNamePrefix = this.fileNamePrefix + mapCount; + } else { + fileNamePrefix = this.fileNamePrefix; + } + File outFile = new File(baseDir, fileNamePrefix + fileNameSuffix); + outFiles.add(outFile); + + OutputStreamWriter out = null; + try { + if (gzip) { + FileOutputStream fileStream = new FileOutputStream(outFile); + GZIPOutputStream gzipStream = new GZIPOutputStream(fileStream); + out = new OutputStreamWriter(gzipStream, Charset.forName("UTF-8").newEncoder()); + } else { + out = new OutputStreamWriter(new FileOutputStream(outFile), Charset.forName("UTF-8").newEncoder()); + } + + writeSiteMap(out); + out.flush(); + + if (autoValidate) SitemapValidator.validateWebSitemap(outFile); + } catch (IOException e) { + throw new RuntimeException("Problem writing sitemap file " + outFile, e); + } catch (SAXException e) { + throw new RuntimeException("Sitemap file failed to validate (bug?)", e); + } finally { + if (out != null) { + out.close(); + } + } + } + + private void writeSiteMap(OutputStreamWriter out) throws IOException { + StringBuilder sb = new StringBuilder(); + writeSiteMapAsString(sb, urls); + out.write(sb.toString()); + } - if (autoValidate) SitemapValidator.validateWebSitemap(outFile); - } catch (IOException e) { - throw new RuntimeException("Problem writing sitemap file " + outFile, e); - } catch (SAXException e) { - throw new RuntimeException("Sitemap file failed to validate (bug?)", e); - } finally { - if(out != null) { - out.close(); - } - } - } - - private void writeSiteMap(OutputStreamWriter out) throws IOException { - StringBuilder sb = new StringBuilder(); - writeSiteMapAsString(sb, urls); - out.write(sb.toString()); - } - } diff --git a/src/main/java/com/redfin/sitemapgenerator/W3CDateFormat.java b/src/main/java/com/redfin/sitemapgenerator/W3CDateFormat.java index 91c8ba3..d090945 100644 --- a/src/main/java/com/redfin/sitemapgenerator/W3CDateFormat.java +++ b/src/main/java/com/redfin/sitemapgenerator/W3CDateFormat.java @@ -32,7 +32,7 @@ import java.util.TimeZone; *
  • MILLISECOND: YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) * * - * Note that W3C timezone designators (TZD) are either the letter "Z" (for GMT) or a pattern like "+00:30" or "-08:00". This is unlike + *

    Note that W3C timezone designators (TZD) are either the letter "Z" (for GMT) or a pattern like "+00:30" or "-08:00". This is unlike * RFC 822 timezones generated by SimpleDateFormat, which omit the ":" like this: "+0030" or "-0800".

    * *

    This class allows you to either specify which format pattern to use, or (by default) to diff --git a/src/main/java/com/redfin/sitemapgenerator/package.html b/src/main/java/com/redfin/sitemapgenerator/package.html deleted file mode 100644 index 195e520..0000000 --- a/src/main/java/com/redfin/sitemapgenerator/package.html +++ /dev/null @@ -1,111 +0,0 @@ -How to use SitemapGen4j - -

    How to use SitemapGen4j

    - -SitemapGen4j is a library to generate XML sitemaps in Java. - -

    What's an XML sitemap?

    - -Quoting from sitemaps.org: - -

    Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site.

    - -

    Web crawlers usually discover pages from links within the site and from other sites. Sitemaps supplement this data to allow crawlers that support Sitemaps to pick up all URLs in the Sitemap and learn about those URLs using the associated metadata. Using the Sitemap protocol does not guarantee that web pages are included in search engines, but provides hints for web crawlers to do a better job of crawling your site.

    - -

    Sitemap 0.90 is offered under the terms of the Attribution-ShareAlike Creative Commons License and has wide adoption, including support from Google, Yahoo!, and Microsoft.

    -
    - -

    Getting started

    - -

    The easiest way to get started is to just use the WebSitemapGenerator class, like this: - -

    WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
    -wsg.addUrl("http://www.example.com/index.html"); // repeat multiple times
    -wsg.write();
    - -

    Configuring options

    - -But there are a lot of nifty options available for URLs and for the generator as a whole. To configure the generator, use a builder: - -
    WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
    -    .gzip(true).build(); // enable gzipped output
    -wsg.addUrl("http://www.example.com/index.html");
    -wsg.write();
    - -To configure the URLs, construct a WebSitemapUrl with WebSitemapUrl.Options. - -
    WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
    -WebSitemapUrl url = new WebSitemapUrl.Options("http://www.example.com/index.html")
    -    .lastMod(new Date()).priority(1.0).changeFreq(ChangeFreq.HOURLY).build();
    -// this will configure the URL with lastmod=now, priority=1.0, changefreq=hourly 
    -wsg.addUrl(url);
    -wsg.write();
    - -

    Configuring the date format

    - -One important configuration option for the sitemap generator is the date format. The W3C datetime standard allows you to choose the precision of your datetime (anything from just specifying the year like "1997" to specifying the fraction of the second like "1997-07-16T19:20:30.45+01:00"); if you don't specify one, we'll try to guess which one you want, and we'll use the default timezone of the local machine, which might not be what you prefer. - -
    -// Use DAY pattern (2009-02-07), Greenwich Mean Time timezone
    -W3CDateFormat dateFormat = new W3CDateFormat(Pattern.DAY); 
    -dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    -WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
    -    .dateFormat(dateFormat).build(); // actually use the configured dateFormat
    -wsg.addUrl("http://www.example.com/index.html");
    -wsg.write();
    - -

    Lots of URLs: a sitemap index file

    - -One sitemap can contain a maximum of 50,000 URLs. (Some sitemaps, like Google News sitemaps, can contain only 1,000 URLs.) If you need to put more URLs than that in a sitemap, you'll have to use a sitemap index file. Fortunately, WebSitemapGenerator can manage the whole thing for you. - -
    WebSitemapGenerator wsg = new WebSitemapGenerator("http://www.example.com", myDir);
    -for (int i = 0; i < 60000; i++) wsg.addUrl("http://www.example.com/doc"+i+".html");
    -wsg.write();
    -wsg.writeSitemapsWithIndex(); // generate the sitemap_index.xml
    -
    - -

    That will generate two sitemaps for 60K URLs: sitemap1.xml (with 50K urls) and sitemap2.xml (with the remaining 10K), and then generate a sitemap_index.xml file describing the two.

    - -

    It's also possible to carefully organize your sub-sitemaps. For example, it's recommended to group URLs with the same changeFreq together (have one sitemap for changeFreq "daily" and another for changeFreq "yearly"), so you can modify the lastMod of the daily sitemap without modifying the lastMod of the yearly sitemap. To do that, just construct your sitemaps one at a time using the WebSitemapGenerator, then use the SitemapIndexGenerator to create a single index for all of them.

    - -
    WebSitemapGenerator wsg;
    -// generate foo sitemap
    -wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
    -    .fileNamePrefix("foo").build();
    -for (int i = 0; i < 5; i++) wsg.addUrl("http://www.example.com/foo"+i+".html");
    -wsg.write();
    -// generate bar sitemap
    -wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
    -    .fileNamePrefix("bar").build();
    -for (int i = 0; i < 5; i++) wsg.addUrl("http://www.example.com/bar"+i+".html");
    -wsg.write();
    -// generate sitemap index for foo + bar 
    -SitemapIndexGenerator sig = new SitemapIndexGenerator("http://www.example.com", myFile);
    -sig.addUrl("http://www.example.com/foo.xml");
    -sig.addUrl("http://www.example.com/bar.xml");
    -sig.write();
    - -

    You could also use the SitemapIndexGenerator to incorporate sitemaps generated by other tools. For example, you might use Google's official Python sitemap generator to generate some sitemaps, and use WebSitemapGenerator to generate some sitemaps, and use SitemapIndexGenerator to make an index of all of them.

    - -

    Validate your sitemaps

    - -

    SitemapGen4j can also validate your sitemaps using the official XML Schema Definition (XSD). If you used SitemapGen4j to make the sitemaps, you shouldn't need to do this unless there's a bug in our code. But you can use it to validate sitemaps generated by other tools, and it provides an extra level of safety.

    - -

    It's easy to configure the WebSitemapGenerator to automatically validate your sitemaps right after you write them (but this does slow things down, naturally).

    - -
    WebSitemapGenerator wsg = WebSitemapGenerator.builder("http://www.example.com", myDir)
    -    .autoValidate(true).build(); // validate the sitemap after writing
    -wsg.addUrl("http://www.example.com/index.html");
    -wsg.write();
    - -

    You can also use the SitemapValidator directly to manage sitemaps. It has two methods: validateWebSitemap(File f) and validateSitemapIndex(File f).

    - -

    Google-specific sitemaps

    - -

    Google can understand a wide variety of custom sitemap formats that they made up, including a Mobile sitemaps, Geo sitemaps, Code sitemaps (for Google Code search), Google News sitemaps, and Video sitemaps. SitemapGen4j can generate any/all of these different types of sitemaps.

    - -

    To generate a special type of sitemap, just use GoogleMobileSitemapGenerator, GoogleGeoSitemapGenerator, GoogleCodeSitemapGenerator, GoogleCodeSitemapGenerator, GoogleNewsSitemapGenerator, or GoogleVideoSitemapGenerator instead of WebSitemapGenerator.

    - -

    You can't mix-and-match regular URLs with Google-specific sitemaps, so you'll also have to use a GoogleMobileSitemapUrl, GoogleGeoSitemapUrl, GoogleCodeSitemapUrl, GoogleNewsSitemapUrl, or GoogleVideoSitemapUrl instead of a WebSitemapUrl. Each of them has unique configurable options not available to regular web URLs.

    - - \ No newline at end of file